Is this a good or bad way to use constructor chaining? (... to allow for testing).

Posted by panamack on Stack Overflow See other posts from Stack Overflow or by panamack
Published on 2010-03-23T23:50:12Z Indexed on 2010/03/23 23:53 UTC
Read the original article Hit count: 285

My motivation for chaining my class constructors here is so that I have a default constructor for mainstream use by my application and a second that allows me to inject a mock and a stub.

It just seems a bit ugly 'new'-ing things in the ":this(...)" call and counter-intuitive calling a parametrized constructor from a default constructor , I wondered what other people would do here?

(FYI -> SystemWrapper)

using SystemWrapper;

public class MyDirectoryWorker{

    //  SystemWrapper interface allows for stub of sealed .Net class.
    private IDirectoryInfoWrap dirInf;

    private FileSystemWatcher watcher;

    public MyDirectoryWorker()
        : this(
        new DirectoryInfoWrap(new DirectoryInfo(MyDirPath)),
        new FileSystemWatcher()) { }


    public MyDirectoryWorker(IDirectoryInfoWrap dirInf, FileSystemWatcher watcher)
    {
        this.dirInf = dirInf;
        if(!dirInf.Exists){
            dirInf.Create();
        }

        this.watcher = watcher;

        watcher.Path = dirInf.FullName;

        watcher.NotifyFilter = NotifyFilters.FileName;
        watcher.Created += new FileSystemEventHandler(watcher_Created);
        watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
        watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
        watcher.EnableRaisingEvents = true;
    }

    public static string MyDirPath{get{return Settings.Default.MyDefaultDirPath;}}

    // etc...
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing