andreoss
andreoss

Reputation: 1820

Does `instanceof` operator violate Liskov Substitution Principle?

For example I have Currency, and Exchange which deals with various implementations of Currency. I want to have an extra rate for curtain currencies, I do it like so

interface Currency { double rate();}
interface Exchange { double convert(Currency currency, double money); }
class PrivateBank implements Exchange {
    @Override
    public double convert(Currency currency, double money) {
        double extra_rate = 1.0;
        if (currency instanceof CanadaDollar) { /// ?
            extra_rate = 1.05;
        }
        return money * currency.rate() * extra_rate;
    }
}

Is LSP violated here?

Upvotes: 3

Views: 681

Answers (3)

Rolbin
Rolbin

Reputation: 133

The above is called "potential violation of LSP" . Any instance check to identify the subtype of a Supertype is considered as a potential violation.

The implementation should not differ for different subtypes. In your case there is no conflict other than just a different value. But still this can be fixed by having a function or value to return exchange rate rather than checking the subtype and setting it.

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 181149

No. The Liskov Substitution Principle is about subtypes faithfully exhibiting all the properties of their supertypes. In no way does it forbid other code from handing different subtypes of the same type differently.

Your example code is a bit smelly, but not because of any conflict with the LSP.

Upvotes: 1

Daly
Daly

Reputation: 879

No, because any implementation of Currency can be passed in to convert and a result will be returned.

Upvotes: 1

Related Questions