Monday, November 17, 2008

Why use object oriented programming…2

In my previous post, I’ve written how OOP resolves basic issues such as

• Functional Clutter
• Problem with Global Variables
• Unmanageable associations

Apart from these OOP has other powerful features, namely Inheritance and abstract classes. In this blog I’m going to discuss what these terms mean and why are they so useful.

We all know the common book definition of inheritance, but why is it so useful?
Basically inheritance is used when you have to

1) Modify the behavior of the object
2) Add additional features to the existing class

To modify the behavior all you gotta do is inherit the parent class into a new class called the base class and override the necessary methods. Take the example of JLabel in swing. The text in the label is rendered onto the screen by calling the paint method. Suppose you wanted to change the way border is shown, you have to override this method which is in turn called by swing framework to render the label.

To add additional features to the label, you have to inherit it into the base class and write additional methods for enabling new features. The base class now contains all the previous functionality that lets keeps it compatible with the existing framework.

Inheritance is essentially like copying and pasting all the code within the parent class into the base class. So why not copy and paste the code manually? I.e. copy code in class A to Class B instead of inheriting.

Just imagine what would happen if class A is modified later on as a result of bug fix or enhancement. You’ll have to re-copy all the code from class A to class B, thereby hampering the code manageability. Moreover inheritance lets you reuse the well designed and tested classes you’ve already made.

What’s more, inheritance also helps you debug the code. Suppose class A, B, C, D inherits class E. If there is a problem in classes A to D then it’s probable that the code in class A is buggy. If class A is buggy then it’s probable that the new code you’ve added is buggy. It may seem like a small thing but believe it or not, about 70% of development time is wasted in debugging and maintenance.

Abstract classes…Inherit benefits of Inheritance

Suppose there are a lot of things in common between the two classes (A and B), i.e. you notice some sort of code redundancy, but there are also many marked differences between them at the same time. Furthermore the redundant code cannot be grouped within a single class as it doesn’t make any sense. If you come across this kind of a situation, you could put all that redundant code in an abstract class (X) and make then create the other two by inheriting the abstract class. This kind of model is blessed with the benefits of inheritance. In short it Inherit benefits of Inheritance ?

Abstract classes don’t have an instance, i.e. it’s not possible to create an object without implementing the abstract methods. Simply make the class specific methods, the ones used by classes A and B as abstract. Sounds like Greek and Latin? Let’s consider an example.

Yesterday I was trying to make a class that can add the ‘trail period’ feature to any software. To do this I’ll have to –

1) Record the date when the software is first used.
2) Whenever the software is started, check the current date with the start date and evaluate the difference
3) If the difference is greater than say 30 days then prompt the user to enter the serial key.

To record the start date there can be two possibilities.

1) Save the data in an encrypted form within a file.
2) Save the data in an encrypted form within a database in case of a distributed application.

So you make two classes, DBValidator and NonDBValidator. Both of then contain redundant code…i.e. the logic that checks the date difference, a fraud detection system to see if the user tampers with the system date etc etc…The only point of change is the way in which the start date is persisted onto a storage medium.

In this scenario you could create an abstract class called validator with all the redundant code and make the persistDate method abstract.

Classes DBValidator and NonDNValidator inherit the validate class by implementing the abstract method persistDate, each one defining their own persistence logic.

Why go through this entire headache? Read the inheritance part again. This helps in centralizing the changes that may be required. You just have to make a change at a particular common place (the parent) and the necessary updates are forwarded to all the base classes.

Today’s software development standard is not about writing logical code, anyone can do that today. Instead more emphasis is laid on writing code that is better managed, even if you’ll have to compromise on the logic part. This is probably one the reasons as to why they look for people with work experience. Anyone involved in big projects would’ve certainly faced this problem before. This is also the reason why frameworks such as hibernate, JSF, struts are so popular in spite of the high learning curve involved.

Now that the basics of OOP is laid out, in my next post I’ll discuss about UML diagrams. I hope this article was useful.

Monday, November 10, 2008

Why use Object Oriented Programming…

