【问题标题】:Naming Convention - Method name for getting data命名约定 - 获取数据的方法名称
【发布时间】:2023-04-02 13:33:01
【问题描述】:

以不同的视角扩展Method names for getting data

我有一系列 GetData 方法,它们以各种形式返回数据。我想知道用什么最好的方式来命名这些方法,既准确又有效。

  1. public DataTable GetData() - 返回给定表中的数据
  2. public List GetData() - 以对象列表的形式返回数据
  3. public DataSet GetData() - 当有多个数据表与查询关联时返回数据
  4. public objectx GetData(objecty) - 返回选中的对象
  5. public DataTable GetData(objecty) - 将选定对象作为表中的单行返回
  6. public DataSet GetData(objecty) - 返回选定的对象(例如:在主子的情况下)

【问题讨论】:

    标签: c# methods naming-conventions


    【解决方案1】:

    在 C# 中,不能有仅因返回类型不同而不同的方法重载。因此,您需要唯一的名称。

    我建议根据返回的内容使用命名。这也将使通过智能感知使用 API 时更加清晰。我还会使用比“数据”更具体的名称 - 例如,如果该方法正在检索代表客户的数据,我会使用:

    public DataTable GetCustomerTable() {
    public List<Customer> GetCustomers() {
    public DataSet GetCustomerDataSet() {
    
    public Customer GetCustomer(int id) {
    // I'd question whether these really belong at all...
    public DataTable GetCustomerAsTable(int id) { 
    public DataSet GetCustomerAsDataSet(int id) { 
    

    【讨论】:

    • 我同意你关于数据的具体名称的观点。但就我而言,这些是接口方法。
    【解决方案2】:

    命名是相当主观的,但在我看来,要拥有“好名字”有两件事要遵循。

    1. 要精确。
    2. 关注principle of least astonishment

    这两个原则对于维护很重要;如果您有一堆名为 GetData 的方法,人们将不知道会发生什么,并且会浪费时间阅读文档以找到合适的重载。

    您还希望拥有代表您所处的抽象级别的名称。因此,假设您想要获取一些名为 Page 的实体。在 DAO 级别,它很容易成为public DataTable GetPagesTable();,因为您正在处理表。在更高的抽象级别上,您可以使用 List 将其更改为 public List GetPages();(从名称中删除 Table)。您离数据库很远,所以名称应该反映这一点。

    如果您要传递对象或 ID,请在方法名称中明确说明以避免任何意外,例如 public DataTable GetPagesFromId(int id);

    从你的例子中,我可能会得到类似的结果:

    public DataTable Get<TableName>Table() - returns the data from a given table
    public List Get<ObjectName>s() - returns the data in the form of List of objects
    public DataSet Get<ComposedObjectName>() - returns the data when there are multiple data tables associated with queries
    public objectx Get<ObjectName>(objecty) - returns selected object
    public DataSet Get<ObjectName>AsMasterChild(objecty) - returns selected object (ex: in case of master-child)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多