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.
Yes! Java supports constructor overloading. In constructor loading, we create multiple constructors with the same name but with different parameters types or with different no of parameters.
Definition. Constructor Injection is the act of statically defining the list of required Dependencies by specifying them as parameters to the class's constructor. The constructor signature is compiled with the type and it's available for all to see.
Example 1: Constructor overloadingWhen the object person1 is created, the first constructor is called because we have not passed any argument. This constructor initializes age to 20 . When person2 is created, the second constructor is called since we have passed 45 as an argument.
Functions are the building blocks and Constructor is a special method that have same name as that of class. Constructors are invoked at the time of object creation. When a class has two or more methods with same name but with different parameter list is known as method overloading.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With