问题
Is it a good practice to hide instance variable initialization in private methods?
For example, I have a user controller with some actions:
class UsersController < ApplicationController
before_filter :get_user, only: [:show, :edit, :update, :destroy]
before_filter :set_user, only: [:new, :create]
def index
@users = User.all
end
def show
end
def new
end
def edit
end
def create
if @user.save
redirect_to @user, notice: 'User was successfully created.'
else
render action: 'new'
end
end
def update
if @user.update_attributes(params[:user])
redirect_to @user, notice: 'User was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@user.destroy
redirect_to users_path
end
private
def get_user
@user = User.find(params[:id])
end
def set_user
@user = User.new(params[:user])
end
end
Some people say that it seems like a magic, but it's DRY. What do you think?
回答1:
They're not hidden, they're right there.
Personally, when it comes to DRY, there's a rule I like to follow (I read it somewhere but I don't remember where, forgive me) - the first time you want to duplicate content, you copy and paste it with a frown, but if you want to duplicate it again, that's when you extract it out into one place.
Your :load_user
example is fine, but I wouldn't bother with :set_user
.
回答2:
This is too DRY for me.
before_filter
for routine stuff like instance variable initialization drives me insane because the method appears blank, yet stuff is happening. Not a big deal if the method is otherwise empty, but large methods may obscure the filter, or you might overlook it altogether. You then have to hunt down the filter method and mentally reconstruct the workflow. It makes maintenance more difficult than it needs to be.
I would forego filters and call getter/setter methods in place:
def show
get_user
end
That way you can see where initialization is happening. If you insist on using filters, put a comment in the method advising that filters are being applied.
Personally, I reserve before_filter
for conditional logic only.
来源:https://stackoverflow.com/questions/14413539/hidden-instance-variables-in-before-filter-method