Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 保护条款和单一责任原则(SRP)_Ruby_Oop_Single Responsibility Principle_Guard Clause - Fatal编程技术网

Ruby 保护条款和单一责任原则(SRP)

Ruby 保护条款和单一责任原则(SRP),ruby,oop,single-responsibility-principle,guard-clause,Ruby,Oop,Single Responsibility Principle,Guard Clause,目前正在阅读《Ruby中面向对象的实用设计》一书,并通过一个简单的kata来真正实践它所讨论的一些原则 我有一个方法可以执行以下操作: def release_bike capacity_empty_error if empty? bike end def capacity_empty_error raise "Docking Station is empty." end 这将从我的DockingStation类中“释放一个bike对象”(我知道bike对象应该是一个参数,但目前

目前正在阅读《Ruby中面向对象的实用设计》一书,并通过一个简单的kata来真正实践它所讨论的一些原则

我有一个方法可以执行以下操作:

def release_bike
  capacity_empty_error if empty?
  bike
end
def capacity_empty_error
  raise "Docking Station is empty."
end
这将从我的DockingStation类中“释放一个bike对象”(我知道bike对象应该是一个参数,但目前我只希望该方法返回bike对象,而不是删除它)

#capacity_empty_错误执行以下操作:

def release_bike
  capacity_empty_error if empty?
  bike
end
def capacity_empty_error
  raise "Docking Station is empty."
end
而且是空的?看起来像:

def empty?
  bike == nil
end
其中bike是我的实例变量@bike的包装器方法。所以DockingStation类的当前容量是1,因为代码假设当#bike设置为某个值时它已满(我计划稍后添加适当的容量)

希望这能解释我的代码,请提问并提出改进建议。如果没有,我想问的问题是:

我觉得#释放#自行车中的防护条款行:

capacity\u empty\u空时出错?

是该方法的一项责任,下一行返回的
bike
是第二项责任。这显然破坏了SRP,但我不知道如何使用guard子句,除非将其作为第二个责任添加到现有方法中


能做到吗?其他人是如何实现的?

如何将功能转移到其他类/模块

module BikeChecker
  def capacity_empty_error
    raise "Docking Station is empty."
  end

  def release_bike
    capacity_empty_error if empty?
  end

  def empty?
    false
  end
end

class YourClass
  include BikeChecker

  def release_bike
    super
    bike
  end

  def empty?
    bike == nil
  end
end 

你可以放弃空的吗?来自BikeChecker的方法,我把它留在这里是为了更好地理解

Ahh!我从未见过super的使用,非常感谢Igor。我是这样看待它的:
release\u bike
的合同是“我释放自行车并归还它”。但如果机架是空的,它就不能这样做。SRP实际上要求方法本身处理该情况,它选择通过引发异常来处理该情况。。。当然,你可以自由地以不同的方式看待它。