Search code examples
smalltalkboolean-logicpharoboolean-expressionsqueak

Evaluate inequality in Pharo


Since I am not aware of any inequality operator in Pharo smalltalk, it makes it difficult to check for inequality of a string. This is my current code:

[ contact password = contact confirmPassword and: firstTime = false and: (contact password = '' ifTrue:[^false])]   whileFalse: [ code]

namely this part:
(contact password = '' ifTrue:[^false])

What am I doing wrong? Is there a better way to check if a string is not empty?


Solution

  • There is an inequality operator,

    a ~= b

    although it's rarely used as it is often better to just write a = b ifFalse: [ ...]

    That's not all however, and: accepts a block, not a boolean

    so

    contact password = contact confirmPassword and: firstTime = false
    

    should actually be

    contact password = contact confirmPassword and: [ firstTime = false ]
    

    if you want the shorthand variant, you can use &

    contact password = contact confirmPassword & (firstTime = false)
    

    The difference is that the and: block is evaluated only if the receiver is true. This is important if the and: block relies on the truthness of the the receiver, such as a ~= 0 and: [ x / a = b ]. This would be a ZeroDivide error if you used & or forgot the block.

    Finally you can check string emptiness by sending it isEmpty or ifEmpty: message, e.g.

    myString ifEmpty: [ ... ] or equivalently myString isEmpty ifTrue: [ ... ]

    So you can write your condition for example as follows:

    contact password = contact confirmPassword & firstTime not & contact password isEmpty ifTrue: [ ^ false ]