English 中文(简体)
处理复杂方法的对象定向方式
原标题:Object Oriented way to deal with complicated method
  • 时间:2012-05-23 15:10:46
  •  标签:
  • ruby
  • oop

我有一个在红宝石方面工作的项目,它需要一些工人做大量工作。大多数商业逻辑都包含在这些工人内部,他们变得相当复杂。我设计了模型来构造方法模式,但非常依赖实例变量来保持状态。我设置这个方法似乎是合乎逻辑的,但是我想从社区那里得到一些反馈,了解这是否是错误的,或者我能够设置这个方法的最清洁的方法。

我基本上使用工人表演(Sidekiq)方法作为开关

def perform(transaction_id, data, account_id)
  @transaction_id = transaction_id
  @data           = data
  @account        = Account.new(account_id)

  @campaign_tag   = nil
  @match_str      = nil
  @options        = nil

  has_starter_tag     || return
  find_campaign       || return
  determine_options   || return
  find_active_option  || return
  reservation_over    || return
  already_filled      || return

  send_to_inventory
end

每种方法都遵循相同的逻辑。 检查规则如果不令人满意, 执行动作( 发送电子邮件, 随便... ) 并返回错误, 从而停止执行 。 如果满意, 保存完成交易和返回真实所需的一些 ivar 数据, 从而进入下一步 。

def has_starter_tag
  result = true

  @campaign_tag = find_starter_tag(@account, @data[:variable])
  if !@campaign_tag
    result = false
    send_email_about_badness
    log_some_stuff
  end

  result
end

为了测试这个代码, 我将每种方法所依赖的参数变量截断。 我理解这是一个代码气味, 因为我的测试意识到了执行而不是界面。 也就是说, 我喜欢这些方法的干净界面, 我感到可以扫描源头, 并知道到底发生了什么。

如果我做错了,有人能花点时间解释一下这样做的正确方式(或至少是另一种方式)吗? 我总是有问题要解决那些必须执行许多小步骤的物体,而所有这些步骤似乎都在相辅相成。

问题回答

我的直觉是,你试图 过份地整理这个。

您描述的方法没有算作设计模式 - 它只是将所需的功能分离成若干不同的方法。 问题在于这些方法彼此紧密地连接在一起, 除了“ 分组” 功能之外, 没有什么其他目的。 这些函数似乎唯一的共同点是它们检查某事并取消检查的工作失败。 重复的功能是, 通过将所有代码都放在一个函数中, 用空白的线将各个部分分隔开来, 您可以实现同样的效果 。

在代码中找到 OOP 解决方案或设计模式的时空可能会适得其反。 归根结底, 真正重要的是, 它是否提供了优势? 它是否保存了代码? 它是否使代码易于维持和扩展? (代码 < em> 需要 容易扩展吗? ) ) 不要为 OOP 使用 OOP 的动作太快了 。





相关问题
Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

JSON with classes?

Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I d like to ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Passing another class amongst instances

I was wondering what is the best practice re. passing (another class) amongst two instances of the same class (lets call this Primary ). So, essentially in the constructor for the first, i can ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签