对于一个将对给定数据进行一些处理的类,是在实例化上还是通过公共方法进行处理更好



我有一个关于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

你知道哪个最好吗?

关于"最佳实践"的一些内容是非常主观的。没有"只有坏"或"只有好",但"这是在这种情况下的最佳做法"。

我个人更喜欢第二个版本。因为:在指定参数之后,在执行方法的位置。

这样可以让你更好地控制行动。

操作是否要执行多次?

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

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

最新更新