12 October 2014

OOPS question:On interface design implementation

When you go for an interview it’s almost certain that interviewer will ask “what is the difference between abstract class and an interface”. Upon answering this, the questions usually go deeper to know more about your understanding of interfaces.

Let’s go through such one question on interface designs.

Say you have one interface called "IBankAccount". From this interface, you have derived two classes. These classes are "ChildAccount" and "AdultAccount". The UML class diagram for this is below:

UML class diagram showing Interface design and implementation

Question: Now if you want to add one more method "WithdrawWithNoLimit()" to "AdultAccount" class how would you design it? Do you alter your "IBankAccount" interface?

Most of us think, let's add the new method "WithdrawWithNoLimit()" to "IBankAccount" interface. With this change the UML class diagram looks like below:

UML class diagram showing Interface design and implementation

But the above design approach has one big disadvantage. For no reason, the "ChildAccount" class end up in implementing the new method "WithdrawWithNoLimit()" and throwing the "System.NotSuuportedException" exception. With this design, the number of methods in a single interface is increasing and this is referred as "Fat interface". This is usually not good design.

Now let's think of another design approach. How about creating one more interface called "IPrivilegeBankAccount" and moving the new method "WithdrawWithNoLimit()" inside this. Then the "AdultAccount" class can derive from the new interface. And in this approach there will be no changes to the class "ChildAccount"; This design follows the "Open Close" SOLID design principle as well.

This new design UML class diagram is below:

UML class diagram showing Interface design and implementation

We need not stop here on improving the interface design. I believe depending on requirements the design can even further be improved. So comments are welcome!.

No comments:

Post a Comment