artima.com

Chapter 1 of API Design
The Object
Guideline 2. See objects as bundles of behavior, not bundles of data
by Bill Venners

Part 7 of 21

Objects as Bundles of Services

Now, you may say that this is obvious. That I was simply factoring out duplicate code into a single method that everyone calls. That's true, but when you perform an object-oriented design, you in effect perform this code-to-data refactoring ahead of time.

During a object-oriented design's initial stages, you discover objects. You assign each object an area of responsibility and flesh out the services each type of object should provide. Finally, you design the interfaces through which objects provide their services to clients. In the process, you move code to data.

For example, you might decide to include in your solution a Matrix object responsible for matrix mathematics. As you flesh out the details, you decide that the Matrix class should handle matrix addition, matrix subtraction, and scalar and matrix multiplication. You then design an interface through which the Matrix can fulfill its responsibilities, such as the interface of the service-oriented Matrix class. By discovering the service-oriented Matrix in the initial design phase, rather than starting with the data-oriented Matrix and later refactoring towards the service-oriented Matrix, you in effect move code to data during the design process.

Moving code to data can yield objects that seem counterintuitive to beginners. In Guideline 1, I mentioned that object-oriented programming enables you to think more in terms of the problem domain. However, what you might do to an object in the real world, you often ask an object to do to itself in an object-oriented program. For example, in the real world you might multiply a matrix by -1, but in an object-oriented program, you might instead ask a Matrix object to multiply itself by -1. The reason you ask a Matrix to multiply itself is because matrix multiplication involves matrix data. Therefore, the code that represents the matrix multiplication know-how belongs in the class that holds the matrix data, the Matrix class itself. Although it may seem counterintuitive to ask a Matrix to multiple itself by -1, a Test to grade itself, or a String to trim white space off of itself, such requests are normal in object-oriented systems.

Part 7 of 21

API Design | Contents | Book List | Printer Friendly Version | Previous | Next

Last Updated: Friday, April 26, 2002
Copyright © 1996-2002 Artima Software, Inc. All Rights Reserved.
URL: http://www.artima.com/apidesign/object7.html
Artima.com is created by Bill Venners