Let’s say we have
public interface ITimestampProvider { DateTime GetTimestamp(); }
and a class which consumes it
public class Timestamped { private ITimestampProvider _timestampProvider public Timestamped(ITimestampProvider timestampProvider) { // arg null check _timestampProvider = timestampProvider; } public DateTime Timestamp { get; private set; } public void Stamp() { this.Timestamp = _timestampProvider.GetTimestamp(); } }
and a default implementation of:
public sealed class SystemTimestampProvider : ITimestampProvider { public DateTime GetTimestamp() { return DateTime.Now; } }
Is it helpful or harfmful to introduce this constructor?
public Timestamped() : this(new SystemTimestampProvider()) {}
This is a general question, i.e. timestamping is not the interesting part.
I think it depends on the scenario, and is basically a function of who the consumer the code is (library vs. application) and whether you’re using an IoC container or not.
If you’re using an IoC container, and this is not part of a public API, then let the container do the heavy lifting, and just have the single constructor. Adding the no-args constructor just makes things confusing, since you’ll never use it.
If this is part of a public API, then keep both. If you’re using IoC, just make sure your IoC finds the ‘greediest’ constructor (the one with the most arguments). Folks not using IoC, but using your API will appreciate not having to construct an entire dependency graph in order to use your object.
If you’re not using an IoC container, but just want to to unit test with a mock, keep the no-args constructor, and make the greedy constructor internal. Add InternalsVisibleTo for your unit test assembly so that it can use the greedy constructor. If you’re just unit testing, then you don’t need the extra public API surface.