Do you get this feeling, “why use classes and objects un-necessarily when functions can achieve the same in a simpler manner?” If yes, this article is for you. It took me about 3-4 months to fully realize the potential of OOP over structural paradigm. The only way you’ll realize the importance of OOP is when you write big code, I mean BIG, around 50K lines or so.

Here’s the scenario, consider yourself as a topnotch programmer who has written about 50,000 lines of code :) , say you’ve written some utility functions (around 800 of em) and have packaged them in a library.

Why does big code gets messy and un-manageable??

Problem 1…Functional clutter

From the usage point of view, the person using your library will probably be confused will all the functions you’ve provided (they’re about 800!!!) and moreover they have to remember all the parameters to the function, its behavior etc…

Ex- funcA(param1, param2, param3)
Param1, param2 are numbers…
Param3 can take values 1,2,3

1 would mean that the function will add param1 and param2…
2, 3 means it’ll perform multiplication and division

The whole point is that it’ll get real tough to remember the functions and its behavior, parameter’s when there are too many of them. Furthermore not all of the functions are of utility value. What I mean is that there will be some functions that are used by other utility value functions.

Ex - funcA() uses funcB() and funcC() to do its tasks. The end user is only concerned with funcA and not with funcB and funcC.


Problem 2…The headache of global variables

The usage of global variables is the most annoying thing for me. It’s very easy to confuse a global variable with a local one or vice-versa. Also tracking the usages of global variables is considerably difficult. It also increases dependencies between the functions.

Ex-

int x; //(global variable)

void func1()
{
//Uses global var x (reads and modifies)
}

void func2()
{
//Uses global var x (reads and modifies)
}


In this case, there exists a dependency between func1 and func2 indirectly via global variables…

How?
If in the future, you’ve found some bugs in func1 and corrected…it might as well affect func2 as they share the same global variable (dependency).

Problem 3…Unmanageable Associations

Consider a game consisting of 300 circles which are moved randomly (say). Every circle has three status variables associated with it.

x, y coordinate and the radius.
Here’s how your code would work.


loop
{
//Clear screen
//Draw all circles by reading their respective status variables
//Update the positions of all the circles by updating the status variables,
//using some logic
}


The thing is that there are three variables with each circle…So that makes it 300 * 3 variables

You’ll probably end up naming variables as
Int x1, y1, r1, y2, r2….x300, y300, r300

What if there are more objects in the game, like clouds, trees etc (even more status variables). All of this makes the code look messy and also makes the associations harder. You’ll soon start confusing which function operates on what and which variable is associated with an object (circle in this case)

So what are the solutions to these issues? If you think about it’ll almost seem obvious.

Solution to problem 2 & 3

In the world of OOP objects form the building blocks of the code. Suppose you’re coding a game, just think of any sprite (something that’s rendered onto the screen) as an object.

An object is just like any other real world entity.

- It has certain attributes or properties associated with it. In case of the circle consider its status variables as its attributes.

- Has certain operations associated with it. You could have associated an operation (function) ‘move()’ with the circle object that would randomly alter its attributes. Also a function called ‘draw()’ can be added to render the circle onto the screen.

Now there’s no more confusion…All the variables and operations are ‘encapsulated’ within an object


Circle (class or prototype of an object)
--------------------------------------
(Attributes)
--------------------------------------
Int x
Int y
Int radius
--------------------------------------
(Operations)
--------------------------------------
Move()
Draw()
--------------------------------------

Class is just a template; an object on the other hand is an instance of the class having its own attributes.

Moreover there is no longer a menace of global variables as all the attributes (variables) are encapsulated within classes.

Solution to problem 1


To avoid the confusion all the related functions and shared global variables could be encapsulated within a class.
Ex- Suppose you have some functions that perform certificate auth, encryption, decryption etc…You could combine (associate, encapsulate) them all in a class named security. Make all the shared global variables its attributes.

As far as the utility of the function is concerned, OOP introduces access modifiers such as public, private etc…

Make the real utility valued functions as public. The supporting functions can be made private so that they cannot be accessed directly from the object.

This is only the beginning (yea, I know it’s a movie dialog). You haven’t tasted the real power yet. Apart from the issues I discussed, the key strength of OOP is in inheritance and abstraction.
I’ll discuss more about those in my next post. I hope this article was useful.