From: Jim Cochrane Date: 2006-11-26T17:15:07+09:00 Subject: Re: coding practise On 2006-11-25, sempsteen wrote: > ok, i get it. > so when we invoke Hash#has_key? it does not responde by calling and > getting the result of Hash#[] method, like if [] responds nil has_key > gives false. > >> It also allows for good code readability - 'has_key?': It's pretty >> obvious to, e.g., a reviewer what the code wants to do. > > Yes, i agree with you and i also want to code in the same way. I want > to learn the best way of doing this. > Let's say that i want to learn the answer to the ultimate question of > life, the universe and everything. > i don't want to make two calls that first one returns true or false > after 7.5 million years and second one returns the answer another 7.5 > million years later if first one returns true. > > puts everything.answer if everything.has_answer? > Easy: puts 42 Seriously, I'd say in your above example that the class that 'everything' is an instance of is poorly designed - if 'has_answer' does the same (redundant) calculation as 'answer'. (If it doesn't, then the design is fine and you have to be very, very patient.) The fix: change 'has_answer' to store the answer (privately) after calculating it and 'answer' to simply retrieve that answer if it has been created. But your hash example is a different matter - if you access the hash a large number of times and there is redundancy re. 'has_key' vs. [] and performance is important, it may be worth it to change the app. to not call has_key. But if you leave it as is and you find that it performs acceptably, then IIABDFI (if it ain't broke, don't fix it). --