Is it better to use local variables or chain methods inline? [closed]

末鹿安然 提交于 2019-12-12 19:28:36

问题


If I have a series of method invocations, the value of each used for the next call, should I store them in local variables, like so:

DynamicForm filledForm = Form.form().bindFromRequest();
String shareIdStr = filledForm.get("data[shareId]");
UUID shareId = UUID.fromString(shareIdStr);
Share share = Share.find.byId(shareId);

or as a single invocation chain, like so:

Share share = Share.find.byId(UUID.fromString(Form.form().bindFromRequest().get("data[shareId]")));

In this case, the only value that is used again is share. Perhaps the answer is somewhere in-between, or is something completely different. What's your opinion?


回答1:


Not chaining Methods :

ADV

  1. Enhances readability.

  2. Gives an opportunity for re-usage.

  3. Pin pointing exceptions (if any) becomes easier.

  4. Debugging becomes easier, i.e. setting breakpoints on specific invocation is easy.

DisADV

  1. Increases length( I wont say size :) ) of code.

  2. IDE warnings (if any).

Chaining Methods

ADV

  1. Reduces the need for creating multiple temp. variables.

  2. Is a syntactic sugar

  3. Reduces the number of lines to be written.

DisADV

  1. Reduces readability of code.

  2. Commenting becomes difficult (if any) for particular methods called.

  3. Debugging the whole chain of invocation becomes very difficult.




回答2:


The first way is only useful if you re-use these variables later in the method. If not, Eclipse will tell you they are not used. So the second way is better, I think.

To clarify a long line of code, I like to write it like this :

Share share = Share.find
                   .byId(UUID.fromString(Form.form()
                                             .bindFromRequest()
                                             .get("data[shareId]")                                   
                                         )
                   );



回答3:


You can only compare these two forms if you consider you will not reuse variables. Otherwise, it doesn't make sense to compare them.

Generally the first variant gives your code more readability and potentially makes it easier to maintain.

Personally I develop a lot for embedded systems where the target platform has big constraints on computation power and size. Therefore I typically inline the code, so that my bytecode is smaller.

If I am to develop an application to run on a powerful server, or even the regular PC, then I would most likely opt for variant one.




回答4:


Depends how you want to read your code. Local variables are useful if you are going to use them again. Otherwise proceed with chain invocation.



来源:https://stackoverflow.com/questions/24631848/is-it-better-to-use-local-variables-or-chain-methods-inline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!