Tuesday, 3 November 2020

OOP Tell dont ask and SRP


Tell dont ask and SRP seem to be conflicting principles, one says to make the object do the work and the other says that each object should only change for one reason (meaning it must be responsible for 1 logical part). So how do we design our programs to conform to both of these principles when an object theoretically does more than one thing?

Protected state, released state

Tell don't ask is actually about querying the state an object, making a decision on that queries state, and then changing the state of that object. So its not saying that you can't query the objects, but just that state changes must happen from within. In relation to Commands and Queries, Queries cannot change the internal state or release write-access to any of the internal state which fits with the tell don't ask principle.

Creating tiny objects

The SRP is about making each object do one thing, it is self explanitory in that a single object must have a defined singular purpose. Often it requires a very high level of granularity which can be found by using very specific bounded contexts e.g. namespaces/nested classes.

Well formed objects, well formed designs

We can combine both together by recognizing that the Tell-Dont-Ask does not mean that you cannot query data from it. So we can create small, axiomatic objects that can be queried by other small objects for the information they need.

Shopping for an objects interface

One problem is that its hard to decide what should be exported by the object and what shouldn't. There are many opinions on how it should be done, but, i find that Bertrand Meyers explanation is most mathematically sound. https://richardbamford.blogspot.com/2020/10/commands-queries-and-side-effects.html . The subject is huge and there are hundreds of sources of information from everywhere!

No comments:

Post a comment

The difference between class and object.

 The difference between class and object is subtle and misunderstood frequently. It is important to understand the difference in order to wr...