From: Phlip Date: 2009-02-22T03:14:40+09:00 Subject: Re: why not check for nil? Roger Pack wrote: > matt neuburg wrote: >> A post I ran across on a rails forum reads: >> >> "Warning! DO NOT test for nil! This is a very bad coding practice. You >> can use "if obj", but do not use "if obj.nil?" or whatever." >> >> Is that generally true? Why? m. > > because it might be false [not nil]? Technically yes, but that admonition has more meanings (some of which may have escaped that original rails poster). Consider this pattern: if @user render :partial => 'premium_content' # for logged-in users else render :partial => 'teaser_content' # for the great washed masses end That is sloppy programming because it asks @user for its type (are you a logged-in user? or just a slovenly nil?) The correct pattern is @user is never nil, and if no user is logged in, then it should hold a "Guest" object. Then User and Guest can provide different methods for the same messages (method names): render :partial => @user.content_template That pattern collects many redundant 'if' statements into one place; that technique is the heart of all OO programming. -- Phlip