design patterns - Using Antipattern in Object Oriented Java -


after reading interesting article, have few questions around this. please refer common pitfall #8: pretending java more c (i.e. not understanding oop) on [zero-turn-around]

i agree authors solution pitfall. face similar issue code (abuse of instanceof). cannot implement code author has suggested. scenario below

  1. i have jms messaging bus.
  2. messages float around system. listener typically listen messages.
  3. all messages have single parent imessage.
  4. i use instanceof distinguish between messages.
  5. the listeners typically domain specific business logic.

if agree authors solution, have implement domain specific business logic in message classes, think bloat light-weight message objects. not that, have many references (composition) in message objects think unfair message objects have business (domain) behavior in it.

what reasonable solution problem? example code below

public void onmessage(imessage mssg) {      if(mssg instanceof mopn){        ...     } else if(mssg instance of mozn){        ...     } else if(mssg instance of moln){        ...     } } 

one reasonable solution creating listeners know work specific type of message.

here interface.

interface messagelistener<m extends imessage> {     void onmessage(m message); } 

here skeleton of 1 of classes:

class moznlistener implements messagelistener<mozn> {     public void onmessage(mozn message) {     } } 

now can create mapping between messages , listeners. can use properties file, hard coded map, annotations. you. once have can implement 1 jms message listener looks like

class messageentrypoint implements messagelistener {     public void onmessage(message message) {         getmessagehandler(message).onmessage(message.getobject());     } } 

now system extandable. no instanceof. introduce new message type have create appropriate class implements imessage , listener supports it.

btw more comments.

  1. using i mark interface not java-style.
  2. i not familiar domain , name mopn self-explainable you, imho not. try use more self explainable identifiers.

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -