C
csharper
I am not sure if this example will make it clear.
Suppose we have a public class Engine and public class Car:
public class Engine
{
//snip
public void Ignite()
{
//snip
}
}
public class Car
{
private Engine engine;
public Car()
{
}
public Car (Engine engine)
{
this.engine = engine;
}
public void Start()
{
this.engine.Ignite();
}
}
Now, in Program.cs, if I do this:
public class Program
{
Car bmw = new Car();
bmw.Start();
}
I will have a problem, because the Start() method depends on a valid Engine object, whereas the default parameterless constructor Car() neither creates one nor receives one.
So, when I run into such situation, I tend to privatize the default parameterless constructor. In other words, the Car class would look like:
public class Car
{
private Engine engine;
private Car()
{
}
public Car (Engine engine)
{
this.engine = engine;
}
public void Start()
{
this.engine.Ignite();
}
}
This way, I cannot instantiate a car without passing it an Engine. However, I am not sure if this is considered good practice. Any idea? Thank you.
Suppose we have a public class Engine and public class Car:
public class Engine
{
//snip
public void Ignite()
{
//snip
}
}
public class Car
{
private Engine engine;
public Car()
{
}
public Car (Engine engine)
{
this.engine = engine;
}
public void Start()
{
this.engine.Ignite();
}
}
Now, in Program.cs, if I do this:
public class Program
{
Car bmw = new Car();
bmw.Start();
}
I will have a problem, because the Start() method depends on a valid Engine object, whereas the default parameterless constructor Car() neither creates one nor receives one.
So, when I run into such situation, I tend to privatize the default parameterless constructor. In other words, the Car class would look like:
public class Car
{
private Engine engine;
private Car()
{
}
public Car (Engine engine)
{
this.engine = engine;
}
public void Start()
{
this.engine.Ignite();
}
}
This way, I cannot instantiate a car without passing it an Engine. However, I am not sure if this is considered good practice. Any idea? Thank you.