Roger said:
matt said:
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
artial => 'premium_content' # for logged-in users
else
render
artial => '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
artial => @user.content_template
That pattern collects many redundant 'if' statements into one place; that
technique is the heart of all OO programming.