I'm a novice programmer i draw two class diagrams for calculator Project, i want you to check each one of them and tell me which one is better and also, i would appreciate it if you point out the parts that are wrong or could be better.
UML Class Diagrams – Best Design for Calculator Project
cjavaobject-orienteduml
Best Answer
Lets start from the top. We want a
Calculator
that can take an input string and turn it into an Abstract Syntax Tree of expressions. I won't go into any specifics on lexing/parsing, but I can conclude that the Composite pattern is a good fit for this.For the Composite pattern we start by defining an
Expression
interface that is a bit more general than yours;The idea of the Composite pattern is that any
Expression
can hold moreExpression
objects. This allows the lexer/parser to build an AST of expressions with a single root expression. Example:Now to allow for nesting of multiple expressions, the
BinaryExpression
needs to hold two expressions, instead of operating on two doubles:This approach does however require you to define expressions for numbers:
In your parser, you can cast integers to double to reuse the
NumberExpression
.You can then easily define new binary expressions like so:
However, you can now also define a number of other expressions as you see fit:
Skipping the complex implementation details of the lexer/parser, your Calculator can now look like this:
Note: Important things like operator precedence can be handled by the lexer/parser.