Dave
Dave

Reputation: 4060

Calling methods during a constructor call

I've been going through the Android development tutorials and I see a lot of calls like this:

String date = new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));

Seems like a nice shorthand way of doing things, but is this really a good practice? Will this have any negative side effects?

Upvotes: 1

Views: 135

Answers (5)

BVSmallman
BVSmallman

Reputation: 601

Negative side effects include:

  • Significantly higher WTFs per Second
  • Angry fellow programmers
  • Much harder to read code

That being said... there are cases where some methods in your code might almost always be called immediately which make sense. If you are in love with doing this I would say definitely no more than 1 extra method call, but in general I would still recommend against it.

Upvotes: 2

jeha
jeha

Reputation: 10700

Fluent interface or not, in this case I'd prefer something like:

String date = String.format("%d-%d-%d ", mMonth+1, mDay, mYear);

Shorter, better to read.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499860

Yes, that's fine - but it's not clear what you're concerned about. If you think that that's calling the append method during the StringBuilder constructor, it's not. This code is equivalent to:

StringBuilder tmp = new StringBuilder();
tmp = tmp.append(mMonth + 1);
tmp = tmp.append("-");
tmp = tmp.append(mDay);
tmp = tmp.append("-");
tmp = tmp.append(mYear);
tmp = tmp.append(" ");
String date = tmp.toString();

Each call to append will actually return this in StringBuilder, but in other similar APIs the object may be immutable and each method will build a new object and return that... the calling code would look the same.

(I assume the real code had a toString call, of course, otherwise it wouldn't have compiled.)

Note that this is actually equivalent to:

String date = (mMonth + 1) + "-" + mDay + "-" + mYear + " ";

... which is really rather more readable than the original code, and does the same thing. The Java compiler will use StringBuilder under the hood anyway. Of course, you should really be using SimpleDateFormat or Joda's DateTimeFormatter to format dates, of course...

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 612804

It's called a fluent interface.

The code does not call methods during the call to the constructor. It calls methods on the object returned by the constructor, after the constructor has completed.

Each of those method calls finish with return this and that is the key. That's what allows the calls to be chained together.

Upvotes: 6

CamelSlack
CamelSlack

Reputation: 573

No negative side affects, just makes it harder to read. A lot of developers go by the practice of the 'less code the better'.

Upvotes: 1

Related Questions