Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In order for the state pattern to work, the context object has to expose an interface that the state classes can use. At a bare minimum this will have to include a <code>changeState(State)</code> method. This I'm afraid is just one of the limitations of the pattern and is a possible reason why it is not always useful. The secret to using the state pattern is to keep the interface required by the states as small as possible and restricted to a tight scope.</p> <p>(1) Having a <code>canChangeQuantity</code> method is probably better than having all states implement a <code>setQuantity</code>. If some states are doing something more complex than throwing an exception, this advice may not follow.</p> <p>(2) The <code>setState</code> method is unavoidable. It should, however, be kept as tightly scoped as possible. In Java this would probably be Package scope, in .Net it would be Assembly (internal) scope.</p> <p>(3) The point about validation raises the question of when you do validation. In some cases, it is sensible to allow the client to set properties to invalid values and only validate them when you do some processing. In this case each state having an 'isValid()' method that validates the whole context makes sense. In other cases you want a more immediate error in which case I would create an <code>isQuantityValid(qty)</code> and <code>isPriceValid(price)</code> that would be called by the set methods before changing the values, if they return false throw an exception. I've always called these two Early and Late Validation and it is not easy to say which you need without knowing more about what you are up to.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload