1

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?

Jason
  • 7,356
  • 4
  • 41
  • 48

1 Answers1

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

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • 1
    Upon more reading, I guess violating the LSP depends on whether or not you can break a client by having it call this method with a subclass. And this seems to actually be the intent of the mapping method, so in this case maybe an if/else cascade of instanceof's isn't automatically a violation of LSP. Thanks for mentioning the Visitor Pattern... there seems to be more discussion of implementations of this method [here](http://stackoverflow.com/questions/5802747/eliminating-gwt-activitymapper-boilerplate). – Jason Dec 04 '11 at 19:50