码迷,mamicode.com
首页 > 编程语言 > 详细

Java coding style - Part one

时间:2015-10-16 16:51:21      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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.

Java coding style - Part one

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!