非静态类中的专用静态字段

时间:2015-10-13 22:10:35

标签: c# solid-principles

有这样的课程:

class query extends Connection {

 // You need to call into your fille .. thant's it . safe query and safe // result :)
  public static function pdoQuery(){

      $query = $this->db->prepare("SELECT * FROM IP WHERE IP= :ip");
      $query->bindParam(':ip',$ip);
      $query->execute();
      return $query->rowCount();

  }

}
  1. 我使用静态字段很糟糕?预计Application的其他实例将使用相同的_applicationPath。
  2. 这是违反SRP原则(SOLID)的一个例子吗?我应该向其他班级提取“部署责任”吗?

2 个答案:

答案 0 :(得分:2)

  

我使用静态字段是不是很糟糕?

这取决于您使用用于的内容。在这种情况下,因为您使用非静态方法(Deploy()更改,所以是的,它可能很糟糕。如果所有实例都应该相同,那么在静态构造函数或属性中设置它(假设应用程序配置将设置它)。

  

这是违反SRP原则(SOLID)的一个例子吗?

这门课的职责是什么?您可以逻辑地提取DeployStart,还是要求另一个?

答案 1 :(得分:0)

  

我使用静态字段很糟糕?预计Application的其他实例将使用相同的_applicationPath。

我不认为这很糟糕。只要此字段为私有,您就可以随意使用它。在部署之后,请小心不要更改它。

  

这是违反SRP原则(SOLID)的一个例子吗?我应该向其他班级提取“部署责任”吗?

是的,我肯定会重构它并将部署与运行应用程序分开。目前,您的课程做了一件事,它运行流程并部署应用程序:

class Application
{
    private Process _process; 

    private static string _applicationPath;

    public void Start(string arguments)
    {
        var isDeployed = string.IsNullOrEmpty(_applicationPath);
        if (!isDeployed)
        {
            var deployment = new Deployment();
            _applicationPath = deployment.Deploy();
        }
        _process = Process.Start(_applicationPath, arguments);
    }

    public void SomeMethod()
    {
        //method that manipulate _process
    }    
}

class Deployment
{
    private static string _applicationPath;

    public string Deploy()
    {
        if (IsDeployed)
        {
            return _applicationPath;
        }

        // copying, installation steps (takes some time) and assign _applicationPath

        return _applicationPath;
    }
}
相关问题