Java coding style

Java coding style:

1. Factory method should be stateless.

State normally refers to the member variables of class. Stateless, more precisely, it means immutable.

Factory is just to create objects, and one call should not affect anothers, if it is mutable, then the method call mnight have the chance to change the states.
and then it would affect other calls which are not supposed to happen.

2.
Restrict the access level of all the class members as much as possible, this conforms to principle of encapsulation

3.
Assert to validate the parameters of constructor, this way to avoid the invalid data of member variables as early as in the construction stage
e.g. in Spring, if you assert to validate the values, intead of leaving the error to later, application even won't be able to start up when Spring tries to initialise these objects.

4.
Try best to use constructor to initialise the object, this way you can validate the assigned values to member variables, you can construct the object
in one place.

e.g. in Spring, using constructor to init the beans, you can make the member variables as "final", this way, the member variables get assigned and initialised
early in the construction stage, you don't have to create an empty object first and then set the fields using setters. What' more, the member variables won't be exposed to others
in this case, so you get a better access control over these member variables.

原文地址:https://www.cnblogs.com/glf2046/p/4885408.html