This is a simple question about the way inheritance should be used.
Consider that I have to provide business logic to print foo and bar and I have hierarchy of two classes: one that has functions to print only foo and another that extends first and has functions to print bar. In both classes, I have a method named as necessaryMethod()
that takes responsibility to call those methods that prints foo and bar.
The way I implemented it in two approaches:
First approach is let base class do some stuff and derived class take advantage of it. The second approach is let base class not do any stuff (only providing implementation) and put all responsibility over derived class.
Consider the following code:
Approach 1:
public class A{
protected void necessaryMethod(){
callFoo();
}
protected void callFoo(){
System.out.pritln("foo");
}
}
public class B extends A{
@Override
protected void necessaryMethod(){
super.necessaryMethod();
callBar();
}
protected void callBar(){
System.out.println("bar");
}
}
public class FooBarClass{
public static void main(String args[]){
B b = new B();
b.necessaryMethod();
}
}
Approach 2:
public abstract class A{
protected abstract void necessaryMethod();
protected void callFoo(){
System.out.pritln("foo");
}
}
public class B extends A{
@Override
protected void necessaryMethod(){
calFoo();
callBar();
}
protected void callBar(){
System.out.println("bar");
}
}
public class FooBarClass{
public static void main(String args[]){
B b = new B();
b.necessaryMethod();
}
}
Which approach would be nice for maintainability of and readability of code (in the context of large software products/ big class hierarchy; this is just an example)? or Which approach you would choose and why?
Aucun commentaire:
Enregistrer un commentaire