简体   繁体   English

仅创建采用该类型实例的静态方法是不明智的做法

[英]Is it bad practice to only create static methods that take instances of that type

Take this class for example: 以此类为例:

public class Account
{
    public string Code { get; set; }
    public string Description { get; set; }
    public DateTime CreatedOn { get; private set; }  

    public void Create()
    {
        // Invoke with new Account({...}).Create();
    }

    //Or

    public static void Create(Account account)
    {
        // Invoke with Account.Create(new Account({...}));
    }
}

Both Create() methods will both do the same thing, but as you can see they are invoked differently. 这两个Create()方法都将执行相同的操作,但是如您所见,它们的调用方式有所不同。 Is one better practice over the other? 一种方法比另一种更好吗? Is there a term for writing code like this? 有写这样的代码的术语吗?

In this case I reccomend you don't use a static method, because you should create a lot of accounts and every account will have its own different properties. 在这种情况下,我建议您不要使用静态方法,因为您应该创建很多帐户,并且每个帐户都有其自己的不同属性。 But I think that the method Create() has no sense, beacuse you can use directly the constructor to set the account. 但是我认为Create()方法没有意义,因为您可以直接使用构造函数来设置帐户。 So here is how I would do: 所以这是我会怎么做:

public class Account
{
      public string Code { get; set; }
      public string Description { get; set; }
      public DateTime CreatedOn { get; private set; }  

      public Account()
      {
          Description = string.Empty;
          CreatedOn = DateTime.Now;
          //Code = ...
      }

      public Account(string Description)
      {
          this.Description = Description;
          CreatedOn = DateTime.Now;
          //Code = ...
      }
}

Ant then I would create another class to manage the accounts: Ant,然后我将创建另一个类来管理帐户:

class AccountsManagement
{
      public List<Account> Accounts
      {
           get;
           set;
      } 

      public AccountsManagement()
      {
           Accounts = new List<Account>();
      }

      //...   

      public void Create()
      {
           Accounts.Add(new Account();
      }

      public void Create(string Description)
      {
           Accounts.Add(new Account(Description);
      }

      //Or

      public void AddAccount(Account account)
      {
           Accounts.Add(account);
      }

      //Find(), Delete()...
}

So continuing the speech it isn't bad practice use static methods, but they should be used only when opportune. 因此,继续演讲不是坏习惯,而是使用静态方法,但只有在适当时才使用它们。

In general, I don't know that this is either good or bad practice. 总的来说,我不知道这是好事还是坏事。 However, I would lean towards 'bad practice' in the example you have given (and I can't off hand think of any useful reasons to pass an instance of a type to a static method declared on that type). 但是,在您给出的示例中,我倾向于“不好的做法”(而且我无法想到将任何类型的实例传递给在该类型上声明的静态方法的任何有用的理由)。

Certainly in your example, you are (IMO) creating an unclear API. 当然,在您的示例中,您(IMO)正在创建一个不清楚的API。 I'm not sure whether; 我不确定是否;

  • Account.Create is meant to issue data storage requests for an account (functionality that certainly belongs elsewhere in your object model) Account.Create旨在为帐户发出数据存储请求(功能肯定属于对象模型中的其他功能)
  • is some sort of 'convenience' method for creating an instance of Account using some default set of parameters (which would arguably be better in a constructor of Account) 是一种使用某些默认参数集创建Account实例的“便捷”方法(可以说在Account的构造函数中会更好)
  • is meant as a copy constructor (in which case, it should be a constructor) 用作复制构造函数(在这种情况下,它应该是构造函数)
  • is a cheap implementation of an AccountFactory (in which case you should make a factory!) 是AccountFactory的廉价实现(在这种情况下,您应该建立工厂!)

Another consideration is testing - static methods can introduce difficulties when unit testing anything that calls them, as they may not be easy to mock or stub. 另一个考虑因素是测试-静态方法在对任何调用它们的内容进行单元测试时可能会带来困难,因为它们可能不容易模拟或存根。

Apart from those, there is nothing inherently 'wrong' about this, technically. 除了这些,从技术上讲,这没有天生的“错误”。 It affects your design in other ways though (eg; no access to instance members as it is not an instance). 但是,它以其他方式影响您的设计(例如,由于它不是实例,因此无法访问实例成员)。

So, I think this approach can lead to some confusion, however, it might also be entirely appropriate for your situation! 因此,我认为这种方法可能会引起一些混乱,但是,它也可能完全适合您的情况!

If both the static and instance versions of the method will do the same thing then I would definitely use the instance method version. 如果该方法的静态版本和实例版本都将执行相同的操作,那么我肯定会使用实例方法版本。 For a few reasons: 有几个原因:

  1. Less code to write . 编写更少的代码 Would you rather constantly write Account.Create(accountObj); 您是否愿意不断编写Account.Create(accountObj); or just accountObj.Create(); 或仅仅是accountObj.Create(); ?
  2. Intellisense . 智能感知 When I have a custom object and I can't remember all the methods I've made on it, it often helps me to type accountObj. 当我有一个自定义对象时,我不记得自己使用的所有方法,通常可以帮助我键入accountObj. and get the drop down menu to see what methods it uses. 并从下拉菜单中查看使用的方法。 If you use the static version, the method will not show up and it might take you a few seconds to remember how to use/find the Account.Create() method. 如果使用静态版本,则该方法将不会显示,并且可能需要花费几秒钟的时间来记住如何使用/查找Account.Create()方法。
  3. It just makes sense . 这是有道理的 If you have a method that works on a single instance of a custom object, it is an instance method. 如果您有一个可用于自定义对象的单个实例的方法,则它是一个实例方法。

The only reason, in my humble opinion, to use the static version over the instance is if you need keep the Create() method from having access to private members of the account object. 以我的拙见,在实例上使用静态版本的唯一原因是,您是否需要使Create()方法不能访问帐户对象的私有成员。

The only reason i can think of to use such static methods as your Create, is the cases where you make ur default constructor private, and wish to control the creation of instances only via ur helper method. 我可以想到使用诸如Create之类的静态方法的唯一原因是,您将默认构造函数设为私有,并希望仅通过helper方法来控制实例的创建。
Such design is actually used by microsofts expression trees framework, where u create the instances via static methods of th expression class, however they also have a more complicated hierarchy of abstract classes in between 这种设计实际上是由Microsoft表达式树框架使用的,其中您是通过表达式类的静态方法创建实例的,但是它们之间还具有更复杂的抽象类层次结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使无状态方法静态化是好是坏做法? - Is it good or bad practice to make stateless methods static? 为 DbSet 创建扩展方法是一种不好的做法吗<t> ?</t> - Is it a bad practice to create extension methods for DbSet<T>? 创建新实例还是使用公共静态方法? - create new instances or use public static methods? 在我的Web服务中有很多私有静态方法是不好的做法 - Is it bad practice to have lots of private static methods within my Webservice 在ASP.Net MVC中,是否使用静态方法在视图上查找缓存对象的不良做法? - In ASP.Net MVC, is using static methods to look up cached objects on views bad practice? 将构建器方法与服务方法相结合 - 不好的做法? - Combining builder methods with service methods - bad practice? 使用IOC容器时,在库中使用New关键字创建实例是否被认为是不好的做法? - Is it considered bad practice to create instances using the New keyword inside a library when using an IOC Container? 全局静态类和方法都不好吗? - Are global static classes and methods bad? 知道表单只有一个实例,在表单不好的情况下使用静态属性吗? - Is using a static property in a form bad practice knowing that there's only one instance of the form? 这对静态类和线程安全来说是不好的做法吗? - Is this a bad practice with static classes and thread safety?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM