0

I was wondering if there is a clearer statement then

if not attached foo then
    create foo
end
if attached foo as l_foo then
    l_foo.bark
end

as

if not attached foo then
    create foo
    foo.bark
else
    foo.bark
end

would repeat the foo.bark and obviously I want to avoid it... and even the last statement won't compile with void-safety as foo on else could be void...

Pipo
  • 4,653
  • 38
  • 47

1 Answers1

2

To avoid code duplication and multiple tests, the following code could be used:

l_foo := foo
if not attached l_foo then
    create l_foo
    foo := l_foo
end
l_foo.bark
Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35
  • And `l_foo` is a local variable declared as `l_foo: like foo`. – Eric Bezault Jan 25 '19 at 07:25
  • Is there a reason the compiler is unable to see that a few lines above the object was created? Does the check of object creation on the compiler check not only the `if` statement, but also the content of the `if` statement if the test includes a non Void case? Thx – Pipo Jan 25 '19 at 10:15
  • @Pipo It's not quite clear what you are asking about, so, I assume, you refer to the second example of your original question. The reason why the compiler reports the calls `foo.bark` as unsafe is that in a concurrent environment, a different thread can change `foo` to `Void` before the current thread has a chance to make the call. If the attribute is always changed from `Void` to attached, it can be marked as [stable](https://www.eiffel.org/doc/eiffel/Void-safety-_Background%2C_definition%2C_and_tools#Stable_attributes), then the code would compile. – Alexander Kogtenkov Jan 25 '19 at 11:32