Interfaces Should Reveal Intention
Kristen Nygaard, father of object oriented programming and the Simula programming language focused in his lectures on how to use objects to model the behavior of the real world and on how objects interacted to get a piece of work done. His favorite example was Cafe Objecta, where waiter objects served the need of hungry customer objects by allocating seating at table objects and interchanging menu and order objects to fulfill each others needs.
In this type of model we will find a restaurant object with a public interface methods such as
reserveTable(numberOfSeats,customer,timePoint), availableTables(numberOfSeats,timePoint), object interfaces reviling each objects intent and responsibility in terms of the domain of a restaurant. So, where are the setters and getters so often found dominating our object models?
They are not here as they do not add value to the behavioral intention and object responsibility. Some might then argue that we need setters to deal with frameworks such as Spring, for the purpose of supporting dependency injection. The answer to that is that you do not need setters for that. Either you use the constructor or you create an interface in an appropriate package called
SpringInjections with methods prefixed with
initializeSomeVariable(). Again your intention of the interface has been made public and clear.
So what about the getters? I think personally you are better of just referring to the actual variable, using methods such as
price(), name() and timePoint(). Methods with a return variable are by definitions some sort of a getter and the code reads better.
The conclusion on this is that setters and getters are alien constructs that do not reveal the intention of a behavior centric interface, and therefore you should avoid using theme.
TO BE COMPLETED
By Einar Landre
This work is licensed under a Creative Commons Attribution 3
Back to 97 Things Every Programmer Should Know home page