Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DDD + Public Parameterless Constructors - Should They Exist?

One of the tenants of DDD is to not allow your objects to enter an invalid state. To me this means there shouldn't be a public parameterless constructor because that's going to be an object in an invalid state 99% of the time.

Is this a good way to move forward? It becomes a huge PITA when you just want to new-up a class real quick.

like image 956
Kyle West Avatar asked Oct 14 '22 17:10

Kyle West


2 Answers

Good question. I have DDD nazi friends who say parameterless constructors are the devil. I agree with that to a certain extent, but I also feel it depends on the class's purpose.

like image 117
Kilhoffer Avatar answered Oct 20 '22 16:10

Kilhoffer


As Kilhoffer stated, it depends on what you are trying to do with the class. Under what circumstances would you want to new-up a class without actually initializing properties? If you have instance methods you wish to call, which don't require any data, you might consider either marking those methods as static or moving the methods to a separate class. It's also possible that your class has one additional valid state - totally empty.

Personally, I believe in everything in moderation. If the PITA factor is high and you are reasonably sure you aren't going to run into problems, then it seems parameterless constructors would be fine. At some point I think it becomes a matter of opinion.

like image 28
Pedro Avatar answered Oct 20 '22 16:10

Pedro