Friday, February 18, 2011

What are some important aspects of Object Oriented Design?

I see this a lot in job descriptions and programmer interview questions; "what are the 3 pillars of OOP?"  The first thing you should know is that no two interviewers will agree on any 3 "pillars" of OOP.  But you can start with...

An interface is an ideal thing.  It describes what a thing does, but doesn't bother to elaborate on how it does that thing.  For example, an automobile moves.  An interface doesn't need to know the details of how the automobile moves, but in order for anything to be an automobile, it must move.

A class is a concrete thing.  It provides the implementation of the ideal.  A car is an automobile.  It's easy to see that a car moves, and most people can agree on how a car moves.

One can say that a car is an automobile, but an automobile is not a car.  This is a common mnemonic you can use to determine contravariance (the ability to convert from a narrow type to a wider type).  If you can say that a thing is-a some other thing, then you are describing contravariance in object-oriented design.

Try it out: an arm is-a limb, but a limb is-not-an arm.  Pizza is-a food, but food is-not-a pizza.  Using is-a can help you understand what your ideal object is, and what your concrete object is.

So, back to these important aspects.

Encapsulation.  This is the practice of hiding data by restricting its access to accessors and mutators.  Accessors might be implemented as properties or a get-style functions.  They act as mechanisms to say "you can touch this data, but you have to do it through these knobs & levers.

Abstractions.  A mechanism that is often useful for dealing with complexity.  If you've ever met someone who responds to every problem with a metaphor or proverb, they are using an abstraction.  Using the car/automobile example from above, it can often be easier to solve a problem when looking through the lens of the automobile abstraction rather than trying to fix a car.

Inheritance.  There are three primary relationships in OOP.  Is-a, which we talked about before.  Has-a is used to express composition.  A garage has-a car, or is-composed-of a car.  Uses-a describes a relationship where an object depends on the existence of another object.

Polymorphism.  One name, many forms.  Polymorphism is how object-oriented programmers can shift the lens to look at an object from another angle.  For example, you can look at an arm from the angle of left arm, arm, limb, or organ.  Each form might share some properties just as each form might have its own specific abilities.  A left arm might have a different style of hand, but any arm will have a very similar tricep or bicep.

So do some browsing on your own.  There's so many other people who want to tell you what they think of OOD, it would be a shame if you didn't get several perspectives while developing your own.

No comments: