0

What is in eiffel the best way to have a constant which can be redefined?

  • class A => color: STRING = "green"
  • color B inherit A => cannot redefine

while having a function which only returns "green" or "blue" needs the string to be created again, performance problem or doesnt matter?

As far as I understood, the onces cannot be redeclared...

Pipo
  • 4,653
  • 38
  • 47

1 Answers1

2

Once features can be redefined as any other features. The example would be

class A feature
    color: STRING once Result := "green" end
end

class B inherit A redefine color end feature
    color: STRING once Result := "blue" end
end

Also, manifest strings themselves can be defined as once:

class A feature
    color: STRING do Result := once "green" end
end

class B inherit A redefine color end feature
    color: STRING do Result := once "blue" end
end

The behavior in both cases is identical, so you can even mix both variants. The performance might be different but only marginally. In both cases new strings are not created on every call.

Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35
  • Despite of the implementation I think `color: STRING once Result := "green" end` should be `green: STRING once Result := "green" end`. Otherwise `color` is actually a variable. Maybe define a set of color constants like `green` or `blue` and the assign those to a color *variable*, or return that color constant. In that case `color` should be a (polymorphic) function`. – U. Windl May 24 '21 at 16:16
  • @U.Windl I believe in the original question there is a common ancestor `LIGHT` with a deferred feature `color` with some default value (say, `white`) that needs to be redefined in `GREEN_LIGHT`, `YELLOW_LIGHT`, etc. without creating new string objects on every call. – Alexander Kogtenkov May 24 '21 at 20:01
  • Sorry, I can only see the question as it is here now, and there is no `LIGHT`. Maybe the lesson is to provide somewhat complete examples for questions to reduce guessworks. – U. Windl May 26 '21 at 09:02
  • @U.Windl Right, the answer does not question why the given functionality is needed, it focuses on the implementation details, not on the (potentially higher-level) design decisions. However, re-reading your comment, I guess, I misunderstood it: the feature `color` is indeed polymorphic, but had to return a constant rather than a new string at every call. – Alexander Kogtenkov May 26 '21 at 12:13