`
leonzhx
  • 浏览: 793968 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 40: Design method signatures carefully

阅读更多

1.  Choose method names carefully. Names should always obey the standard naming conventions. Your primary goal should be to choose names that are understandable and consistent with other names in the same package. Your secondary goal should be to choose names consistent with the broader consensus, where it exists.

 

2.  Don’t go overboard in providing convenience methods. For each action supported by your class or interface, provide a fully functional method. Consider providing a “shorthand” only if it will be used often. When in doubt, leave it out.

 

3.  Avoid long parameter lists. Aim for four parameters or fewer.

 

4.  The first technique for shortening long parameter lists is to break the method up into multiple methods, each of which requires only a subset of the parameters. (i.e. operations on sublist of a List can be divided into List.subList and other method of List.)

 

5.  A second technique for shortening long parameter lists is to create helper classes to hold groups of parameters. Typically these helper classes are static member classes. This technique is recommended if a frequently occurring sequence of parameters is seen to represent some distinct entity. 

 

6.  A third technique is to adapt the Builder pattern from object construction to method invocation especially if some of them are optional. It can be beneficial to define an object that represents all of the parameters, and to allow the client to make multiple “setter” calls on this object, each of which sets a single parameter or a small, related group. Once the desired parameters have been set, the client invokes the object’s “execute” method, which does any final validity checks on the parameters and performs the actual computation.

 

7.  For parameter types, favor interfaces over classes.

 

8.  Prefer two-element enum types to boolean parameters. It makes your code easier to read, to write, and to add more options later.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics