Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the constructor logic code smell dependent on the type of code or quantity?

Logic in a constructor is a code smell. However, is it the quantity of code in a constructor which is bad or the type of code (is there certain code which would be allowed in a constructor?)?

Thanks

like image 444
GurdeepS Avatar asked Dec 05 '25 15:12

GurdeepS


1 Answers

The constructor's main purpose is to validate the context of the object creation (parameters, environment...) and to initialize the instance before any method can be called.

For instance, one of FileStream's constructors takes a file path and file mode in parameter and will throw an exception if the file does not exist.

IMO, as long as your code is validation/initialization logic, it is perfectly valid in a constructor even if it represents a lot of code. What could be fishy is code in a constructor that is not related to the validation of the context or the initialization of the instance.

like image 118
vc 74 Avatar answered Dec 08 '25 23:12

vc 74