The State Machine Compiler - SourceForge

1y ago
7 Views
3 Downloads
760.23 KB
83 Pages
Last View : 1m ago
Last Download : 2m ago
Upload by : Elisha Lemon
Transcription

TheState Machine CompilerbyEitan SuezUptoData, Inc.http://u2d.com/

About the SpeakerEitan Suez is a Java programmer living and workingin Austin, TexasEitan is primarily known as the author of ashkelon,an open source tool for Java API documentationEitan is an active member of the Austin Java UsersGroupEitan maintains a weblog on http://java.net/2

Primary Purpose1. In General:To learn how Finite State Machines (FSMs)are useful for modeling stateful objectsin a software system2. Specifically:To learn to implement such objectsin a clean and agile wayusing the State Machine Compiler3

AgendaA. Uncle Bob’s TurnstileB. Finite State Machines BasicsC. What is SMC?D. Solving Turnstile using SMCE. SMC In DetailF.Examples4

A simple turnstileDescription of the normal operation of aturnstile:1. Turnstile initially locked2. A coin or ticket is inserted (event)3. Triggers action: turnstile unlocks4. A person passes through turnstile (event)5. Triggers action: turnstile locks again5

State Diagrampass/lock()LockedUnlockedcoin/unlock()6

Complete nlock()7coin/thankyou()

Coding the turnstilebreak into hands-on session8(first pass)

DiscussionMost implementations don’t think to separateactions into neat little packages:alarm / thankyou / unlock / lockSo, the first improvement is to go ahead andperform this packaging:1. put the code for each case in a separate method (theaction)2. gather the collection of actions into an interfaceThis helps with action code getting in the way of seeingthe transition logic9

More IssuesDifficult to clearly interpret conditionallogic. It’s difficult to read; you can get lostin it. It’s error-prone.Violates the Open-Closed Principle (OCP).Extending the system requires modifyingexisting code.10

Let’s try the State Pattern (second pass)break into hands-on session11

The State PatternReplace conditional logic by using polymorphismThe context class becomes much simpler; itdelegates transitions handling to its current state.The code is cleaner.12

DiscussionIf you need to extend the system, say youneed to introduce a new state:you add a new classyou don’t have to touch existing codeThe state pattern respects the OCP:software entities should be open for extension butclosed for modification13

Issues with the State Pattern1. The state logic is distributed across anumber of classes, and so there’s no singleplace to see it all2. Tedious to write14

The state of affairsEmploying the state pattern is usually as far as mostpeople goState diagrams are typically used only passively, inour designs, and to help us understand the statelogicLet’s go back to our diagram and discuss someFinite State Machine (FSM) basics.15

AgendaA. Uncle Bob’s TurnstileB. Finite State Machines BasicsC. What is SMC?D. Solving Turnstile using SMCE. SMC In DetailF.Examples16

Basic TerminologyStates,Transitions, and coin/unlock()Transitions17coin/thankyou()Actions

Other ConceptsEntry and Exit ActionsActions performed every time we enter and exit astate, respectivelyTransition GuardsConditions that must be met in order for transitionsto proceed18

Transition Guard ExampleForm Entry:Fill out a form (in "Edit" state)The "Submit" event (or transition) essentiallycontains a guard condition.If the form was not completed correctly (invalid),then we will remain in edit mode and have tomake correctionsConversely, if the guard condition is true (theform is valid), then we will proceed withtransition to "Read" state/mode.19

Transition TablesA common mechanism for describingtransition diagrams clearly in text formFor each state, we write out:the transitionwhat the next state will bewhat action to perform (if any)20

Transition table for turnstileStateTransitionNext lockedthankyoupassLockedlockLockedUnlocked21

AgendaA. Uncle Bob’s TurnstileB. Finite State Machines BasicsC. What is SMC?D. Solving Turnstile using SMCE. SMC In DetailF.Examples22

SMCSMC is a toolthat mates FSMs with Objects23

SMC(continued)An open-source project hosted n by and maintained Charles Rapp24

SMCEssentially:“you put your state diagram in one file using aneasy-to-understand language. SMC generates theState Pattern classes for you.”25

SMC HistorySMC is Robert Martin’s invention (it is discussed inRobert’s book Agile Software Development (Ch 29))Charles Rapp happened to have succeeded Robertat Clear Communications Corporation.He added many features, made design revisions, andopen-sourced the project (more information in thepreface of the SMC manual on sourceforge).26

