【问题标题】:For a class that will do some processing on given data, is it better to do the work on instantiation or via a public method?对于将对给定数据进行一些处理的类,是通过实例化工作还是通过公共方法进行工作更好?
【发布时间】:2014-10-14 07:37:07
【问题描述】:

我有一个关于 OOP 最佳实践的问题。

假设我有一个类负责接收一些输入并进行一些处理以使输出结果可用。

是否建议提供所有输入并在实例化时进行处理,例如这样:

public class Processor
{
    private ProcessorConfig config;
    private ProcessorInputData inputData;

    public ProcessorResults Results { get; set; }

    public Processor(ProcessorConfig config, ProcessorInputData inputData)
    {
        this.config = config;
        this.inputData = inputData;

        Process();
    }

    private void Process()
    {
        // private function that does the processing using the the inputData
        // and constructs the public Results object
    }
    ...
} // class Processor

public class ProcessorExample
{
  public static Example()
  {
     ProcessorConfig config = GetConfigFromSomeWhere();
     ProcessorInputData inputData = GetInputDataFromSomeWhere();
     Processor processor = new Processor(config, inputData);
     ProcessorResults results = processor.Results;
  }
} // class ProcessorExample

或者最好在实例化(配置参数)时提供一些初始输入,并在需要对某些数据进行处理时调用一个单独的函数,如下所示:

public class Processor
{
    private ProcessorConfig config;

    public Processor(ProcessorConfig config)
    {
        this.config = config;
    }

    public ProcessorResults Process(ProcessorInputData inputData)
    {
        // public function to call with inputData,
        // doing the processing and returning a Results object
    }
    ...
} // class Processor

public class ProcessorExample
{
  public static Example()
  {
     ProcessorConfig config = GetConfigFromSomeWhere();
     Processor processor = new Processor(config);

     ProcessorInputData inputData = GetInputDataFromSomeWhere();
     ProcessorResults results = processor.Process(inputData);
  }
} // class ProcessorExample

你知道哪个最好吗?

【问题讨论】:

    标签: oop architecture


    【解决方案1】:

    关于“最佳实践”的一些东西是非常主观的。没有“只有坏的”或“只有好的”之分,而是“在这种情况下,这是一个最佳实践”。

    我个人更喜欢第二个版本。因为:方法执行的地方,参数赋值后。

    这使您可以更好地控制操作。

    这些操作会被执行多次吗?

    如果答案是肯定的,通常使用第二个选项。

    如果答案是否定的,只有一次,通常第一个选项是常用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      相关资源
      最近更新 更多