From: Henrik Horneber Date: 2004-10-06T03:29:35+09:00 Subject: Extending existing classes (was: Re: A ruby course) Hi! Taking over from Brian (sorry :) ) I need to ask a question of my own. Brian Schr�der wrote: > Henrik Horneber wrote: .... >> - extending String so you can tell it to remove cpp comments /* remove >> me */ >> >> Of course both tasks could be accomplished without extending those >> classes. I have no idea in which cases you should write helper methods >> and when you should extend existing classes... does anybody have some >> 'heuristics' or best practices? >> >> regards, >> Henrik >> > > Hello Henrik, > .... > > Extending string with something like remove_cpp_comments seems awkward > to me. In any usecase for this I'd rather have a class CppCode that I > can ask to remove_comments. (Or even better, to give me the source > without comments.) > > So my personal heuristic tells me not to extend in this case. Now, the reason I was immediatly reminded of that remove_cpp_comments example is, that I wrote a small script some time ago, which used exactly this case. First, I implemented remove_cpp_comments in its own class (which was not called CppCode, but had the same intend), but out of curiosity (and because in ruby I can, dang it! :) ) I moved the remove_cpp_comments method to String. Turns out, the method got shorter and somewhat clearer, at least to me. And I could write something like source_code = IO.readlines(file).join("\n") source_code.strip_comments! # instead of source_code = CppCode.strip_comments( source_code) .... you get the idea. Even though the code became clearer on that level, I still have to agree with Brian that it is somehow dirty/awkward on a different level to extend String with such a method. This, formerly extremly happy, Ruby user is confused. What are your experiences? regards, Henrik