Managing Complexity

As you all can well imagine by now, things can get pretty hairy and complicated when trying to program. What we need to fix this are ways to keep programs from getting too complex to write and understand. We have seen that we can use functions for control, but what do we do about the data? What can we do to keep our data in an orderly fashion? Let's try objects.

Objects

Objects can be described as:

Example: circles

So far we have been using circles in the context of QuickDraw and now we are going to use them to help us understand how objects work.

  //Draw a circle centered at (300,200) with radius 75.
  Rect r;
  SetRect(&r, 300 - 75, 200 - 75, 300 + 75, 200 + 75);
  PaintOval(&r);

Now how would we manipulate ths circle??

As can be seen things are not as clear cut as they should be. To use this circle you have to know that it is stored as a Rect. But think about this: Do you have to know how many valves per cylinder your car has in order to drive it? The obvious answer is no, so why should you have to know how a circle is stored?

Object Ideas

One thing we can do is encapsulate together all the data needed to describe an object and all the functions that will operate on it. Another good idea would be to abstract the object's interactions with the outside world so that you need to know as little as possible about how the object is really implemented in order to use it.

For our circle:

Data to describe Functions that operate on it

Only these functions should access the data unless we give explicit permission to other functions.

See Demo circles1.cpp

Things to note about circles1.cpp

It is easy to change or add member functions.

See Demo circles2.cpp for additional member functions to move and scale a circle.

A Counter Object

A counter has data:

A counter also has functions:

See Demo counter1.cpp

Note the hidden assumption in the counter::show() function: the counter has at most 2 digits.

To Index Previous Next