gpt4 book ai didi

if-statement - 在 Smalltalk 中重构 if-chains 没有类爆炸

转载 作者:行者123 更新时间:2023-12-04 04:47:01 24 4
gpt4 key购买 nike

由于 Smalltalk 不鼓励使用 case Of:,有什么替代方案可以实现以下情况而不会发生类爆炸?

self condition1
ifTrue: [ self actionForCondition1 ]
ifFalse: [
self condition2
ifTrue: [ self actionForCondition2 ]
ifFalse: [
self condition3
ifTrue: [ self actionForCondition3 ]
ifFalse: [ .... ] ] ]

最佳答案

取决于你的条件到底是什么样的?

  • 如果您的条件是型式测试
    anObject isKindOf: aClass

    你可以在类上调度,这意味着你在 anObject 上调用一个 Action 方法.
  • 如果您的条件是平等测试
    anObject = anotherObject

    您可以使用以对象为键的字典和作为块闭包的操作。
  • 作为最后的恢复,如果没有其他帮助,您可能需要重写建议的代码以避免不必要的嵌套:
    self condition1
    ifTrue: [ ^ self actionForCondition1 ].
    self condition2
    ifTrue: [ ^ self actionForCondition2 ].
    self condition3
    ifTrue: [ ^ self actionForCondition3 ].
    ...
  • 关于if-statement - 在 Smalltalk 中重构 if-chains 没有类爆炸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8113497/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com