oop - Java: Encapsulating if-return statement in a method call for cleaner, more concise code? -
i'm learning java studying books on code design.
i wondering, possible in java have if
statement encapsulated in method call allows 1 somehow exit parent method if boolean
false?
what i'm wondering if if can further distill following code
public void addstock (string stock) { boolean stocknameisvalid = teststringforvalidstockname(stock); if (stocknameisvalid == false){ joptionpane.showmessagedialog(getparent(), "invalid text entered. stock ticker names may include upper-case alphabetical letters.", "invalid text entry error", joptionpane.error_message); return; } boolean stockalreadyexistsinpanel = testforstockexistenceinlistingpanel(stock); if(stockalreadyexistsinpanel == true){ joptionpane.showmessagedialog(getparent(), "the same stock cannot entered twice list of stocks being watched.", "redundant stock error", joptionpane.error_message); return; } controller.addstocktodb(stock); }
into
public void addstock(string stock){ giveerrorandreturnifstocknameinvalid(stock); giveerrorandreturnifstockcannotbefound(stock); controller.addstocktodb(stock); }
i'm wondering if doing possible because ide can't extract code above further, , having code shaped in second way above think communicate intent better , have higher level of abstraction initial example.
i have idea because i'm reading uncle bob's "clean code" book, , inside says methods should short can make them. if encapsulate lower-level logic within method calls leaves code reflecting higher-level logic. makes code easier understand because requires less of developer's mental resources general concept of each part of code does.
my goal here eliminate reader having analyze implementations details of code here unless it's absolutely necessary. instead of having read through entire method comprehend it, reader can instead more abstract representation of logic of code.
we have use exceptions, below pseudo code explains same:
public void addstock(string stock){ try { isstocknamevalid(stock); isstockexists(stock); controller.addstocktodb(stock); } catch(illegalargumentexception exe) { } } public boolean isstocknamevalid(stock) throws illegalargumentexception { //check stock name valid, if not throw new illegalargumentexception("stock name exists"); } public boolean isstockexists(stock) throws illegalargumentexception { //check stock exists, if not throw new illegalargumentexception("stock name exists"); }
Comments
Post a Comment