… or “Saying stupid things about object orientation”. Keep reading the post and afterwards you’ll realize which title is the one that should go there.

Next week we turn in the final practical assignment for DIED. It’s a kind of advanced calculator. It started as an expression evaluator. Then it was extended to support custom user functions, like “sumar(a,b) = a + b”, and finally the software has to plot functions, and also approximate with the divided differences technique (sorry for reminding you about it). Regarding this last part, you keep adding points on a cartesian axis, move them, delete them, and the polynomial gets generated/plotted live and in real time.
Another feature (in this case of the plotting module) is that expressions in terms of y can be plotted. There were already special classes to evaluate an expression, but only in terms of x: a parser (which took care of tokenizing the expression), an evaluator, an Expresion class, etc. We used the Visitor design pattern.

Now those classes had to be specialized to support the y variable. What could have been done, simply, is to modify the originals, and that’s it. So that it supports another variable besides x. We surely wouldn’t have violated the assignment’s statement, but what happens if this isn’t feasible? (actually in the assignment it isn’t “that” feasible to simply do that). That is, if they have to be specialized no matter what. What has to be changed is very little… simply add two lines in one section of the crearTokens method, which check whether the token (which is still a string) is “y”, and in that case create the Variable token (now it is already a token object):
| |
At first I thought that by overriding that method in my new class (copying and pasting all the code and adding those two lines) everything was going to work like a charm. The problem is that other methods are called before. The call chain is analizar -> tokenizar -> crearTokens. That whole chain must be overridden as well, even though the first two methods have exactly the same code. This is so because otherwise methods of the parent class would be called, which is what I don’t want.
It occurs to me, being completely unaware of how a compiler works, that this could be better. In the parent class, we could “name” part of the code as follows:
| |
Then in the child class, we override only that portion of the method (we add two lines at the beginning of the “CreandoTokens” section):
| |
And the same for the other methods in the chain (analizar and tokenizar). We would override a section of those methods, right where the next one is called, so that it is clear which methods from which classes to use.