sobota, 21 stycznia 2012

Model logic

We all know that our models should be fat and controllers / views are supposed to be simple (dumb). Recently I was asked why such code should be put into model :


What's wrong with using Ad.unverified_ads.last in the view. I don't have an answer for the "why?" question often asked by beginner programmers. You can trust your more advanced colleagues that it should, that it is beneficial and will make your life easier or stick with your current way, wait until the application gets bigger, and regret it later. Anyway, I always ask myself one question when I have to decide whether something probably is part of the model. Would I need this method if the application had different way of interacting with the user. If it was a console application or just an API serving JSON to some clients. Given the previous code example. Can I image an usecase that requires me to display last unverified ad to user interacting with the program via command line. Yep, I can. Is it possible that I am gonna need it when serving JSON response? Might be. So I think I would make it part of the model.

How about this one:


Would I use it in CLI ? Nope. When rendering JSON ? Not really ? So... Not a model.

Third example:

I think it can be part of your model but does not have to. Even if this method could be useful in console application or for JSON api it looks like it still fits better in the presenter layer (or helper) instead of model layer.

I know that the examples are extremely simplified but that's not the point. When you are in doubt, just image that you would also have to implement the same app in completely different environment that has nothing to do with HTML. Which parts would you still keep in your model ? Asking myself such questions helps me make right decisions.