Monday, May 7, 2012

A Misconception Of Object Oriented Programming

I was reading another object oriented programming blog earlier and read in a comment that they didn't understand why anyone in their right mind would use OOP and said that it lacks real world objects.  He or she then began to say why with an example.  He or she said that you can have a person class, a worker class which inherits the person class, and then a student class that also inherits the person class.  He or she then began to state that now you cannot have a student who is also a worker.  They said it's impossible. 

Why is this impossible?  This is the exact reason to use object oriented programming.  The person class should have a PersonID which is a unique value.  Why can't a worker class and a student class point to the same person?  I think their problem was how they were perceiving the data.  Obviously, the worker can't be of the same type as the student.  When you grab data (from a database in my example) you would most likely would be grabbing a specific type.  You would either have tables that holds workers and students or you would have a Person sub table that would be able to hold additional or multiple types.  Below is an image of the second description in how it would look.

The PersonType table simply points a person to a type.  The type then points to a worker or a student.  It could someday point to hundreds of other types.  If you need to get all workers data then you can do so by ensuring the TypeID in the PersonType table has the description of "Worker" or whatever you want to use.  You would then create the instance of the worker class that inherits from the PersonID.  The beauty of this being object oriented is now if you make a change to the person in the worker table, it will automatically be updated to the person in the student table.

Again, I believe they were having trouble imagining this in their head.  Yes, you can't have two objects that are of different types as one type.  You're not ever supposed to.  A Ferrari is not an F-150.  They can't be and aren't supposed to be.  A worker is not a student.  A student is not a worker.  A person who works CAN be a person who is a student and a person who is a student CAN be a person who is a worker.  I don't give grades to workers and I don't think any college would plan on paying any student a salary.

No comments:

Post a Comment