首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止状态耦合?

防止状态耦合?
EN

Stack Overflow用户
提问于 2012-02-16 23:27:23
回答 1查看 65关注 0票数 1

我有以下对象和关系,

代码语言:javascript
复制
Lecture >- Tests
Test >- Questions

业务规则

代码语言:javascript
复制
When the lecture is started, a test can be given
If a test is being given, questions can be asked

推理

代码语言:javascript
复制
Therefore questions shouldn't be asked if the lecture hasn't been started.

问题模型

代码语言:javascript
复制
class Question
  belongs_to :test
  belongs_to :lecture, :through => :test

  def ask_question
    raise "Test not started!" unless test.started?
    raise "Lecture not started!" unless lecture.started?
  end
end

因此,很明显,问题模型的状态现在与测试和类的状态相耦合。

在创建单元测试时,为了测试这一点,我需要设置所有这些状态,这会变得相当笨拙,特别是在业务案例变得越来越复杂的情况下。

我怎样才能避免这种情况?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-20 13:07:10

我不熟悉Ruby关联,但在我看来,数据模型在这里与运行时逻辑混在了一起。

如果我为问题和测试建立一个数据模型,我会希望在测试中重用我的问题,并且在讲座中重用准备好的测试(问题集)。在这种情况下,我会这样写

代码语言:javascript
复制
class Lecture
  has_and_belongs_to_many :tests
end

class Test
  has_and_belongs_to_many :lectures
  has_and_belongs_to_many :questions
end

class Question
  has_and_belongs_to_many :tests
end

与这种结构分开,我会有一些与实时讲座、测试、问题和结果概念相对应的结构。结果是给定学生尝试回答实时问题。

我还将“委托”检查演讲会话的状态给测试会话。如果由于某种原因无法启动测试会话,则问题会话也无法启动。

要对问题会话进行单元测试,您只需模拟测试会话,要对测试会话进行单元测试,您需要模拟演讲会话,依此类推。

代码语言:javascript
复制
class Lecture_Session
  has_many :tests_sessions
  belongs_to :lecture
end

class Test_Session
  belongs_to :lecture_session
  belongs_to :test
  has_many :question_sessions

  def validate
    raise "Lecture not started!" unless lecture_session.started?
  end
end

class Question_Session
  belongs_to :question
  belongs_to :test_session

  def validate
    raise "Test not started!" unless test_session.started?
  end
end

class Result
  belongs_to :lecture_session
  belongs_to :test_session
  belongs_to :question_session
  belongs_to :student

  def validate
    raise "Question is not active!" unless question_session.active?
  end
end

希望这能有所帮助。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9313982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档