You have an immutable object, and you set its internal variables in the constructor which accepts couple of parameters.
Question:
Do you see any problems to VALIDATE constructor parameters in the constructor method of an immutable object and throw ArgumentExceptions if not valid?
(to me it makes sense but I wanted to ask in case there are some better ways or something not OK with this – for example if it is a better design to move validation from constructor to a factory)
Or if I generalize it by rephrasing the question:
Is it OK to put business rules-wise logic in the constructor methods? Or should constructors always do nothing more than setting object’s internals?
Thanks
In a way, it makes sense to validate in the constructor itself because you know that all usages of it will pass through that single point, and any other developer that will use your code will be protected from making mistakes because of your “low-level” validations.
If you move the validation higher up the call chain, you leave the class code cleaner but you expose the code to the possibility of “you’re using it wrong” bugs.