Mika Vatanen
Mika Vatanen

Reputation: 4017

How to reuse a single class within multiple projects, with minor modifications in functionality?

I have a common library where I've put classes that are used between multiple Android projects. However, now I encountered a situation where I have to make minor changes to the functionality of the class in one project. How should I organize the classes, keeping in mind easy readability of code and future extension possibilities?

Should I

  1. Extend the class (MyClass) with modifications that are special to the subproject (MyClassSub extends MyClass)? What about if I have references to MyClass in the library classes, but in this special subproject MyClassSub should be called?
  2. Have switch OR if clauses for each special part in the class file? And then pass some variable to the class?
  3. Some other option?

This is probably a trivial question, but I am quite new to java and can't quite figure it out.

Upvotes: 1

Views: 296

Answers (3)

JAL
JAL

Reputation: 3319

Unfortunately the answer is "it depends."

Specifically, a class hierarchy should be designed such that the behavior of the base class holds for all subclasses of the class. One way to look at this is to say that the subclass may expand the behavior of the base class. The corollary is that a subclass should not restrict the behavior of the base class. So a Square IS NOT A Rectangle.

Also consider "favor composition over inheritance" unless the base class is specifically designed for inheritance, as a change to the base class might BREAK the subclass.

Have fun!

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

If the new functionality is specific to the one project, I would avoid putting the functionality in the library. Go with a subclass or a replacement class. If later you find that this extended behavior is more widely usable, you can migrate it to the library (perhaps creating an entire new version of the library, much in the same way that the Java API evolves.)

Upvotes: 1

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

Definately 1.

Create a library (jar) containing the base class, and then use that jar in the projects that need its base functionality. Each project should provide the specialized class that extends the base.

Upvotes: 2

Related Questions