Does GWT's ActivityMapper violate the Liskov Substitution Principle?

会有一股神秘感。 提交于 2019-12-08 03:25:46

问题


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).



来源:https://stackoverflow.com/questions/8368684/does-gwts-activitymapper-violate-the-liskov-substitution-principle

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