在smalltalk中,对消息参数强制执行某些值的最佳方法是什么?

在smalltalk中,对消息参数强制执行某些值的最佳方法是什么?,smalltalk,pharo,Smalltalk,Pharo,我正在用Pharo开发一个简单的棋盘游戏,我的棋盘上有一个向单元格添加对象的方法。单元格只是对象上点的字典 作为方法的一部分,我想强制一个点应该大于零,但小于电路板的宽度和高度,换句话说,它应该实际位于电路板上。最好的方法是什么 我当前的尝试如下所示: at: aPoint put: aCell ((((aPoint x > self numberOfRows) or: [aPoint x <= 0]) or: [aPoint y > self numbe

我正在用Pharo开发一个简单的棋盘游戏,我的棋盘上有一个向单元格添加对象的方法。单元格只是对象上点的字典

作为方法的一部分,我想强制一个点应该大于零,但小于电路板的宽度和高度,换句话说,它应该实际位于电路板上。最好的方法是什么

我当前的尝试如下所示:

at: aPoint put: aCell

((((aPoint x > self numberOfRows) 
    or: [aPoint x <= 0]) 
    or: [aPoint y > self numberOfColumns ]) 
    or: [aPoint y <= 0]) 
    ifTrue: [ self error:'The point must be inside the grid.' ].

self cells at: aPoint put: aCell .
(aPoint x > self numberOfRows 
    or: [ aPoint x <= 0  
    or: [ aPoint y > self numberOfColumns
    or: [ aPoint y <= 0 ] ] ])
        ifTrue: [ self error: 'The point must be inside the grid.' ].
at:aPoint put:aCell
(((aPoint x>self numberOfRows)
或:[aPoint x self numberOfColumns])

或者:[aPoint y通常
或者:
是这样嵌套的:

at: aPoint put: aCell

((((aPoint x > self numberOfRows) 
    or: [aPoint x <= 0]) 
    or: [aPoint y > self numberOfColumns ]) 
    or: [aPoint y <= 0]) 
    ifTrue: [ self error:'The point must be inside the grid.' ].

self cells at: aPoint put: aCell .
(aPoint x > self numberOfRows 
    or: [ aPoint x <= 0  
    or: [ aPoint y > self numberOfColumns
    or: [ aPoint y <= 0 ] ] ])
        ifTrue: [ self error: 'The point must be inside the grid.' ].

您只需在“cells”字典中预先填入范围内有效的所有点,即在初始化过程中的某个地方放入:

1 to: numberOfRows do: [:y |
  1 to: numberOfCols do: [:x |
     cells at: x@y put: dummy "or nil " ] ]
然后,在给定点添加单元格的方法将非常简单,如下所示:

at: aPoint put: aCell

   self cells at: aPoint ifAbsent: [ self error: 'The point must be inside the grid.' ].
   self cells at: aPoint put: aCell .
还有一个helper方法#between:和:,可用于最小化代码混乱:

((aPoint x between: 1 and: self numCols) and: [
 aPoint y between: 1 and: self numRows ]) ifFalse: [ ... bummer ... ]

任何时候,当事情嵌套得那么重时,都是调用另一个方法的时候了

isValidPoint: aPoint
  aPoint x > self numberOfRows ifTrue: [^ false].
  aPoint x <= 0 ifTrue: [^ false].
  aPoint y > self numberOfColumns ifTrue: [^ false].
  aPoint y <= 0 ifTrue: [^ false].
  ^ true.
isValidPoint:aPoint
aPoint x>self numberOfRows如果正确:[^false]。
aPoint x self numberOfColumns如果正确:[^false]。

a点y啊,那太完美了。同样感谢assert语法,我认为assert可能有用。我忘记了
between:and:
这是一种更简洁的表达方式。谢谢!这是一个很好的建议,我最终确实采纳了。特别是当以后的方法需要两个有效点,我需要检查bo时请记住,您可以自动“格式化”代码,通过Cmd+r或Ctrl+r删除所有额外的括号,或者右键单击方法体并选择format。