Thursday, October 22, 2009

Section 14.4. States in Software










14.4. States in Software







If you're a software developer, you're probably wondering when you'll ever need to model the operation of a CD player or coffeemaker. In software, state diagrams model an object's life cycle, or the states it goes through during its lifespan. Figure 14-12 shows the life cycle of
an AccountApplication object as it passes from pending to approved or rejected and then to finalizing.



Figure 14-12. The life cycle of an AccountApplication object



State diagrams are useful for modeling an object that behaves differently depending on its state. Considering an AccountApplication object, calling the complete( ) method when the object is in the pending state wouldn't make sense if the finalizing state performs wrap-up behavior, such as creating the blog account if approvedit would first have to know whether the application was approved. State diagrams are an effective way to make this information explicit.


If an object has a simple life cycle, then it's not worth modeling its life cycle with a state diagram. For example, a ContactInformation object that stores an Author's contact information and doesn't change states other than being created and destroyed probably doesn't warrant a state diagram.


If you're wondering what an object's states would look like in codethe AccountApplication class could have a status attribute and the states shown in Figure 14-12 could be possible values of status. transitions occur when methods on the AccountApplication object are invoked. See Chapter 4 for a review of how an object's state is captured in its attributes.



State diagram are also heavily used in certain software niches, such as first-person shooter (FPS) games. In FPS games, state machines are used to model game character states. For example, a game character, such as a troll, could have the states Neutral, Attack, Panic, and Die, as shown in Figure 14-13. When the troll is in the Attack state, he is performing behavior, such as unsheathing his sword or charging his opponent (that's you). Triggers causing a state change include seeing an opponent or receiving a blow from the opponent.



Figure 14-13. State diagram modeling a troll in a FPS game; the troll's behavior is determined by his state













No comments: