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
- 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?
- Have switch OR if clauses for each special part in the class file? And then pa开发者_开发技巧ss some variable to the class?
- Some other option?
This is probably a trivial question, but I am quite new to java and can't quite figure it out.
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.
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.)
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!
精彩评论