When do we want to privatize the default parameterless constructor?

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.
 
A

Arne Vajhøj

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?

Just remove it completely.

You only need to make it private when there are no other constructors.

Arne
 
C

csharper

Just remove it completely.

You only need to make it private when there are no other constructors.

Arne

Oh yeah, I forgot about that. What a shame. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top