Reputation: 149
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:
FunctionCall
class becomes an attribute, but there is a doubt that this would pollute overall semantics, as the attribute should not be visible "globally".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?Thanks in advance.
Upvotes: 1
Views: 74
Reputation: 1802
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
...
}
Upvotes: 0
Reputation: 5546
From what you wrote, it seems that the FunctionCall
object is just a value object with data, not some object that evaluates itself and returns value. With multiple types of such objects, you need to have a way to disambiguate what type of object you are using.
For that part, I can advise you using enums to disambiguate rather than using instanceof
operator or class reflections. You can create nice switch-case
commands with it, too.
public class FunctionCall {
// ...
public MyType getType() {
return MyType.BASIC_FUNCTION_CALL;
}
}
Another nice thing about enums is, it is a class that can have its own fields. Have some final
fields for the enum constants, put in values that describe some trait of it, and you can use this information in the logic that handles it, to your advantage.
As for the actual answer to your question though, it's not quite possible from knowing so little about your problem. In some cases, inheritance is better, in some other cases, composition is better. In both cases, some kind of interface is nice, and it could declare the getType
method.
Upvotes: 1