Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poor practice to include code in default constructor [duplicate]

Tags:

c#

oop

I worked with a developer that had many years my senior in C# experience. I no longer have a way to contact him and I remember him saying that it's not a good idea to include code in a default parameter less constructor but I cannot remember the reason why.

Is it good practice or bad practice to include code in the default constructor in C# or any language for that matter?

like image 351
broguyman Avatar asked Apr 26 '13 16:04

broguyman


People also ask

Is it bad practice to call methods in constructor?

Calling instance method in constructor is dangerous as the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on test-ability.

Can we have multiple default constructor?

There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.

Can we call constructor from method in Java?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.

Can constructor have methods?

Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.


1 Answers

It depends on the situation, but it is definitely NOT bad practice to put code in default constructors. If you need to, go ahead and do it.

like image 93
Jeff Avatar answered Oct 10 '22 19:10

Jeff