Tell, don’t Ask

The most languages i develop in these days are OOP (Object Oriented Programming) languages and i try to use the SOLID-principles as much as possible.

The first principle in SOLID is the Single Responsibility Principle (SRP), which states that a class should have only one reason to change. In other words, it should only have one responsibility.

The “Tell, don´t ask” principle is a good rule of thumb when it comes to SRP. Rather than asking an object for data and acting on that data, we should instead tell an object what to do. This will move behavior into an object that is maintaining the data.

This makes it easier to maintain and to test.

Imagine the following code where we “ask” for data:

The MonitorThreshold class is just a dataholder with properties. To validate if a new CurrentThreshold is less or equal to MaxThreshold we need to handle that in the MonitorService.

If i need a MinThreshold property i have to modify both MonitorThreshold and the MonitorService classes, and that does not comply with the single responsibility principle. Also, as you can see, the testing of this will be very cumbersome.

Instead we “tell” the MonitorThreshold what to to. Like this.

This makes the MonitorThreshold class easy to test and it will also comply with the single responsibility principle. Adding a property of MinThreshold and use that in the validation will not affect any other class.

Leave a Comment

Your email address will not be published. Required fields are marked *