Suppose a Car Validator and many methods that read its attributes to valid them.
Thus, the best way to structure it is to make Car an instance field.
Two ways of making it :
1) make a constructor taking a Car as argument and then call validate().
2) Remove all constructors but rather pass Car to validate method as arguments: validate(Car car).
If we imagine that this validator must continuously validate, let’s say 500 cars.
With the 1) method, 500 validator objects must be instanciated … Even if Garbage collector is doing its job really well, it doesn’t seem to be the best practice.
The benefit is that initialization of Car field is made by constructor => so more natural way.
With the 2) method, we avoid the drawback of the 1) but we have to init Car field into the method validate, that means after object construction. Is that considered as a good practice? Indeed, only validate method use Car field and furthermore, there is only validate method that is not private.
Of course, there is a third way to do this for avoiding all doubts => pass Car from validate method toward each private methods…but I find this very ugly…
Which of the three methods should I choose ?
I think the 2nd approach is an antipattern and should be avoided, it resembles the infamous
SimpleDateFormatclass (it looks like stateless and thread safe, but it’s not).Regarding the other approaches, if you really have many private methods it would be better to use the 1st approach, otherwise you can use the 3rd approach, it doesn’t look too ugly for me.
Also note that using the 1st approach “as is” involves more coupling than the 3rd one. In the 3rd case you can decouple clients of validator from its implementation by injecting a preconfigured instance of validator, whereas in the 1st case you need to introduce a factory to achieve the same effect.