Next: Coding. Up: Fraction class example. Previous: None.


Design

Today we're going to look at an extended example of defining a class, to get a better feel for how the design process works. We'll define a class to represent a fraction. This class is actually included in the csbsju.cs160 library, almost exactly as presented here.

We begin our task by asking ourselves the question: What are the properties of a fraction? That is, what does an individual fraction need to ``remember''? In the case of a fraction, we reason, there are two properties of which we need to keep track: the numerator and the denominator. We're going to make the decision right now that we'll always store a fraction in reduced form - 2/4 will be remembered as 1/2, for example.

One decision that we'll make right now is that a fraction will be immutable - once created, its properties won't change. If we want a different fraction, then we'll have to create a brand-new one anew.

We also ask ourselves: What must a fraction ``do''? That is, what methods do we need to implement? There are a several things we might want to do to a fraction.

It's also useful to define two Fraction constants ZERO and ONE: Our reason for making these constants is similar to the red and black constants in the Color class: We will tend to want to refer to them often, and it would be nice if we don't have to create a new instance to do this.


Next: Coding. Up: Fraction class example. Previous: None.