Search code examples
eiffel

Modify class attributes in Eiffel


Goodmorning. I've starting using Eiffel at the University.

I have this example:

    class
      CLASS_1

    create make

    feature
      x: INTEGER

      make
        do
         x:=0
        end

      increment(inc: INTEGER)
        do
          x:=x+inc
        end

      get_x: INTEGER
        do
          Result:=x
        end
    end

----------------
class
   CLASS_2

create make_2

feature
    make_2
        do
            print("EXAMPLE")
            meth_1
        end
    meth_1
    local
        instance: CLASS_1
        i: INTEGER
    do
        create instance.make
        from
            i:=0
        until
            i<20
        loop
            instance.increment(5)
        end
        io.put_string ("The result is: ")
        io.put_integer (instance.get_x)
    end
end

Why the result is always 0? It seems like it doesn't update the value. I've read that the client class attributes are read-only. Is it true?


Solution

  • The issue is not with variable attributes, but with the fact that the loop is never executed. Just remove the loop while keeping the call to the procedure increment and you'll see the difference.

    Talking about loops, the code has 2 issues:

    1. Unlike the while loops in other languages, the expression in the until part is an exit condition. As soon as this condition is true, the loop exits. In this code this happens at the first iteration (because i = 0 and 0 < 20), i.e. without ever touching the loop body.

    2. The variable i is not changed in the loop body and has the same initial value for all loop iterations.

    Minor comments:

    • There is no need for "getter" methods in Eiffel, such as get_x. You can use x directly.

    • Self-initializing variable attributes are set to the default values on object creation. In particular, x is set to 0 when an object of type CLASS_1 is created. Having x := 0 in the creation procedure is harmless, but is also useless unless you want to use this procedure as a regular one as well.