This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am writing an expression evaluator for arithmetic expressions. I have treated parentheticals in expressions such as: 25 * (7 + 3) + 19 as "sub-expressions" and have called methods recursively in order to evaluate them. The only way that I have been able to keep track of variable values across my recursive objects is to make the necessary variables static - but it feels as though this is sort of anti-encapsulation. I have tried using return statements lots of places, but the variable values still aren't retained. Also, I haven't found a discussion of recursion in Java in the books I have (Head First Java and Core Java, book 1). Could anyone suggest somewhere I could get some information on this?
The generic answer is you hold all state for the current level of recursion in local variables. Show us some of what you have written. I'm pretty sure we'll be able to give you enough hints to get you going again.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Apr 29, 2007
Thanks very much for your offer - and I'll be happy to send the code for comments and criticism. Please let me know.
But I think I might not have been very clear. The code works - meaning that I can give it a messy input expression and get the correct answer returned; it also has error messages for stuff like unbalanced parentheses. I'm doing this as a way to learn object orientation using Java as the vehicle - object orientation came in while I was raising & home-schooling my son, so I missed out when it was fresh. So when I was whining about needing something to do, because I have no confidence that I've learned something until I can actually write code, my (obnoxious) son suggested an expression evaluator. I have 3 classes and an enum in it and since I'm quite new at this it's probably pretty crude as well as being long. I asked the question because I'm all sorts of uncertain about whether I'm doing something crudely that more experienced folks can do more prettily or efficiently ...