« Hardware relax | Main | Parrot »

Where to put you validation

Yesterday I saw a question by fREW Schmidt regarding where to place the validation code in your apps. I made a mental note to answer it, but as most of my mental notes, it was quickly forgotten.

Today, a new article describes the answer he got. In the end he decided to put the validation inside the model. I can only say: good for you.

But one of the reasons against the validation-inside-the-model that he received baffled me: Models don’t know about the current user (or other higher level information).

If your models don't know who is the person authenticated (and please read Yuval article about modelling identity to understand how complex it can become), then you are doing it wrong.

Models must know who is the authenticated user. They must know it because that is the only sane way to implement authorization inside your methods, and to generate a audit log of operations.

What I usually do is to create a Session class. For each request (be it Catalyst request, incoming email message, or XMPP request), I create a new Session instance initialized with the current user information plus some tidbits like channel (Web, email, XMPP) and IP address (if available).

Then all accesses to my API are either via the session object (create methods to access most important parts of your API), or by passing this session object to the API you are calling.

You should also use your Session as the access point to your logging and auditing capabilities.

The article mentions other issues like error messages. I haven't add the necessity of developing an application with multiple language support yet, but I think that the current throw-exception-objects strategy, with all the information (including the authorized user to figure our preferred language) will be able to deal with the problems that I can think of now.

In the end, I'm actually really curious about why would people think that putting your validation code in the controllers is a good idea.

Update: a lot of stuff in the comments if you care about this topic.

Contacts

melo@simplicidade.org (XMPP/email)
+351 302 029 050 (voice)
melopt (Skype)

IronMan challenge

Iron Man badge Are you ready to be an Iron Man? Join the challenge and find out! (what is the meaning of this little man?)

Moosaico

Junta-te!

Recent Comments

Powered by Disqus
Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 3.2