AgendaA. Uncle Bob’s TurnstileB. Finite State Machines BasicsC. What is SMC?D. Solving Turnstile using SMCE. SMC In DetailF.Examples27

Where were we?Ah yes. Issues with the State Pattern1. The state logic is distributed across a number ofclasses, and so there’s no single place to see it all2. Tedious to write(Notice: there’s nothing wrong with the design from thepoint of view of the runtime implementation)28

The .sm fileOne place to see it all%class Turnstile%package turnstile%start MainMap::Locked%map MainMap%%Locked{coin Unlockedpass nil}Unlocked{pass Locked {coin nil{}%%{ unlock(); }{ alarm(); }lock(); }thankyou(); }29

The CompilerGenerates the State Pattern codejava -jar Smc.jar -java -d turnstile Turnstile.smThe SMC CompilerSpecify java language outputOptionally specify target directorySpecify the .sm file to process30

t.javaA single file is produced, but it contains many classes:TurnstileContext MainMap.classTurnstileContext MainMap Default MainMap Locked.classTurnstileContext MainMap Default MainMap Unlocked.classTurnstileContext MainMap Default.classTurnstileContext TurnstileState.classTurnstileContext.class31

Write the AppClassDefine and instantiate “fsm”context class (generated)Expose transition calls toother parts of application, ifnecessaryImplement (or delegate)actions32

The AppClassThe term “AppClass” in SMC refers to a class youwrite that is designated to interact with theContext class that SMC generatesThe actions you specify are assumed to be methodsdefined in the AppClass33

t.java uses uses Turnstile.java(the AppClass)34

The big pictureAbstractions interface ITransitions interface IActionsDetailsAppClassContextAppClassThe context class invokes actions on the AppClass.Conversely, the AppClass invokes transitions on the Context Class.35

Steps Review1. Write the state diagram (.sm file)2. Run the SMC tool (generates state pattern code)3. Implement the actions (write the AppClass)4. Interact with FSM by invoking transition methods36

AgendaA. Uncle Bob’s TurnstileB. Finite State Machines BasicsC. What is SMC?D. Solving Turnstile using SMCE. SMC In DetailF.Examples37

SMC In Detail1. Tool mechanics and project setup2. SMC features in detail3. SMC's design38

1.Tool mechanics and projectsetup39

Project SetupSeparate directory gen forgenerated source codegen directory structuremirrors src structurebin directory contains the smctool (Smc.jar)Ant target automaticallyreruns SMC when .sm filechangesInclude statemap.jar inruntime classpath40

The Smc.jar commandjava -jar Smc.jar -{targetlanguage}{options} {smfilename}.smTarget languages:c , java, tcl, vb, csharptable (generates HTML table representation of the .sm file)graph (generates a GraphViz .dot file diagram of the statemachine logic41

Smc.jar command optionsjava -jar Smc.jar -{targetlanguage}{options} {smfilename}.smOptions:-suffix(override output file name suffix)(e.g. for Java: add synchronized keyword totransition method declarations)-sync-d(specify output directory)-serial(generate serial IDs for states to allow persisting ofstates)-g(add debug output messages to generated source code)42

Smc.jar command options (continued)java -jar Smc.jar -{targetlanguage}{options} {smfilename}.smOptions (continued):(applies only to -graphviz output: specify level ofdetail in the generation of .dot file diagram)-version (prints smc version)-help (prints help)-verbose (generate verbose output during compilationphase)-glevel43

Examplejava -jar Smc.jar -graph-glevel 1 Turnstile.smProduces Turnsile sm.dot,which in Graphviz, lookslike this:44

ant task and target taskdef name "smc" classname "net.sf.smc.ant.SmcJarWrapper"classpath "lib/smc-ant.jar" / target name "gen" depends "init" smc target "java" smfile " {smfile}"destdir " {gen.pkg.dir}"smcjar " {smc.jar}" / /target target name "compile" depends "gen" javac debug "on" deprecation "on"classpathref "class.path"destdir " {build.classes.dir}" src path " {src.dir}" / src path " {gen.dir}" / /javac /target 45

Important note about namingIn Java, it is possible to create a file for a class whosename is different from the declared class name (in thefile)In SMC:the name of the file is derived from the name of the .sm filethe class name (in the file) is derived from the AppClassnameTherefore:make sure to always use the same name for both .smfile and AppClass46

2. SMC features in detail47

Basic .sm file syntax%class Turnstile%package turnstileThe AppClassPackage name%start MainMap::LockedThe start state%map MainMap%%Locked{coin Unlockedpass nil}Unlocked{pass Locked {coin nil{}%%States are grouped into MapsDemarcates start of map{ unlock(); }{ alarm(); }lock(); }thankyou(); }}Essentially a transition tableDemarcates end of map48

