1

I have an abstract class Employee that implements interface IEmployee and is further composed of abstract classes like EmploymentType. I have used Abstract classes, so as to avoid code duplication for common functionality among sub classes.

enter image description here

So I want to ask following questions:

  1. Does moving abstract methods from abstract classes to interfaces will improve the design?

enter image description here

  1. Secondly, Are Interfaces better than Abstract classes for big projects? The reason why I am asking this is because I have seen a lot of enterprise applications where interfaces are used a lot more than abstract classes. Which gives an impression that using interfaces is the right way to build enterprise applications.
Meena Chaudhary
  • 9,909
  • 16
  • 60
  • 94

1 Answers1

2

What common logic exists in your base abstract Employee class? I'd say any shared logic is probably trivial and probably could just be copied among the descendents (DRY isn't always necessarily the way to go). That way, you can just have an Employee interface, and one or more direct concrete ancestors, with some duplicated code in the constructors, getters and setters. It's arguably controversial but I've seen this approach preferred over and over.

EmploymentType and WorkLocation could be enums instead of classes, to avoid the arbitrary String fields. Perhaps WorkTime could also be an enum; I can't see it's structure in your UML. The hourlyPay field could be encapsulated in one of the enum types; I'm not sure where it best belongs with the information you've given.

On your general question about interfaces, see Effective Java by Joshua Bloch, Item 18 ("prefer interfaces to abstract classes"). Also the item "prefer composition to inheritance". Interfaces are simpler and more flexible from a design standpoint, and are particularly preferred for their testability. This is because if you have collaborators which are declared as instances of abstract classes, then they may contain logic which is hard to test (e.g. initialisation or additional dependencies). Collaborators declared as an interface type can be mocked 100%.

Ben Rowland
  • 361
  • 1
  • 5
  • When you say `interface are flexible from a design standpoint`, are you talking about their implementation or polymorphism? Also, the reason why I am thinking of moving methods from abstract classes to interfaces, so I can create a contract(design by contract) for my classes. And implement those methods in abstract classes to avoid code duplication. – Meena Chaudhary Dec 25 '15 at 16:43
  • 2
    Hi Meena, my comment about the flexibility of interfaces was due to several reasons: (i) a class can implement a number of interfaces but can only inherit from one abstract class, (ii) it's easier to make an existing class implement a new interface and harder to make an existing class (which may exist within a hierarchy) extend an abstract class. – Ben Rowland Dec 25 '15 at 17:45