java coding style_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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值