Instanceof At Layer Boundaries

We're told that use of instanceof is a CodeSmell. But we're also told that a FourLayerArchitecture is the way to structure systems. How do we prevent use of instanceof at layer boundaries - especially between the application and domain layers? I see a lot of things like: if object is of this type, show this corresponding form, etc. Just a thought...


Use polymorphism. That's what it's for. In particular, you're not usually looking for a specific type as much as you are a particular behavior. So you may choose to have yor domain objects implement things like "String formType()" that returns a generic name that might correspond to a form class. Your Form Generator could then use an if statement to look that up, or look it up in a HashMap of keys to Form types read from a file.

Another option is to use double-dispatch. For instance, a Form generator sends "getDisplay()" to the domainObject. The DomainObject sends "displayFor(self)" back to the Form generator. The Form Generator has a bunch of displayFor() methods each overridden for a particular domain object type. That returns the display type, that is then returned back to the domain object message and thus back to the Form generator. --KyleBrown


EditText of this page (last edited August 29, 2001) or FindPage with title or text search