-->

Does GWT's ActivityMapper violate the Liskov S

2019-05-30 09:41发布

问题:

In my GWT application, I have a class like so:

public class AppActivityMapper implements ActivityMapper {

    @Override public Activity getActivity(Place place) {

        if(place instanceof ThisPlace) {
            return new ThisActivity((ThisPlace)place);
        }
        if(place instanceof ThatPlace) {
            return new ThatActivity((ThatPlace)place);
        }
        if(place instanceof AnotherPlace) {
            return new AnotherActivity((AnotherPlace)place);
        }
        // you get the idea
    }
}

The ActivityMapper, Activity, and Place objects are part of the framework, and the interface implies that this is how it was meant to be used.

However, according to the Liskov Substitution Principle, a method that accepts a type but does a type check for subclasses to infer what action to take is a violation of the principle.

Is GWT's ActivityMapper interface by nature encouraging a violation of the LSP? Or is there another LSP-compliant way to code that method that I haven't thought of?

回答1:

The role of the ActivityMapper is to map a Place to an Activity, where the rules for the mapping are left entirely free.
What makes for that kind of if/else cascade is that Java doesn't support multiple dispatch, but in my opinion it doesn't mean it's violating the LSP (or at least, well, you have no other choice in Java, so it's a non-issue; you could use a visitor pattern –that's what Spring Roo generates– but that doesn't change much things).