if statement - Is there a best practice for using DRY with several partially overlapping logic streams? -
i unsure how search this, if has been answered, please point me it.
i have once again come upon common situation in unsure of best practice. consider situation in function has 1 of 3 possible values; 'a', 'b', , 'c'.
if receive 'a' or 'b', have a significant amount of overlapping processing do, after case specific stuff. however, if receive 'c', need different. trivial sake of example, have across pretty heavy instances of this.
example (python):
def dostuff(self, val): if val == 'a': self.counter += 1 print val, "is good" self.passing = true self.domorestuff() elif val == 'b': self.counter += 2 print val, "is not bad" self.passing = true self.domorestuff() elif val == 'c': self.counter -= 1 self.passing = false print val, "is unacceptable" self.wearedonehere()
so idea either 'a' or 'b', there case-specific instructions , repeated stuff, 'c', it's different. in cases, it's not bad leave 3 separate cases, though makes dry eye twitch @ it. in other cases, if there's lot of repeated code, can bigger problem.
one solution following:
def dostuff(self, val): if val == 'a' or val == 'b': if val == 'a': self.counter += 1 print val, "is good" elif val == 'b': self.counter += 2 print val, "is not bad" self.passing = true self.domorestuff() elif val == 'c': self.counter -= 1 self.passing = false print val, "is unacceptable" self.wearedonehere()
is double-checking-the-value method okay? makes dry eye twitch little, not as repeating huge blocks of code.
my real question, suppose, has been discussed somewhere or there standard "best practice" way this?
i don't know python, in cases refactor common between , b , put them in private function, call , b.
an example in javascript:
var somefunction = function (somearg) { var stuffcommontoaandb = function () { // stuff both , b }; switch (true) { case somearg === 'a': stuffcommontoaandb(); // stuff break; case somearg === 'b': stuffcommontoaandb(); // stuff b break; case somearg === 'c': // stuff c break; } };
it might worth mentioning passing flags function toggle different behaviors can sign function violating single responsibility principle, in case want take step , rethink design further.
Comments
Post a Comment