Thursday, September 25, 2008

Object orientation

I figured I would give my thoughts on my view toward object orientation and it's benefits. Also, why it makes a difference using an object-oriented programming language as opposed to a functional or procedural language.

I think a definition would serve its purpose here. What is object orientation? Object orientation in the context of software development is a practice that developers undertake in order to better represent abstractions. Notice I'm referring to the idea of object orientation and not the features that define an object-oriented programming language. You could, in theory, practice object orientation in a functional language. You would just need to implement the object-oriented language features using the language itself. Which doesn't gain anyone anything.

Lots of developers use functional languages today and there is absolutely nothing wrong with that it it is done right. Good design is good design. The C programming language has been around for decades and is going nowhere fast. It is cross-platform, fast, and relatively easy to program in.

C++ is the object-oriented C (an increment of C). It defines the object-oriented constructs necessary for C to be considered an object-oriented programming language. Enough of the history lesson already.

Class

The class lies at the very heart of object-orientation. The class classifies things. This makes sense in software because even when developing in a functional language, you are still implicitly modeling abstractions. For example, consider the following functional code that defines a user and some behavior that the user is capable of.

def create_user(user_name=None, password=None, is_active=None):
user={}
user['user_name']=user_name
user['password']=password
user['is_active']=is_active
return user

def is_user_active(user):
if user['is_active']:
return True

if __name__=='__main__':
user=create_user(user_name='test',\
password='123',\
is_active=True)
print 'Is the user active?',is_user_active(user)

Here we have a user abstraction that is very difficult to comprehend. Lets take a look at the equivalent object-oriented functionality.

class User:
def __init__(self, user_name=None, password=None, is_active=None):
self.user_name=user_name
self.password=password
self.is_active=is_active

def is_active(self):
return self.is_active

if __name__=='__main__':
user=User(user_name='test',\
password='123',\
is_active=True)
print 'Is the user active?',user.is_active()

Here, it is much more obvious that we are dealing with a user abstraction. In the main program, we actually create a user object. This object then encapsulates the user essence. That is, the behavior associated with the concept of a user is bound to that object. This is illustrated when we invoke user.is_active().

I'll continue this discussion as part two (or something like that) because I have much to say about other object-orientation topics.