简体   繁体   English

链接方法调用还是引入中间变量更好?

[英]Is it better to chain method invocations or to introduce an intermediate variable?

Eg 2 method invocations: 例如2方法调用:

myMethod(getHtmlFileName());

or 要么

String htmlFileName=getHtmlFileName();
myMethod(htmlFileName);

which is better way, exclude less typing in first case ? 哪种方法更好,在第一种情况下排除了较少的键入?

If you are going to use a return value of a method in more than one place, storing it in a variable and using that variable in your code could be more practical, readable and easily debuggable rather than calling the method every time: 如果要在多个地方使用方法的返回值,则将其存储在变量中并在代码中使用该变量可能更实用,易读且易于调试,而不是每次都调用该方法:

String htmlFileName = getHtmlFileName();
myMethod(htmlFileName);
....
myMethod(htmlFileName + "...");

The second approach would help you debug the return value of getHtmlFileName(), but other than that, neither approach is better than the other in an absolute sense. 第二种方法将帮助您调试getHtmlFileName()的返回值,但除此之外,从绝对意义上讲,这两种方法都不比另一种更好。 It's a matter of preference, and perhaps context, I would say. 我想说,这是一个偏好问题,或者是背景问题。 In this particular case I'd go for the first approach, but if you were combining several methods, I'd go for the second, for sake of readability, eg: 在这种特殊情况下,我会选择第一种方法,但是如果您将几种方法组合在一起,那么出于可读性考虑,我会选择第二种方法,例如:

String first = firstMethod();
String second = secondMethod(first);
String third = thirdMethod(second);

rather than 而不是

thirdMethod(secondMethod(firstMethod()));

EDIT: As others have pointed out, if you're going to use the value in more than one place, then obviously you'd use the second approach and keep a reference to the value for later use. 编辑:正如其他人指出的那样,如果您打算在多个地方使用该值,那么显然您会使用第二种方法并保留对该值的引用以备后用。

It will probably depend on the context. 这可能取决于上下文。 If you are going to use htmlFileName variable elsewhere in you code block you probably what to store it local variable like (especially true for some heavy method calls) : 如果您打算在代码块的其他位置使用htmlFileName变量,则可能会将其存储在本地变量中(例如,对于某些繁重的方法调用尤其如此):

String htmlFileName=getHtmlFileName();
myMethod(htmlFileName);

if it is one-off call the 如果是一次性的,请致电

myMethod(getHtmlFileName());

is probably more elegant and easy to read. 可能更优雅,更易于阅读。

If you use the getHtmlFileName() returned value later on, and if the returned value is fixed, you will want to use the first form, ie assign a local variable and reuse it, and thereby avoid redundant calls / object creations. 如果稍后使用getHtmlFileName()返回值,并且返回值是固定的,则将要使用第一种形式,即分配局部变量并重用它,从而避免重复调用/对象创建。

Otherwise (eg if you only call the getHtmlFileName method once, you will want to use the first form which is more concise, and which avoid a useless local variable assignment, but there is no real harm if you still use the second form (eg for debugging). 否则(例如,如果您只调用一次getHtmlFileName方法,则您将希望使用更简洁的第一种形式,并且避免了无用的局部变量赋值,但是如果您仍然使用第二种形式(例如,对于调试)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM