Search This Blog

Tuesday, May 18, 2010

But Sometimes Ask

As a followup to my previous post, the book Growing Object-Oriented Software Guided by Tests makes the point that you can't always tell sometimes you do have to ask.

Some reasons for asking include

  • getting information from values and collections

  • using a factory to create new objects

  • asking objects about their state when searching or filtering


When asking though it is important not to expose the internal structure of your object. For example instead of this code


carriage.getSeats().getPercentReserved() < percentReservedBarrier


Try this.


carriage.hasSeatsAvailableWithin( percentReservedBarrier )


The method hasSeatsAvailableWithin asks the question you really want answered instead of asking for the information to help you figure out the answer yourself. Or in other words you write a query that describes the intention of the calling object not just the implementation. Doing this moves the behavior to the most appropriate object, gives it an explanatory name, and makes it easier to test.

No comments:

Post a Comment