Wednesday, July 20, 2011

The Roles of Classes in Object-oriented programming

It’s important to remember that although all classes are created in more or less the same way

in your code, they can serve different logical roles. Here are the three most common examples:

Classes can model real-world entities. For example, many introductory books teach

object-oriented programming using a Customer object or an Invoice object. These

objects allow you to manipulate data, and they directly correspond to an actual thing in

the real world.

Classes can serve as useful programming abstractions. For example, you might use a

Rectangle class to store width and height information, a FileBuffer class to represent a

segment of binary information from a file, or a WinMessage class to hold information

about a Windows message. These classes don’t need to correspond to tangible objects;

they are just a useful way to shuffle around related bits of information and functionality

in your code. Arguably, this is the most common type of class.

Classes can collect related functions. Some classes are just a collection of static methods

that you can use without needing to create an object instance. These helper classes are the

equivalent of a library of related functions, and might have names like GraphicsManipulator

or FileManagement. In some cases, a helper class is just a sloppy way to organize code

and represents a problem that should really be broken down into related objects. In

other cases, it’s a useful way to create a repository of simple routines that can be used in

a variety of ways.

Understanding the different roles of classes is crucial to being able to master object-oriented

development. When you create a class, you should decide how it fits into your grand development

plan, and make sure that you aren’t giving it more than one type of role. The more vague a

class is, the more it resembles a traditional block of code from a non-object-oriented program.


No comments :

Post a Comment