Construct classes from the outside in
When experimenting with the design of a new class, it's very helpful to approach the task from the point of view of the caller :
- the quality of the final design will be higher, since there is more feedback from use cases
- the class is often constructed significantly faster, since discovery of poor design decisions usually happens much earlier
- make your best guess
- find and fix the errors
- repeat
Constructing a non-private method from the outside in might involve these steps :
- write some code from the point of view of the caller
- make the code compile by providing a simple stub implementation of the method you are designing. For a void method, such a stub is simply an empty method. For a method which has a return value, such a stub might simply return null, 0, false, or an empty String.
- experimenting with different designs is simple at this point, since the amount of calling code is minimal, and the implementations are toys
- correctness of method name and return type are determined by the needs of the caller
- correctness of arguments seems to be determined more by the needs of the implementation, not the caller
- is the return type correct? This is an important item, since changes in return type will often have large ripple effects in the caller.
- is the method intelligible at the point of call?
- when the design is more or less stable, write the javadoc of the method as the formal specification of the contract between the method and its callers. Often, this will also help clarify details and border cases.
- finally, replace the stub implementation with a real implementation, and test it
See Also :
Use a testing framework (JUnit)
Use javadoc liberally
Separate public and private members
Design by Contract
Use javadoc liberally
Separate public and private members
Design by Contract
Would you use this technique?
|
|