13.8. Composition

Once a class is defined, the goal is to use it as a model programmatically, embedding this object throughout your code, intermixing use with other data types and the logical flow of execution. There are two ways of utilizing classes in your code. The first is composition. This is where different classes are mingled with and into other classes for added functionality and code reusability. You may perhaps create instances of your class inside a larger class, containing other attributes and methods enhancing the use of the original class object. The other way is with derivation and discussed in the next section.

For example, let us imagine an enhanced design of the address book class we created at the beginning of the chapter. If, during the course of our design, we created separate classes for names, addresses, etc., we would want to integrate that work into our AddrBookEntry class, rather than have to redesign each of those supporting classes. We have the added advantages of time and effort saved, as well as more consistent code—when bugs are fixed in that same piece of code, that change is reflected in all the applications which reuse that code.

Such as a class would perhaps contain Name and Phone instances, not to mention others like StreetAddress, Phone (home, work, telefacsimile, pager, mobile, etc.), Email (home, work, etc.), and possibly a few Date instances (birthday, wedding, anniversary, etc.). Here is a simple example with some of the classes mentioned above:

						class NewAddrBookEntry:         # class definition
  'new address book entry class'
  def __init__(self, nm, ph):    # define constructor
     self.name = Name(nm)        # create Name instance
     self.phone = Phone(ph)      # create Phone instance
     print 'Created instance for:', self.name

The NewAddrBookEntry class is a composition of itself and other classes. This defines a “has-a” relationship between a class and other classes it is composed of. For example, our NewAddrBookEntry class “has a” Name class instance and a Phone instance, too.

Creating composite objects enables such additional functionality and make sense because the classes have nothing in common. Each class manages its own namespace and behavior. When there are more intimate relationships between objects, a more elegant solution is the concept of derivation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset