From: Mark Slagell Date: 2000-10-23T13:48:33+09:00 Subject: [ruby-talk:5767] Re: Array#insert Aleksi Niemel� wrote: > > ... > While it might not be obvious, as you say, there's one catch here. Assume > Array#insert would have been named Array#insert!: > > class Array > def insert > dup.insert! > end > end > > But if you have only non-state-modifying version, plain Array#insert, > there's no way one can go to other direction. Yes, but I guess I don't think it has much to do with the method name issue. (Unless, again, you hear me saying something that I don't mean to be saying.) It does suggest an implementation guideline. > def update(anArray) > @theArray.insert(@index, anArray) > end > > For me it's obvious (or I should put, I expect) insert in above code does > change @theArray. Context makes it clear, yes? But that's the readability of existing, working code. If, without the benefit of an example like the above in front of me, I write bar = foo.insert(idx, obj) ... I've unwittingly created context that will frustrate me later. (Okay, maybe you'd never write that line of code, but bear with me.) The method name is recognized, the arguments are acceptable, the interpreter doesn't complain, and, well, it seems like good code to me. Context doesn't help a bit; if anything, staring at it just reinforces the original mistake in my mind. I have to eventually trace my program's misbehavior to a line of code that passed those routine intuitive tests. At the risk of belaboring the point -- hmm, maybe I'm about ready to abandon this one too -- a convention saying that methods ending in '_' are non-state-modifying means I'm likely to first try bar = foo.insert_(idx, obj) and if there is an undefined method error, I can either go straight to the documentation to see what's what, or just try it again without the '_'; but in the latter case my suspicions for this line of code are already raised, and if I'm wrong, the error will be much more quickly diagnosed as a result. Don't we all do essentially the same thing with the '!' now and then? (or, again, is this just me?) > Anyway, this discussion has enlargened my view for Ruby name issues. > Previously I considered naming having to be conformant to OO-centered world. > That world suggests state-modifying plain names when obvious. > > > So, instead I suggest standardizing a way to name a > > 2. ends in '_': receiver's state guaranteed not to change. > > I think the idea is quite good as it isn't pervasive. Anyway the difference > between > > myInteresting.object.code.dup.partly_destroy.to_s and > myInteresting.object.code.partly_destroy_.to_s > > isn't many chars and the psychological distance with in the end of the line > gets smaller and smaller, so the coder has to be very careful. > > - Aleksi Sigh. I hadn't thought of how an underscore blends in with the surroundings. It certainly doesn't grab the eye the way ! and ? do. So the dup'ed version, as you've written it, is easier to read. -- Mark