Refining the Window Classes

Consider the behavior of the scroll bar more closely. If the user clicks on either end, the text moves one line in the appropriate direction. If the user clicks on either side of the slider, the text moves one page in the appropriate direction. (We'll ignore dragging on the slider itself.)

This is a fairly complex set of responses for a window to perform. Moreover, a window might have two scroll bars, one vertical and one horizontal, which requires a lot of repetition in the code for responding to a mouse click. Instead of making a window responsible for scroll-bar behavior, you can make scroll bars a separate class. A text window is thus responsible for interpreting mouse clicks on the text, while a scroll bar is responsible for interpreting mouse clicks on its surface. Objects of these two classes interact to perform text scrolling.

What information does a ScrollBar object maintain? It knows its size, but what about its position? Suppose it knows its absolute position on the screen. With such a design, consider how you would move a scrollable window. Not only would you update the window's position attributes, you'd also have to update the attributes of both scroll bars. This is an example of giving an object too much information about its context. By knowing its absolute position, ScrollBar is implicitly aware of the position of the window containing it. Instead, let ScrollBar store only its relative position, as an offset from the corner of the window containing. With this distribution of information, moving a window requires updating only the window's position attributes.

How is ScrollBar related to the classes already defined? It has a number of similarities to the Win class: it knows its size and relative position, and it can display itself and respond to mouse clicks. You can factor out this common behavior, place it in a base class, and make scroll bars and text windows derived classes.

Thus, the fundamental entities in our program are not text windows but something more primitive. This new class represents a screen area that interacts with the user as a logical unit, so call it Interactor. It should be an abstract base class, since there's no such thing as a generic interactive area. A Win is an Interactor, and so is a ScrollBar.

The Interactor class is an example of a class that wasn't among the original candidates classes, but was created after examining the attributes and behavior of the candidates. The class represents an entity that wasn't immediately evident in the description of the program. The class hierarchy is shown in Figure 10.2.

Remember that this is only the first approximation of the window class hierarchy, and that it may change as you design the classes in more detail.