Search code examples
javafieldsubclasssemantics

java subclass or field, good semantics


Please help me to decide which approach is reasonable in the following case. Object:

public class FunctionCall {
  private String functionName;
  private List<Exp> args;
  ...
}

In one very particular case/check the object need to be identified somehow. Possible approaches:

  1. FunctionCall class becomes an attribute, but there is a doubt that this would pollute overall semantics, as the attribute should not be visible "globally".
  2. SpecialFunctionCall inherits the FunctionCall and with instanceof can be identified in the very special case. This would be ideal, the only doubt that it would misuse purpose of inheritance?
  3. Any other suggestions are very welcome.

Thanks in advance.


Solution

  • What you actually need is to use two of the main three principles of Java,polymorphism and 'inheritance' combined together. Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. This means that the behavior of an object could be changed depending on particular circumstances or cases.

    In your case you could create two classes, a FunctionCall and a SpecialFunctionCall. Latter should extends the first one with its one spexial behavior.
    Then when your special case comes up you would use the second class which would have a different behavior than the first.

    By this way you guarantee that there is a per-case functionality of the parent class FunctionCall.

    See below an example of use:

    public class SpecialFunctionCall extends FunctionCall{
      //your special logic goes here
      ...
    }