java - When "if else"/"instance of" are inevitable, how do we improve the design apart from using visitor pattern? -
when have object hierarchy purely inheritance of semantic , not of behaviors,then inevitably need write "instanceof" or "if/else" everywhere run time type checking.
e.g.
if have object hierarchy has
class function class average extends function class sum extends function class max extends function
if there method called calculate() in these classes, not have problem, can take advantage of polymorphism , design satisfies lsp.
however if not want add calculate() method hierarchy reason, these objects purely plain object stateless objects represent semantic.
then forced write following code everywhere :
if (function instanceof average) //perform average else if(function instanceof sum) //perform sum else if(function instanceof max) //perform max
the code above indicates bad design, because write code everywhere , design fragile , hard change later on. guess if number functions limited , calculation of function in single place perhaps ok depends on complexity.
what i've known far solve above approach, possible way implement visitor pattern, there other way solve above design apart using visitor pattern?
one problem can see visitor pattern visitor pattern's accept method not return value, not convenient sometime if accept() method doesn't satisfy requirement.
if still know types @ compile time can use helper class:
class function { } class average extends function { } class sum extends function { } class max extends function { } class functionhelper { public number calculate(average a) { return null; } public number calculate(sum s) { return null; } public number calculate(max a) { return null; } public number calculate(function a) { return null; } }
generally you'd make helper methods static not restricted - there rather interesting things can multiple flavours of helper class.
Comments
Post a Comment