Tell, Do NOT Ask
Halloween is over and it is again time to get into serious business - welcome to Software Design Principles part 3: "Tell, Do NOT Ask".
Many developers who change from C to Java are used to C's procedural way of thinking - dividing the program execution into subroutines. Their code gets some input data and after that, the execution starts.
In object oriented (OO) design Encapsulation defines that a class is responsible of its own state - meaning the appropriate values of member variables. Other classes should not be interested how this data looks like, but that it behaves in a required way.
As an dummy example, we have a service that should change its state when enough data is collected. The backseat boys would develope it in an evil way with accessors and they would kill the encapsulation principle:
public void doSomethingWrong()
{
AnotherClass ac = new AnotherClass();
int returnValue = ac.getAnswer(); // ouch!
if( returnValue == 1 )
{
service.setReady();
}
}
Our function asked for other class' state and made choices based on the return value. Works, but all we produced was crap. If the code would require changing of the return type from int to something else, we would have to change code from all the locations that call the accessors.
The correct way would be to tell the object having the interesting data, to calculate its own state and tell it to the service:
public void doSomethingRight()
{
AnotherClass ac = new AnotherClass();
ac.setServiceState(); // do calculations and call the service.
}
CRC (Class-Responsibility-Collaboration) card is a brainstorming tool that can be used to help the thinking what classes are required for the OO-design. Take a small paper and divide it in three sections that describe the name of the class (Class), what the class' objects can do (Responsibility) and names of other classes that can talk to the current class (Collaboration). In the end we should have a small set of collaborations if the design goes well.
Until next time,
/markus

