![]() |
Sponsored Link •
|
Advertisement
|
Designing objects for flexibility and robustness
Why should you care about designing good objects? One reason is that a
set of robust objects can help contribute to the overall robustness of
the program they constitute. In addition, well designed objects are
more flexible (easier to understand and easier to change) than poorly
designed objects.
A fundamental way to make your object designs robust and flexible is by ensuring that your objects have a valid state, and experience only valid state transitions, from the beginning of their lifetimes to the end. The rest of this article will discuss ways to ensure that classes begin their lifetimes with a valid state.
Introducing class CoffeeCup
and the virtual café
The discussion of object design in this and subsequent articles will
make use of a class that models coffee cups. You can imagine using this class
in a program that implements a "virtual café": a place in cyberspace where
guests can sit at small tables, sipping virtual cups of coffee and chatting with
one another. The primary function of the café is that of a chat room, where
people separated by (potentially vast) physical distances yet
connected to the same network come together to converse. To make
your chat room more compelling, you want it to look like a café.
You want each participant to see graphical representations
("avatars") of the other people in the café. And, to
make the participants' experience more real, you want the people to be
able to interact with certain items in the café, such as tables,
chairs, and cups of coffee.
The CoffeeCup
The basic CoffeeCup
class has one instance variable,
innerCoffee
, which keeps track of the number of
milliliters of coffee contained in the cup. This variable maintains your virtual
coffee cup's state. The following methods allow you to change its state by:
add()
method)
releaseOneSip()
method)
spillEntireContents()
method)
Here is a class that represents a simple coffee cup in a virtual café:
// In Source Packet in ex1/CoffeeCup.java class CoffeeCup { private int innerCoffee; public void add(int amount) { innerCoffee += amount; } public int releaseOneSip(int sipSize) { int sip = sipSize; if (innerCoffee < sipSize) { sip = innerCoffee; } innerCoffee -= sip; return sip; } public int spillEntireContents() { int all = innerCoffee; innerCoffee = 0; return all; } }
Sponsored Links
|