Why do we use Base classes in Java
While doing a desing/framework it is a usual practice to have a Base Class for Value Objects, Services, DAOs etc. For example if we create a new VO, it extends from that BaseVO. If we create new DAO, it should extend from Bas开发者_如何学编程eDAO. What is the reason why we have such a base class?
Answer is obvious ;) Because it's easy to add common functions or logic application-wide.
For instance if you always want to store creation date and modification date for your value objects. Or provide helper methods to get database connection in services.
Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics of object-oriented programming. Inheritance (inheriting the base class) enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.
It is easy to add common methods and properties to the base class. But that's not the correct way for all the cases. Design patterns (like Strategy Pattern) uses above mentioned OOP concepts to do real designing.
I have heard a sentence once and quote it here:
small programs
have a funny way of getting bigger quickly
.
As the project get bigger and bigger you need it to be more flexible and tangible. Therefore making services and business logic loosely coupled we avoid the object to be dependent on other implementations.
An example for what the BaseDAO could do for all its subclasses would be setting up or retrieving the connection to the database. It would be pretty unnerving to put the same code in the AppleDAO, PearDAO and BananaDAO (in case what you want to store in your DB is Apple, Pear and Banana).
If you put the code for getting the DB connection into all of them, you would have to change all of them, e.g. when your database host changes. If it's in the superclass, you only have to change it in one place.
It is a good practice to have a mother class, such that behaviors and data members applicable to all the sub child may be shifted up the inheritance tree.
For example:
Object toString();
BaseDAO will consists of common methods that will be used across successor classes, or you can also define an abstract method that has to be implemented as a behavior that all extended class should have.
There's certain functionality or fields that sometimes need to be preserved when extending frameworks. Let's take a simple example. If we have an Animal with a name and the ability to speak (yes school example but bear with me) then anything that is an animal should have those things. So say we have a cat, obviously the Cat doesn't say the same thing as a Dog so while both of these have the ability to Speak() they give 2 different results.
In your case it also makes for extensible and interchangable systems so that you can swap out layers without having to rewrite large portions of code (sometimes you don't even have to change anything at all).
精彩评论