Eiffel: void safety, a concise way to test if an object exists and then call its feature

118 Views Asked by At

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...

1

There are 1 best solutions below

3
Alexander Kogtenkov On BEST ANSWER

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