Tell Don’t Ask Principle

reported-ordersWhen working with an Object Oriented Programming (OOP) language, we design our classes based on their responsibility, following the Single Responsibility Principle (SRP) of course. We are able to use encapsulation to add behavior within these classes, unlike Procedural Programming (PP). The readability of the application components can be improved this way. Alec Sharp wrote about this topic:

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.

Am I saying that OOP is better than PP? Absolutely not, these are two different paradigms and it is important to remember this. I personally started with the procedural aspects, in C and I moved to OOP with C++ and after that I switch to C#. When I started C++ and the Object Oriented programming it was not as easy as it is now, it was a whole new “world”.

This is where the Tell Don’t Ask principle becomes handy. This principle helps you remember that you should design your components by focusing on their behavior and by hiding their internal working using encapsulation technic.

I have created an example of a component as an example to this principle. We will first take a look at the “ask” version and then we will see the “tell” version. This example is about a payment system that debit a wallet for a giving amount.

Ask version

public class Wallet
{
    public int OwnerId { get; set; }
 
    public int Balance { get; set; }
}
 
public class PaymentService
{
    public void DebitCustomer(int amount, int customerId)
    {
        var wallet = WalletRepository.GetWalletByCustomerId(customerId);
        if (wallet.Balance < amount)
            throw new Exception("Not enough funds.");
 
        wallet.Balance -= amount;
    }
 
    public void CreditCustomer(int amount, int customerId)
    {
        var wallet = WalletRepository.GetWalletByCustomerId(customerId);
        wallet.Balance += amount;
    }
}
 
public static class WalletRepository
{
    public static Wallet GetWalletByCustomerId(int customerId)
    {
        // Simulation of a query to data storage
        return new Wallet
        {
            Balance = 200,
            OwnerId = customerId
        };
    }
}

In this version my “Wallet” class is only a “data holder” and does not have a single piece of logic. It is the PaymentService that do all the work and “ask” the wallet if it has enough money to continue the operation. And it is the same service that update the wallet balance, it is not necessary the kind of behavior we might want in our application.

Now imagine that some customers are allowed to have a negative balance. In this case I do not want to throw an exception and I need to add a new condition in the DebitCustomer method.

public class Wallet
{
    public int OwnerId { get; set; }
 
    public int Balance { get; set; }
 
    public bool IsOverdraftAllowed { get; set; }
}
 
public class PaymentService
{
    public void DebitCustomer(int amount, int customerId)
    {
        var wallet = WalletRepository.GetWalletByCustomerId(customerId);
        if (wallet.Balance < amount && !wallet.IsOverdraftAllowed)
            throw new Exception("Not enough funds.");
        wallet.Balance -= amount;
    }
 
    public void CreditCustomer(int amount, int customerId)
    {
        var wallet = WalletRepository.GetWalletByCustomerId(customerId);
        wallet.Balance += amount;
    }
}

I had to modify both the Wallet class and the PaymentService class. I end up with a lot of wallet related logic in my payment service where it should only focus on debiting and crediting customers.

Now, it is time to see the tell version.

Tell version

public class Wallet
{
    public int OwnerId { get; private set; }
 
    public int Balance { get; private set; }
 
    public bool IsOverdraftAllowed { get; private set; }
 
    public Wallet(int ownerId, int balance, bool allowOverdraft)
    {
        OwnerId = ownerId;
        Balance = balance;
        IsOverdraftAllowed = allowOverdraft;
    }
 
    public void Debit(int amount)
    {
        if (Balance < amount && !IsOverdraftAllowed)
            throw new Exception("Not enough funds.");
        Balance -= amount;
    }
 
    public void Credit(int amount)
    {
        Balance += amount;
    }
}
 
public class PaymentService
{
    public void DebitCustomer(int amount, int customerId)
    {
        var wallet = WalletRepository.GetWalletByCustomerId(customerId);
        wallet.Debit(amount);
    }
 
    public void CreditCustomer(int amount, int customerId)
    {
        var wallet = WalletRepository.GetWalletByCustomerId(customerId);
        wallet.Credit(amount);
    }
}
 
public static class WalletRepository
{
    public static Wallet GetWalletByCustomerId(int customerId)
    {
        // Simulation of a query to data storage
        return new Wallet(customerId, 200, true);
    }
}

In this version, we can see that the payment service is much “cleaner” and it only focuses on its responsibility, nothing more. All the wallet logic has been moved to the Wallet class, where it belongs. And I used encapsulation to “protect” this class against unintentional uses, only the wallet instance can update its balance amount.

Tell Don’t Ask to save bandwidth

Now imagine that you have a class that act as a client for a service (like in WCF) and it calls a remote endpoint to perform a certain operation if it is available. I create the following piece of code as an example in the “ask” way.

public class RemoteService
{
    public bool IsOperationAvailable()
    {
        // some logic
        return true;
    }
 
    public void DoOperation()
    {
        // some operations
    }
}
 
public class Client
{
    public void CallRemote()
    {
        var service = new RemoteService();
        if (service.IsOperationAvailable()) // network latency here
            service.DoOperation();          // network latency again
    }
}

Even it the code does not look that “dirty”, I highlighted the issue in the comments. The client has to make two calls to the service in order to perform the desired operation. This has an effect on the application performance. In this case the “ask” approach clearly needs to be avoided.

The “Tell” approach

public class RemoteService
{
    private bool IsOperationAvailable()
    {
        // some logic
        return true;
    }
 
    public void DoOperation()
    {
        if (!IsOperationAvailable())
            return;
        // some operations
    }
}
 
public class Client
{
    public void CallRemote()
    {
        var service = new RemoteService();
        service.DoOperation();      // network latency only here
    }
}

I just made a slighty change to the code, now the client always tell the service to perform the operation and the service checks itself if the operation is available or not. This way I was able to reduce the number of calls on the network for my application without removing any functionalities.

You might wonder why I put an example like this one, that looks obvious. Simply because I have seen a similar example in a real world application. This way I wanted to show you the importance of the Tell Don’t Ask principle in some cases.

The Tell Don’t Ask principle helps you focus on the behavior of your classes and the functionalities you want them to expose. Remember that you don’t have to ask your components about their state in order to do an operation, just tell them to do it.

I hope you liked this presentation of this principle, as always, do not hesitate to share/comment/give your opinion.

See you next time!


Image credits:

https://www.englishclub.com/grammar/reported-orders.htm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s