Andrew's Digital Garden

Tell, don't ask

The Tell, Don't Ask (TDA) principle suggests that it is better to tell an object a command to perform some operation or logic, rather than to ask for its state and then take some action as a result.

The principle doesn't always apply though - it's okay to query an object for its state provided that information isn't being used to make a decision related to that object. If it is related, that logic is better encapsulated in the responsibility of that object. It's especially problematic if this logic is repeated across the codebase, which violates the DRY principle.

Another consequence of violating TDA is that often magic numbers or business rules end up sprinkled throughout code that references object state, rather than embedded within the object itself or passed into the object as a defined and well-named construct

It's easiest to stay out of this trap by designing classes based on responsibilities, which naturally evolves into specifying commands that the class can execute, rather than queries that inform you on its state.

[[principles]]

Tell, don't ask