Java – OOP :What are some of the situations in which class based design is better than interface based one

architectural-patternsdesignjavaobject-oriented

I was reading JDOM's website.

Why is the JDOM API defined in terms of concrete classes rather than interfaces?

Jason Hunter summarizes the arguments against an interface-based API for JDOM:

With interfaces everything becomes a factory, elements have to be 'imported' into new documents instead of just added, features like long-term serialization cannot be guaranteed, and the list goes on.

We started with interfaces actually. During our pre-release review to some peers we received the feedback we should try concrete classes. We did, and the design was much better for it.

I am a beginner designer. All the advice I have heard about till now is advising against using designing with concrete classes.

May be using concrete classes are appropriate in certain places. Are there any common class problems for which using concrete classes in design is okay?

Best Answer

  • Inheritance creates dependencies on implementation, which might be a big problem regarding maintainability. The corollary of this is that you can safely use inheritance and concrete classes when dealing with data transfer object, which by definition contain almost no implementation. You can also use inheritance of concrete classes when you want this dependency. You might want to use an abstract class containing the common methods (usually utility functions) at the the top of the hierarchy in this situation.
  • When using a concrete class hierarchy, do not forget to apply the Liskov Substitution Principle.
  • There is no problem with using concrete classes for clients (i.e. classes that uses, not classes that are used).
  • IMHO you can use concrete classes until there are things to change. The Open/Closed Principle would tell you to use interfaces to avoid coupling, but regarding the You Ain't Gonna Need It Principle you might consider using concrete classes until the moment when you need to change something in the implementation. The problem is that you would have to change every client of your classes the first time something changes somewhere. While you only have one possible tool to do something, you can use concrete classes IMO.

[EDIT] JDOM's website takes java.io.File as an example, but this is definitely an interface based design as one can manipulate a java.io.File instance as if it were only a Serializable. In this situation only "creators" would know the concrete class

Related Topic