简体   繁体   中英

Java chained/nested method calls

I'm working on a JSONObject with multiple sub-JSONObjects. Here is the way I fill the content :

myJson.getJSONObject(CAT_NAME).put(VAR_NAME, var)
                          .put(VAR_NAME2, var2)
                          .put(...);

A friend told me that it is a very bad practice to use "nested function/method calls" and that I should do it this way :

myJson.getJSONObject(CAT_NAME).put(VAR_NAME, var);
myJson.getJSONObject(CAT_NAME).put(VAR_NAME2, var2);
myJson.getJSONObject(CAT_NAME).put(...);

From my view, my way is more like an chained method call than a nested one. And I don't like the second way because it force the program to get the same object again and again when the put() method already returns it.

Is my case is a "nested function calls" case ? Is this dangerous or bad for any reason ? And what are those reasons ?

edit : I don't feel like my question is duplicated. The other question involves chained methods but it mainly talks about c# interfaces.

Is my case is a "nested function calls" case ?

No that is method chaining (Builder pattern).

Is this dangerous or bad for any reason ?

No. Your friend is wrong. Not at all bad practice in your case. It's quite Ok since you are building a Json.

Using method chaining will actually be more efficient than the alternative you provided because myJson.getJSONObject(..) is only called once in the first case, whereas you call it many times in the second. There is a much more significant cost for calling getJSONObject(..) than there is for reusing the original object returned by it.

The correct way to accomplish this without using method chaining would be more like this:

JSONObject obj = myJson.getJSONObject(CAT_NAME);
obj.put(VAR_NAME, var);
obj.put(VAR_NAME2, var2);
obj.put(...);

Personally, I prefer to not use method chaining because I think it looks better, but ultimately it's your preference and the code here would have basically the same performance as your first chunk of code.

He PROBABLY considers it bad because it can be less readable (but that's a personal opinion and depends a lot on code formating, how well someone understands the specific APIs, is familiar with the concept of method chaining, etc. etc.).

It's certainly not a generally bad thing to do though. In fact a lot of APIs work exactly like that. Just look at StringBuilder in the Java standard API as a very commonly used example.
As others already pointed out it's potentially more performant (depending on how the called methods are implemented) as well, but that's not a given.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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