Home > Net >  Call chaining vs creating a variable
Call chaining vs creating a variable

Time:02-10

In this line, the name of my object is formatter, right? Since I gave it that name.

NumberFormat formatter = NumberFormat.getPercentInstance();
String result = formatter.format(answer)

I have another line of code that I wrote and it's a more clean version of this, using method chaining, that means I only have to write 1 line instead of 2 like the first one, I didn't have to give my NumberFormat class a name anymore, instead, I did this:

String resultz = NumberFormat.getPercentInstance().format(answerz);

Is resultz still an object? Or is it just a name that is labeling my line of code? Because I chained the method instead of doing it like my first line of code.

EDIT: I clarified more things

CodePudding user response:

In

NumberFormat formatter = NumberFormat.getPercentInstance();
String result = formatter.format(answer);

the formatter is a NumberFormat instance (an object of the class NumberFormat). The name of the variable is formatter.

String resultz = NumberFormat.getPercentInstance().format(answerz);

Here you skip the formatter variable, but the code does exactly the same as the previous version; result and resultz have the same class (String) and the same value (assuming answer and answerz have the same value).

Creating a variable vs chaining has no impact on the return type, format always returns a String. If it didn't, it would be a pain to use. Also, what else should it return?

Whether method call chaining is more clean or readable depends on the calls involved and personal taste.

  •  Tags:  
  • Related