Where should I put validation code?

Posted by D Lawson on Stack Overflow See other posts from Stack Overflow or by D Lawson
Published on 2010-03-11T17:53:14Z Indexed on 2010/03/11 18:04 UTC
Read the original article Hit count: 198

Filed under:
|
|
|

I'm creating interfaces and abstract classes that represent a messaging framework for short text-based messages like SMS, email, twitter, xml, etc.. and I was wondering where I should put the message validation code.

The thing is that I am only writing the superclasses and interfaces, so I'm not putting the actual implementation in, I'll just put the hooks in that allow others to validate the content of the messages. The way I see it, I could do it several ways:

  • in the abstract superclass "Message", have an abstract method 'isValid'. A variation on this would be to have isValid be called when the Message constructor is called, throwing a MalformedMessageException if the message is formatted incorrectly.

  • in the transport layer, immediately before sending, validate the message. I would have a send(Message) method that calls an isValid(Message) method immediately before it sends.

  • have a singleton message validator with a static method isValid(Message) that is called at some point.

I'm sure there are other options that I'm missing. Currently, I'm leaning towards the first one, but it doesn't feel right to me to have validation code in what should be a domain object.

© Stack Overflow or respective owner

Related posts about message

Related posts about validation