Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Constructors Evil?

I recall reading an article about constructors being evil (but can't place it). The author mentioned that constructors are a special case of methods; but have restrictions (such as that they cannot have a return value).

Are constructors evil? Is it better to have no constructors and instead rely on a method like Initialize, along with default values for member variables?

(Your answer can be specific to C# or Java, if you must pin down a language.)

like image 628
ashes999 Avatar asked Dec 04 '22 08:12

ashes999


2 Answers

That sounds like Allen Holub. One might argue that constructors are evil solely to drive web traffic :) They are no more evil than any other language construct. They have good and bad effects. Of course you can't eliminate them -- no way to construct objects without them!

What you can do, though, and this is the case that Allen was making, is you can limit your actual invocation of them, and instead favor, when sensible, factory methods like your Initialize. The reason for this is simple: it reduces coupling between classes, and makes it easier to substitute one class for another during testing or when an application evolves.

Imagine if your application does something like

DatabaseConnection dc = new OracleDatabaseConnection(connectionString);
dc.query("...");

and imagine that this happens in a hundred places in your application. Now, how do you unit test any class that does this? And what happens when you switch to Mysql to save money?

But if you did this:

DatabaseConnection dc = DatabaseConnectionFactory.get(connectionString);
dc.query("...");

Then to update your app, you just have to change what DatabaseConnectionFactory.get() returns, and that could be controlled by a configuration file. Avoiding the explicit use of constructors makes your code more flexible.

Edit: I can't find a "constructors" article, but here's his extends is evil one, and here's his getters and setters are evil one.

like image 86
Ernest Friedman-Hill Avatar answered Dec 06 '22 09:12

Ernest Friedman-Hill


They aren't. In fact, there is a specific pattern known as Inversion of Control that makes ingenious use of Constructors to nicely decouple code and make maintenance easier. In addition, certain problems are only solvable by using non default constructors.

like image 37
Tejs Avatar answered Dec 06 '22 09:12

Tejs