Branching on Concrete Type


For the method createExternalDeclaration(type, name) in the implementation of ASTFactory, is it really bad to use instanceof in order to determine which constructor I need to use for adding the new declaration (either global variable or function declaration)?

I’d say it does not make a difference, whether it is a global variable declaration or a function declaration, since both are identified with an identifier and have a corresponding type and do not have any differentiating characteristics. This way, you would not need to have different classes for the two declarations.

1 Like

So you mean that we only need one class that extends Declaration for FunctionDefinition ?

Note that in general, instanceof is not bad, but adding a function Type::isFunctionType might be more canonical.

I don’t see why you would want more than one kind of function definition…

Here, I meant that since we have one class for ExternalDeclaration (i.e no need to distinguish between GlobalVariable and FunctionDeclaration), so apparently we have 2 options:

  • extending this class, ExternalDeclaration, in order to have the subclass FunctionDefinition.
  • adding another constructor in the class ExternalDeclaration which supplies the required parameters for the FunctionDefinition.

Personly, I think the first option is more approprite for the oop style, but I only wanted to be sure.

In fact, you have zero (0) classes named ExternalDeclaration in the template. If you have such a class, you created it yourself. How you create your class structure is of course up to you, but as a general rule, one must not be afraid of creating new classes in this project.

Having an abstract class ExternalDeclaration and two (or even three) subclasses of it makes a lot of sense.

1 Like