Simple TransitionIdleRunningRunTransitionNext StateActions/* smc recognizes c-style comments */// .as well as c style commentsIdle{Run}Running{}49

Loopback TransitionIdleTimeoutTransitionIdle{Timeout}Next StateActionsnil{}Idle{}orIdle{Timeout}50

Transition with ActionsIdleRunningRun /StopTimer("Idle")DoWork()TransitionIdle{RunNext ;

Transition GuardsIdleRun /RejectRequest()TransitionIdle{Run [ ctxt.isValid() ]RunningRun [ IsValid() ] /StopTimer("Idle")DoWork()Next rk();{ RejectRequest(); }52

Notes on transition guardsGuard condition must evaluate to a boolean. Guard maycontain , &&, comparison operators ( , , etc.) or it can bea method invocationIf guard condition is a method invocation on the AppClass, thenprefix invocation with "ctxt."e.g.: ctxt.isValid()Transitions with guards have higher precedence thanunguarded transitionsThere's also a default / fallback transition mechanism that we'lldiscuss shortly53

Transition ArgumentsLoggedOutonLogin(uname, pwd)[isLocked(uname)] , pwd)[ authenticate(uname, pwd) ] /setupUser(uname)Next StateActionsLoggedOut{onLogin(username: String, password: String)[ctxt.isLocked(username) ]nil{ displayLockedDlg(); }}onLogin(username: String, password: String)[ctxt.authenticate(username, password) ]LoggedIn{ setupUser(username); }.54

Entry & Exit ActionsLoggedInEntry { dismissLogin() }Exit { clearUser() }TransitionLoggedInEntryExit{onLogout}Next StateActions{ dismissLoginDialog(); }{ clearUser(); }LoggedOut55{}

Push and Pop TransitionsSMC allows the definition of multiple maps.Each map should contain related states.The idea is that you can use push and poptransitions to move across maps.56

Push Transition esource();}"GetResource()" is invoked and the state changes to"Blocked," defined in WaitMap. SMC pushes (remembers)the existing state on the state stack (internal).57

Pop Transition }The "Granted" transition causes the state stack to pop andthus to revert to the state that the FSM was in prior to thepush. The "OK" transition then takes place in that state.58

The Default StateYou may define a state named "Default" and specifytransitions for it.These transitions serve as "fallback" transitions forall the other states.That is, if you omit defining a transition in a certainstate and that transition takes place, then SMC willfall back to calling the Default state's transition(assuming it's defined there)59

Default State ExampleCan define default behavior of turnstile in "Default"state and override default behavior (exceptions) in Locked andUnlocked states, like so:Locked{pass nil { alarm(); }}Unlocked{coin nil { thankyou(); }}Default{coin Unlocked { unlock(); }pass Locked { lock(); }}60

Default TransitionsYet another level of fallback can be defined as the"Default" transition within a state.If a state S does not define a transition T and the"Default" state does not define one either, then Twill be handled by S's "Default" transition.Default transitions can be defined on the Default state61

3. SMC's design62

(standard code, in statemap.jar)TurnstileState(generated code)TurnstileContextMainMap DefaultMainMap UnlockedMainMap LockedThe SMC PatternMainMap63

AgendaA. Uncle Bob’s TurnstileB. Finite State Machines BasicsC. What is SMC?D. Solving Turnstile using SMCE. SMC In DetailF.Examples64

Where do FSMs apply insoftware development?65

Generic GUI Uses / ExamplesGenerally, anything modal:Application Login ProtocolWizards (follows a series of steps from start to finish) andPagingAssociating by picking from a listlist can be in "pickable" state, where it exposes a "pick"transition, that triggers an action that performs theassociation of the selected item with some other objectGUI manifestation of the object life cycle: Create / Read /Update / Deletee.g.: in Edit state, the object exposes "Save" and "Cancel"transitions. In Read state, it might expose "Edit" and"Delete" transitions.66

