Could someone please explain what does Refused Bequest means?
I tried reading some articles and says its a kind of code smell or in wiki it tells that it is a class that overrides a method of a base class in such a way that the contract of the base class is not honored by the derived class.
But in a nutshell or in a more simple terms, what is it actually?
I think you get it. Refused Bequest is a code smell. But, what type of code smell? Quoting Martin Fowler's book Refactoring: improving the design of existing code:
Subclasses get to inherit the methods and data of their parents. But
what if they don't want or need what they are given? They are given
all these great gifts and pick just a few to play with.
You have a subclass, that inherits from a parent class, but the subclass does not need all behaviour provided by the parent class. Because of that, the subclass refuses some behaviour (bequest) of the parent class. That's why this is a code smell.
Update answering @catzilla's comment:
If you don't have the opportunity to read the book (I totally recommend it), at least you have the SourceMaking page that describes it pretty well.
About a code example, let's try. Let's imagine we have some classes to compute a person's taxes. We could have a class that computes government taxes:
class Government {
protected double computeBaseTax() { //... }
protected double addPersonalTax(double tax) { //... }
public double getTax() {
double tax = computeBaseTax();
return addPersonalTax(tax);
}
}
Then, we could have a class that computes the amount of money a company has to pay as taxes. For whatever reason, we realized this class can reuse the addPersonalTax
method, but not computeBaseTax()
. And taking a bad decision, we decided that our Company
class would inherit from Government
.
class Company extends Government {
private double computeInitialTax() { //... }
@Override
public double getTax() {
double tax = computeInitialTax();
return addPersonalTax(tax);
}
}
Ok, the problem could be solved in a better way (overriding computeBaseTax()
method) but I'm trying to ilustrate that Refused Bequest is a code smell that happens when we inherit from a base class and some functionality provided is refused.