Monday, June 23, 2014

OOP : When to prefer an Abstract Class and Interface


Abstract classes allow you to provide default functionality for the subclasses.

Why is this extremely important though?
If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class.

Because you can make a change to it and all of the inheriting classes will now have this new functionality.

If the base class keep on changing and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if it's just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.

As per my personal experiences, frameworks is a good place to show when and where to use both an abstract class and an interface.

Another general rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class.

An Example of this would be something like a business rules engine. This engine would take in multiple BusinessRules as classes perhaps? Each one of these classes will have an analyze function on it.

public interface BusinessRule{
     Boolean analyze(Object o);

This can be used ANYWHERE. It can be used to verify the state of your application. Verify data is correct. Verify that the user is logged in. Each one of these classes just needs to implement the analyze function, which will be different for each rule.

Where as if we were creating a generic List object, the use of abstract classes would be better. Every single List object is going to display the data in a list in some form or another. The base functionality would be to have it go through its data provider and build that list. If we want to change that List object, we just extend it, override our build list function, change what we want and call super.buildList();

In Brief: interfaces means you are just defining a list of functions and that abstract classes has the option of providing default functionality.

No comments :