Search code examples
smalltalksqueak

Squeak Smalltalk: Why reduction of a fraction does not happen after numerator and denominator values are modified in the inspect window?


a := 12 / 24.

a is a variable assigned a fraction 12 / 24. 1 / 2 is the answer when print. Now opening inspect pop up window, I alter the value of numerator and denominator and guess the answer to be the same as before, 1 / 2. What truly happens is that the output stays 12 / 24, which is kind of weird to me.

I have recorded a video to help understand this issue.

https://www.youtube.com/watch?v=LNj24f2wP0M

Why reduction of a fraction does not happen after numerator and denominator values are modified in the inspect window ??


Solution

  • The behavior you describe is correct and is the intended one.

    As a developer you can modify objects in two ways:

    1. Sending messages to them
    2. Modifying their instance variables from an inspector

    Method 1 is preferred because it conforms to the paradigm. So, why do we have method 2? Because when you open an inspector you somehow impersonate the object. In other words, you become the object under inspection and therefore you are entitled to modify yourself.

    Of course, if you modify your internal state it is up to you to preserve your invariants. In the case of fractions, there are two invariants:

    1. denominator > 0
    2. (numerator gcd: denominator) = 1

    In sum, the inspector will assume you know what you are doing and will let you modify all instance variables the way you want. When sending messages, however, the object should behave in such a way that its invariants are preserved.

    Of course, there are private methods that should be handled with care (i.e., be only sent by public methods), but the general idea is that direct manipulation of objects is a good thing and presents no obstacle or safeguard.