给出像这样的Ruby方法:
def create_object_and_do_if_necessary params
if necessary?
do_precondition_stuff
end
object = create_object params
if necessary?
do_postcondition_stuff object
end
end
这段代码可能闻到了。有没有更好的写作方式?
答案 0 :(得分:1)
不是真的。如果你想节省空间,你可以使用一个班轮:
def create_object_and_do_if_necessary params
do_precondition_stuff if necessary?
object = create_object params
do_postcondition_stuff object if necessary?
end
答案 1 :(得分:1)
这是一个从创建对象中提取条件的示例。
def create_object_and_do_if_necessary(params)
with_around_conditions { create_object(params) }
end
def with_around_conditions
do_precondition_stuff if precondition_stuff_necessary?
object = yield
do_postcondition_stuff object if postcondition_stuff_necessary?
object
end
答案 2 :(得分:0)
鉴于你在Linuxios的答案评论中写的necessary?
是一种沉重的方法,你能做的最好的事情就是保留条件结果的标志。
def create_object_and_do_if_necessary params
flag = necessary? # which is long or heavy
do_precondition_stuff if flag
create_object params
do_postcondition_stuff object if flag
end