Login ProtocolLoggedInStateEntry { dismissLoginDialog(); }Exit { clearUser(); }{onLogout LoggedOutState {}}LoggedOutStateEntry { showLoginDialog(); }{onLogin(username: String, password: ialog();}onLogin(username: String, password: String)[ctxt.authenticate(username, password)]LoggedInState { clearBadAttempts(username); setupUser(username); }onLogin(username: String, password: String)[ctxt.tooManyBadAttempts(username)]nil{ lock(username); displayLockedDialog(); }onLogin(username: String, password: String) nil { loginInvalid(); }}67

Another login implementation68

Application-Specific GUI UsesThink about GUI apps such as Photoshop or the GIMP, whereeach tool you pick puts you into a different mode (brush,eraser, selection tool, etc.)Further, within each mode, you can have sub-modes. Forexample, the "selection" tool in photoshop is modal. The firstclick which starts a selection has a different behaviorcompared to the second, which completes it. The UI reflectsthis: after the first click (transition), we're enter selectionmode (state). In this mode onmousemove (transition) triggersthe action to redraw a dashed rectangle, but stay in that mode.Another transition, "onclick" will take it back out of selectionmode. The exit action is to record the selection.69

App-Specific GUI UsesEnabling and disabling GUI features in an application basedupon whether those features are applicable (valid transitions)in the existing application state.Example: in Keynote, unless I pick some text, the textinspector remains disabled70

Network codeGeneral: Disconnected, Connecting,Connected, Disconnecting statesFile transfer: connect, send data, disconnect71

ParsersSMC is great for finding patterns incharacter streamsDetecting tokens such as words, numbers,whether we're inside comments, etc.As the tokenizer reads the text stream, it entersand leaves different states (inside comment,outside comment) and fires transitions (detectedtoken)72

A Comment StripperNormalState{slash PerhapsEntering { }asterisk nil { outputit(); }other nil { outputit(); }}PerhapsEntering{slash nil { outputit(); }asterisk InComment { }other NormalState { outputwithslash(); }}%%73PerhapsLeaving{slash NormalState { }asterisk nil {}other InComment { }}InComment{slash nil {}asterisk PerhapsLeaving {}other nil {}}

Comment Stripper Driver74

Anything with a user interfaceTurnstiles, Coke machines, Gumballmachines, ATMs75

Business ObjectsA Visit can be scheduled, confirmed, inprogress, or completeA Bill can be outstanding, partially paid, orpaidAn Order can be placed, partially filled,filled, shipped76

Wrapping up.77

Current Status of ProjectSMC project is mature / stableCurrent version is v3.2(latest addition is the production of Graphvizdiagrams from a .sm file)Expect ant task to be bundled with the nextrelease78

ConclusionsSMC is a simple tool that can be used repeatedly tosolve a specific category of problems that occurfrequently in various domains in softwaredevelopmentSMC offers a "best of both worlds" solution toFinite State Machine problems:1. The design advantages of the State Pattern without the tediumof writing the state classes2. View and edit the entire finite state machine logic in a single file79

References1. Design Patternsby Gamma, Helm, Johnson, & Vlissides2. Agile Software Developmentby Robert Martin3. SMC Projecthttp://smc.sourceforge.net/(maintained by Charles Rapp)80

Q&A81

ContactEitan Suezeitan@u2d.comUptoData, Inc.http://u2d.com/Please remember to complete evaluation forms.82

Fin83

SMC History SMC is Robert Martin's invention (it is discussed in Robert's book Agile Software Development (Ch 29)) Charles Rapp happened to have succeeded Robert at Clear Communications Corporation. He added many features, made design revisions, and open-sourced the project (more information in the preface of the SMC manual on sourceforge). 26

Related Documents:

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

Chính Văn.- Còn đức Thế tôn thì tuệ giác cực kỳ trong sạch 8: hiện hành bất nhị 9, đạt đến vô tướng 10, đứng vào chỗ đứng của các đức Thế tôn 11, thể hiện tính bình đẳng của các Ngài, đến chỗ không còn chướng ngại 12, giáo pháp không thể khuynh đảo, tâm thức không bị cản trở, cái được

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. Crawford M., Marsh D. The driving force : food in human evolution and the future.

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. 3 Crawford M., Marsh D. The driving force : food in human evolution and the future.