Search code examples
javaexceptionobserver-pattern

Use observer pattern ot throw exceptions in model


Is it more likely to use the observer pattern in Java to handel for example game rules like in some simple games or just throw exceptions to handel these in the UserInterface classes?

Each time an user clicks onto a button on the UserInterface, this controller just delegates this action to the model with the data in it. The model decides whether the data is correct compared to some game rules or just throw exceptions to handle this in the controller and react on each custom exception. E.g. (in model class; don't need to show you the corresponding controller class):

Observer Pattern with PropertyChangeListener and PropertyChangeSupport:

public void setPlayerNames(ArrayList<String> playerNames) 
{
    if(playerNames.size() == 0)
       propertyChangeSupport.firePropertyChange("pleaseEnterAtLeastOnePlayerName);
    else
       startGame();
}

And with some custom exceptions in the model:

public void setPlayerNames(ArrayList<String> playerNames) throws NoPlayerException
{
    if(playerNames.size() == 0)
       throw new NoPlayerException();
    else
       startGame();
}

Which of these methods complies more to the MVC paradigma?


Solution

  • The first one uses a PropertyChangeListener to fire events that have nothing to do with property changes. Using an event-based model to implement validation doesn't look very intuitive or easy to use.

    The second one throws an exception to signal an illegal argument. Using IllegalArgumentException is the best way to signal such a problem. But it should be done only to protect the model from entering into an invalid state, not to implement validation. The controller should check the validity of the list before passing it to the model.