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
Much of design is summed up simply as:
-
make your best guess
-
find and fix the errors
-
repeat
The critical step seems to be the second. The best techniques are those
which discover the errors the fastest. Coding "from the outside in"
seems to perform very well in this regard.
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
In effect, such techniques use the programming language itself as a design tool.
See Also :