Pergunta

I've just recently started learning MVC patterns, originally in android but currently with spring MVC framework. I'm wondering if it is more appropriate to have testing/exception handling in the model or a controller. What I mean is, say I had some field in the model which should be restricted to some values, or a range of values; should I be testing the inputs and throwing exception in the model and having the controller catch them, or should the controller check inputs on it's own before forwarding inputs to the model?

My concern with testing in the controller is that I may need to check values in several spots whereas if I were to test in the model it's only done in one place. My concern with checking inputs in the model is that, for some reason, that seems really odd to me; then again I am new to this pattern so I don't really know yet.

What is the norm? What is recommended?

Thanks everyone

Foi útil?

Solução

It is appropriate to have testing and/or exception handling in the model and the controller, which ever is most appropriate to the handling of the exception.

For example, if you want want to parse a number from a string and use a default value when the string does not contain a number and you are parsing in the model, then you should handle the numberformatexception in the model. I think of this as an "expected" exception.

private String blammyValue;

public int getBlammyAsInt()
{
    int returnValue;

    try
    {
        returnValue = Integer.parseInt(blammyValue);
    }
    catch (NumberFormatException exception)
    {
        returnValue = -1; // some default value
    }

    return returnValue;
}

If the exception is something that is out-of-the-ordinary, like a database exception, and for which there is no reasonable default behavior, then catching it in the controller makes sense.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top