天哪,它沒有看起來那麼複雜。狀態機代碼非常簡單和簡短。
將狀態存儲在一個變量中,讓我們說myState。
你的狀態機將是一個switch語句,分支myState變量的值來爲每個狀態執行代碼。
的代碼將出現類似這樣的行:
myState = newState;
要強制狀態轉變的要求,你需要添加一個名爲而不是小的方法,這樣
void DoSafeStateTransition(int newState)
{
// check myState -. newState is not forbidden
// lots of ways to do this
// perhaps nested switch statement
switch(myState) {
…
case X: switch(newState)
case A: case B: case Z: HorribleError(newState);
break;
...
}
// check that newState is not undetermined
switch(newState) {
// all the determined states
case A: case B: case C … case Z: myState = newState; break;
default: HorribleError(newState);
}
}
void HorribleError(int newState)
{ printf("Attempt to go from %d to %d - disallowed\n",
myState, newState);
exit(1);
}
我認爲,這簡單而短小的檢查將比單元測試做得更好 - 它肯定會更快!
單元測試的重點在於測試代碼比測試代碼更簡單,因此可以更容易地檢查測試代碼的正確性,然後用於測試複雜的代碼。檢查狀態機代碼通常比狀態機測試代碼更容易。報告100%單元測試通過沒有太多意義,當你不知道單元測試是否正確時。
換句話說:編碼狀態機很簡單,設計正確的狀態機很困難。單元測試只會告訴你,如果你正確地編碼設計,而不是如果設計是正確的。
搜索「國家正規機驗證」 – bobah 2013-11-28 20:39:15