What is a Refused Bequest?

孤街浪徒 提交于 2019-12-10 01:36:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28271150/what-is-a-refused-bequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!