在构造函数中创建目录是一个坏主意吗?

HAL*_*000 3 c# directory installation constructor

起初看起来很自然 - 如果一组目录不存在,那么对它们起作用的对象将无法履行其合同.所以在构造函数中我有一些逻辑来检查是否存在某些目录,如果没有则创建它们.虽然实际上还不是单身,但这个对象就像一个一样.

构造函数是否适合这种设置逻辑?

背景
该类称为FileGetter.它抽象从远程服务器获取特定文件,提取它们,准备文件并将它们放在另一个目录中,其中第二个类将是filesystemwatching /处理数据.

cas*_*One 8

控制反转或依赖倒置的角度来看,是的,这是不正确的.

您声明在目录上工作的对象如果不存在则无法正常工作.我将目录的提供和检查/创建抽象到另一个抽象,然后将该抽象的实现传递给您的对象.

然后,您的对象将简单地从此抽象中获取目录并从那里继续.

举个例子,这就是我的意思.首先,有目录提供程序的抽象,如下所示:

public interface IDirectoryProvider
{
    // Gets the full paths to the directories being worked on.
    IEnumerable<string> GetPaths();
}
Run Code Online (Sandbox Code Playgroud)

然后是实施.

public sealed class DirectoryProvider
{
    public DirectoryProvider(IEnumerable<string> directories)
    {
        // The validated directories.
        IList<string> validatedDirectories = new List<string>();

        // Validate the directories.
        foreach (string directory in directories)
        {
            // Reconcile full path here.
            string path = ...;

            // If the directory doesn't exist, create it.
            Directory.CreateDirectory(path);

            // Add to the list.
            validatedDirectories.Add(path);
        }
    }

    private readonly IEnumerable<string> _directories;

    public IEnumerable<string> GetPaths()
    {
         // Just return the directories.
         return _directories;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您的类处理目录,如下所示:

public sealed DirectoryProcessor
{
    public DirectoryProcessor(IDirectoryProvider directoryProvider)
    {
        // Store the provider.
        _directoryProvider = directoryProvider;
    }

    private readonly IDirectoryProvider _directoryProvider;

    public void DoWork()
    {
        // Cycle through the directories from the provider and
        // process.
        foreach (string path in _directoryProvider.GetPaths())
        {
            // Process the path
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 听起来很危险,在某些时候,对象需要做实际的*工作*.OP的问题可以很容易地*关于IOC抽象的实现. (2认同)

Fre*_*örk 5

我会说这取决于.一般来说,使对象构造尽可能便宜是一个好主意; 也就是说,让构造函数包含尽可能少的逻辑.这反对在构造函数中创建目录.另一方面,如果没有目录,对象实际上根本无法运行,那么尽早失败可能是个好主意(例如,如果由于某种原因无法创建目录).这可以说是在构造函数中创建它们.

就个人而言,我可能倾向于不在构造函数中创建它们,而是让每个需要它们的方法调用一些创建目录的方法,如果还没有完成的话.