java - Cons of using setters during construction of classes? -


please note: i'm asking cons not whether or not pros out weigh cons of vice-versa not opinion based.

i working though java tutorial , tutorial recommend not using setters during construction (even if setter logic make sense in construction of instance). wondering why bad idea. tutorial made rather vague mention inheritance issues latter on.

also if setter validation take out validation separate function , able call function in constructor without having same issues using setter directly?

the major point (which tutorial trying @ inheritance) when you're constructing object if you're calling methods if setters overridden in subclass can cause problems. overridden version call subclass code subclass may not initialized yet (since subclass initializers , constructor haven't run yet), initialization may fail or have unexpected consequences. if limit calling of instance methods during construction call final methods can avoid issue.

there people put validation in setters not best practice. validation can added using annotations, or moved separate dedicated validation objects, can control under circumstances validation gets invoked. instance, in jpa persistent entities' getters , setters used orm implementation , validation code within them can in way. suggest looking ways remove validation setters.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -