du6029076877 2013-04-24 13:26
浏览 67
已采纳

根据构造函数参数编写行为不同的类的规范

If you have a class that responds differently depending upon constructor arguments, how do you go about writing a spec for that class?

class Route
{
  function __construct($url, array $methods = array())
  {
    // stores methods and url in private member variables
    // creates a regex to match $url against incoming request URLs
  }

  public function isMatch($url)
  {
    // checks if the incoming request url matches against this url
  }
}

Example use:

$a = new Route('/users/:id');
$a->isMatch('/users/1') // returns true;
$b = new Route('/users');
$b->isMatch('/users') // returns true

If I set up my spec for this class using the let function from phpspec:

class Route extends ObjectBehaviour
{
  function let() 
  {
    $this->beConstructedWith('/users/:id')
  }
}

My spec can only check if the behaviour of this class works in one of the cases.

I've contemplated adding setter methods to allow me to test around this, but it seems like I'd be breaking encapsulation for the purpose of testing.

I'm struggling to find anything that touches upon this, so I'm started to think that maybe this is bad code smell situation.

  • 写回答

2条回答 默认 最新

  • dpiuqwwyu187975836 2013-04-24 13:35
    关注
    1. Constructor should be used only to obtain variables that will be set to a member properties here. No further logic should be done here...
    2. Following the idea from point 1 there should be another logic that determines what happens next (e.g. if Object->hasProperty(X) then do x(), etc.)
    3. Then a comment would be plain and straight forward.

    Example:

    class Route
    {
        private $url;
        private $methods = array();
    
        /**
         * Constructor method, sets the attributes to private member variables
         * @param string $url URL pattern
         * @param array $methods Methods that should be used with given URL
         */
        function __construct($url, $methods = array())
        {
            $this->url      = $url;
            $this->methods  = $methods;
        }
    
        // ...
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算