Posted by stephan on 10. October 2008
While reading about the DRY principle (for “Don’t repeat yourself”) and the evil of copy-and-paste coding (again), I started thinking what to do instead. Actually, what to do is more or less obvious: Put the code into a place where its accessible to be reused — a method, may be in a new or existing module or class.
So, whenever I feel the ‘need’ to copy code, I now think about cutting it, creating a new method and calling that. Apart form avoiding duplication, the code is now testable immediately by calling the method (instead of getting the surrounding code exercised). And the methods using the code gets shorter.
In the end, it boils down to pasting code being perfectly OK, it’s the copying that causes the trouble.
Posted in Programming, method call, testing | Tagged: Coding, Testability | Leave a Comment »
Posted by stephan on 28. January 2007
Sometimes I like to find out in which method my programs are currently in — may be for debugging but a lot more likely to log that fact for later analysis. For some (long running) automation stuff that’s really useful. Especially if (or when) the exact order of method calls it not deterministic. Think for example of a rules based engine which randomly applies a set of rules to a set of objects.
That said, you could just make each method log it:
def method_1
logger.info "Executing #{ method_1 }"
# more code
end
But that’s not DRY after the second method doing that. And it’s manual, cumbersome and error-prone.
Well, there’s Kernel#caller, but I was looking for something a bit more compact. So here it comes:
module MethodCallList
def method_name
list = caller[ 0..-2 ]
if list.empty?
"method_name"
else
list.map do | el |
if md = el.match( /in '(.+)'/ )
md[ 1 ]
else
''
end
end.reverse.join( '/' )
end
end
end
Is there any better, more elegant or completely different way to do this in Ruby? I’d love to hear about that.
Hmm, the module name could be better than this…
Posted in Ruby, method call, syntax | 1 Comment »