On Thursday, April 26, 2012 7:07:40 PM UTC-4, Arne Vajhøj wrote:
> On 4/26/2012 2:44 PM, csharper wrote:
> > 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
Oh yeah, I forgot about that. What a shame. Thanks.
|