Java coding style - Part One

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 another, 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, instead 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 initialize 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 initialize 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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章