5 ms·
He's basically a step away from having several objects (let's call them handlers) which can do your handling for you. Further, they can define the set of circum
by mendicant 14y ago
He's basically a step away from having several objects (let's call them handlers) which can do your handling for you. Further, they can define the set of circumstances in which they are valid.
I'm going to work with a couple of assumptions:
1) The test casts which he refactors to test*() methods are non-trivial
2) The handlers _may_ be large sets of code
Here's a way to handle one of this refactored methods:
if (!test1()) {
handle_failure_1();
return false;
}
if (!test2()) {
handle_failure_2();
return false;
}
if (!test3()) {
handle_failure_3();
return false;
}
handle_success();
return true;
That's a lot of potential code we're dealing with in this class.
What if:
class HandlesFailure1
def handles_this_case(params)
#code from test1()
end
def handle(params)
#code from handle_failure_1()
return false;
end
end
class HandlesFailure2
def handles_this_case(params)
#code from test2()
end
def handle(params)
#code from handle_failure_2()
return false;
end
end
class HandlesFailure3
def handles_this_case(params)
#code from test3()
end
def handle(params)
#code from handle_failure_3()
return false;
end
end
class HandlesSuccess
def handles_this_case(params)
return true
end
def handles(params)
//code from handle_success
return true
end
end
#And now the original class
class DoesSomething
#There are ways to set this up fairly easily. One simple way it to just new it up here, but you could auto-wire it too
handlers = [HandlesFailure1, HandlesFailure2, HandlesFailure3, HandlesSuccess]
def do_something(params)
handlers.each do |handler|
return handler.handle(params) if handler.handles_this_case(params)
end
end
end
There. Now there's a loop and an if. Check each case and either handle or toss it out. This can also work for the case where you might want multiple handlers to handle something, just don't return on the first one.
I'm not saying it's the right way, but it's another way.
Pros:
It really helps to group together the handling methods with the test methods.
Very simple dispatch method
Cons:
Separate classes, and harder to view all the handlers together.