android - better structuring the Java code -
i have written piece of code assignment , want well-factored. basically, part of simple old-school calculator perform addition, subtraction, multiplication, division (when performing division, reminder should shown). required have separate classes each operation (addition, subtraction, multiplication, division have introduced 1 more - reminder). have advice or see gaps in understanding of concept of java generics?
public class logic implements logicinterface { private final int addition = 1; private final int subtraction = 2; private final int multiplication = 3; private final int division = 4; /** * reference activity output. */ protected activityinterface mout; /** * constructor initializes field. */ public logic(activityinterface out){ mout = out; } /** * perform @a operation on @a argumentone , @a argumenttwo. */ public void process(int argumentone, int argumenttwo, int operation){ operationsinterface operationsinterface =null; if(operation==addition) { operationsinterface = new add(); } else if(operation==subtraction) { operationsinterface = new subtract(); } else if(operation==multiplication) { operationsinterface = new multiply(); } else { operationsinterface = new divide(); } if(argumenttwo==0 && operation == division) { mout.print("you cannot divide zero!"); } else { try { //get result int result = operationsinterface.process(argumentone, argumenttwo); mout.print(string.valueof(result)); //add reminder output in case performing division if (operation == division) { operationsinterface = new reminder(); mout.print(result + " r: " + string.valueof(operationsinterface.process(argumentone, argumenttwo))); } } catch (exception exception) { mout.print("something went wrong!"); } } } }
i don't see has generics.
as code review point of view:
- you should ask how easy change code when need extend functionality. in case, suppose want add operator. need add constant , add if/else case, , maybe other logic. suggest have map operator constants operating classes, or use enum that; need initialize once , save if/else cases.
- consider having different
add
classes, 1 simple addition, , prints out something. if want exchange them, need changenew add()
part, cannot have 2 calculators, 1 simple add , extended one. therefore, practice usenew
in kind of factory method can overridden, e.g.protected operationinterface createadd() {return new add();}
. can subclass calculator , overridecreateadd()
. same holds other operators, of course. - your
operationinterface
seems returnint
. not think works division. should @ leastdouble
. - i see
reminder
subclass ofdivide
. @ least logic related division operations , should therefore located individe
class or subclass of it.
Comments
Post a Comment