feat: 为状态机增加获取targetState、targetStateChain功能#518
feat: 为状态机增加获取targetState、targetStateChain功能#518benym wants to merge 4 commits intoalibaba:masterfrom
Conversation
feat: 为状态机增加预计算targetState功能,接口新增 feat: 完善stateChain测试用例及代码实现 feat: 移除多于代码 feat: 优化注释
|
老哥,看你的状态描述和我的有点类似。我想咨询个问题,你上面说的:
|
significantfrank
left a comment
There was a problem hiding this comment.
Code Review Summary
This PR adds StateChain functionality to the state machine, enabling pre-calculation of subsequent states and state chains without performing actual transitions. The overall design with the Visitor pattern is solid.
Key Issues Found:
- Key collision risk in
stateChainMap— simple string concatenation can cause collisions - Only first internal transition handled in
buildInternalStateChains— others are silently ignored - Raw type usage
State statewithout generics in BFS - Thread safety — check-then-act pattern on
ConcurrentHashMapis not atomic - Typo
"Event:+"should be"Event: " - Misleading naming —
getTargets()returns intermediate chain states, not just final targets - No deduplication in
getTargetStates()result
Suggestions:
- Use
computeIfAbsentfor thread-safe lazy init ofstateChainMap - Use a delimiter in cache keys to prevent collisions
- Consider deduplicating target states or documenting the behavior
- Align generic type conventions across
StateChainVisitormethods
significantfrank
left a comment
There was a problem hiding this comment.
Skill verification test — please disregard.
significantfrank
left a comment
There was a problem hiding this comment.
代码检视总结
本 PR 为状态机增加了 getTargetStates 和 getTargetStateChain 功能,整体设计思路清晰,新增的 Visitor 模式与已有代码保持了一致性。以下是主要发现:
🟠 Major (2)
- BFS 算法逻辑问题:
buildExternalStateChains中!stateQueue.contains(targetState)条件会将非环路路径错误标记为环路,可能导致返回不正确的 StateChain - 原始类型使用:
getTargetStates和buildExternalStateChains中使用了原始类型State而非State<S, E, C>,破坏了类型安全
🟡 Minor (7)
ConcurrentHashMap的 check-then-act 竞态条件(建议用computeIfAbsent)- 缓存 key 缺少分隔符,存在碰撞风险
buildInternalStateChains仅处理第一个内部转换StateChainVisitor泛型参数顺序<S, C, E>与项目惯例<S, E, C>不一致Transition.getType()声明后缺少空行- 通配符导入替换了原有具体导入
getTargetStates中State sourceState使用原始类型
🔵 Suggestion (2)
- 测试中
checkStateChain的断言模式较弱,可能掩盖 bug SysOutVisitor的访问者方法同时产生副作用(打印)和返回值,建议分离
重点建议
最关键的问题是 BFS 算法的正确性,建议重点验证 buildExternalStateChains 在多路径场景下是否能产生正确结果。如果需要找到所有可能路径,建议改用 DFS + 回溯算法。
|
这个pr的时间实在是太久了,我重新回忆了下COLA的源码,对应的问题已经修复,环形链路的错误重新补了精确单测,部分是属于误判的
|
虽然状态机在内部DSL维护了状态转移规则,但在实际使用过程中
发现不能够通过当前状态+事件获取到后续可能转移到的状态,DSL转移过程除UML图外不支持代码获取
比如场景
正向状态,待审核->业务审核通过->商务审核通过->法务审核通过
反向状态,待审核->业务审核驳回
待审核->业务审核通过->商务审核驳回
待审核->业务审核通过->商务审核通过->法务审核驳回
事件是审核通过、审核拒绝
在这个场景中通过待审核初始状态+审核通过事件,能够走到正向链路的最后,这条链路可能是需要展示出去的
更加通用的情况是:
通过当前状态+事件获取后续节点,或后续状态链
如果单独再维护一套等价于DSL转移过程的代码显得有点烦琐
除此之外也为了增加代码维度对后续状态获取的透明度,当状态机状态较多时提升状态链路可预测性
基于上述情况
新增4个功能
对应单元测试
com.alibaba.cola.test.StateChainTest
具体示例


给定如下状态机
获取初始状态为STATE1, 事件为EVENT1的,状态链为