Constructor injection and default overloads

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.

Answers


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.


Need Your Help

Why does the iOS Safari user agent stylesheet appear to override my margin style on the body?

html ios css ipad margin

Why does the following markup result in body having an 8px margin on iOS (latest iPad) (and hence a vertical scrollbar)?

Quickly add + to positive strings

php integer

Hay all, is there a PHP function which adds "+" to positive strings?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.