Pattern: Tell, don't ask (but sometimes ask)

January 31st, 2021

 

Tell, don't ask

 

Model: Law of Demeter

Objects make their decisions based only on the information they hold internally or that which came with the triggering message; they avoid navigating to other objects to make things happen.

 

this style produces more flexible code because it’s easy to swap objects that play the same role.

 

why?

  • information hiding

  • flexible code

  • forces us to name the interactions between objects

 

But Sometimes Ask

“ask”

when getting information from values and collections,

or when using a factory to create new objects.

Occasionally, we also ask objects about their state

when searching or filtering

 

ask the question, not the information

 

(src: Book: Growing Object Oriented Software, Guided By Tests - Steve Freeman & Nat Pryce)