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.
Related
I've read here why Optional.of() should be used over Optional.ofNullable(), but the answer didn't satisfy me at all, so I ask slightly different:
If you are SURE that your method does not return null, why should you use Optional at all? As far as I know, the more or less only purpose of it is to remind the "user of a method", that he might have to deal with null-values. If he does not have to deal with null-values, why should he be bothered with an Optional?
I ask, because I recently made my service-layer return Optionals instead of nulls (in certain situations). I used Optional.of() and was highly confused when it threw a NullPointer.
A sample of what I did:
Optional valueFromDB = getUserById("12");
User user = valueFromDB.get();
.....
public Optional<User> getUserById(String id) {
//...
return Optional.of(userRepository.findOne(id)); // NullPointerException!
}
If null is not possible, I don't see why one would wrap it in an Optional. The dude in the linked answer said "well, if a NullPointer happens, it happens right away!" But do I really want that? If the sole purpose of an Optional is, to remind the programmer who gets such an object, to keep null in mind (he HAS to unwrap it), why should I want to have NullPointerException at wrapping-time?
Edit: I needed to edit the question, because it got marked as duplicate, even though I already linked said question from the start. I also did explain, why the answer did not satisfy me, but now I need to edit my text with an explanation.
But here is some appendix to what I want to ask, since I got 5 answers and everyone answers a different case, but none fully covered what I try to ask here:
Is there a reason, that Optional.of(null) is impossible and they specifically added Optional.ofNullable() for the null case?
Using streams should not be the problem with my idea of the implementation.
I got a lot of insight from your answers, thanks for that. But the real question has not been answered until now, as far as I can tell/read/understand.
Maybe I should have asked: "What if we remove the Optional.of() method and only allow Optional.ofNullable() in Java 9, would there be any problem except backwards-compatibility?"
You are mixing up the API design rationale with knowledge within a particular implementation code. It’s perfectly possible that a method declares to return an Optional, because the value might be absent, while at a certain code location within the method, it is known to be definitely present. I.e.
String content;
public Optional<String> firstMatch(String pattern) {
Matcher m = Pattern.compile(pattern).matcher(content);
return m.find()? Optional.of(m.group()): Optional.empty();
}
This method’s return type denotes a String that might be absent, while at the code locations creating an Optional instance, it is known whether the value is present or absent. It’s not about detecting a null value here.
Likewise, within the Stream API methods findFirst() and findAny(), it will be known at one point, whether there is a matching element, whereas supporting the conversion of its presence to absence in case of a matching null element is explicitly unsupported and supposed to raise a NullPointerException, per specification. Therefore, Optional.of will be used to return the matching element, which you can easily recognize in the stack trace when using Stream.of((Object)null) .findAny();
The other reason to use Optional.of(value) when you know that value can't be null is that if you want to do additional filtering operations on that Optional.
For example:
public static long getPageSizeFrom(HttpServletRequest request) {
return Optional.of(request.getParameter("pageSize"))
.filter(StringUtils::isNumeric)
.map(Long::valueOf)
.filter(page::hasPageSize)
.orElse(page::getDefaultPageSize)
}
I think you are right with your opinion that you should not use Optional if you are sure that you always have a return-value.
But your method is not sure, that it always returns a value!
Think of an call to getUserById(-1). There is (normally) no User with this id, and your userRepository will return null.
So in this case you should use Optional.ofNullable.
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ofNullable-T-
Optional is one of those things that has been imported from functional programming languages and dumped into the laps of OO and procedural programmers without much background explanation...which has caused much pain and hand wringing.
First, a quick link to a blog post (not by me) which greatly helps to clear the air on this: The Design of Optional
Optional is related to functional programming types like Haskell Maybe. Because of the way strong typing works in functional programming, a programmer in that language would use Maybe to say that a value can be either Something, or Nothing. The Something and Nothing are actually different types, here. Anything that needs the values inside a Maybe has to handle both - the code simply won't compile if it doesn't handle both.
Compare that scenario to what is the typical situation in C-based object-oriented languages (Java, C#, C++, etc.) where an object can either have a value, or be null. If a method needs to handle null parameters as an edge case, you need to explicitly write that code - and being the lazy programmers we all are, it's just as often we don't bother to.
Imagine what coding would be like if code wouldn't compile unless null cases were always explicitly handled. That's a pretty close comparison to what happens when using Maybe in functional languages.
When we pull language features over from functional programming, and the compiler behaves the way it always has, and we code the way we always have... you can see there's a disconnect happening.
Separately, Optional can be used as a simple stand-in for null. Because it seems familiar that way, and is new, magpie developers are prone to using it as a replacement for situations where null-checks would have happened before. But, in the end, is foo.isPresent() really so different than foo != null. If that is the sole difference, it's pointless.
And let's not even get started on how Optional can be a stand-in for autoboxing and unboxing in Java.
Now, getting back to your specific question about the particular API of Optional in Java, comparing ofNullable() vs. of(), the best I can work out is that you probably aren't expected to use those in typical code. They are mainly used at the terminal end of stream() operations. You can look at the code to Optional.of() vs. Optional.ofNullable() and see for yourself that the only difference is that ofNullable checks if the value is null and arranges things for that situation.
My jaded eye doesn't see a whole lot of benefit to using Optional in Java, unless I am using Java 8 streams and I have to. Some would say that the main benefit of using Optional as a type for non-stream usage is to specify that a particular parameter is optional - that is, the logic takes a different route if it's there vs. not there. Which, again, you can simply do with null. But I would say that the mental baggage associated with Optional means that for every forward step of supposedly more verbose code, you are taking multiple steps backwards with requiring people to understand that the Optional (in this specific case) is almost entirely cosmetic. For the situation you described, I would probably go back to using nulls and null checks.
Angelika Langer says that Optional.ofNullable is only a convenience-method, calling the other both static methods from Optional. It is implemented as:
return value == null ? empty() : of(value) ;
Also she says that Optional.ofNullable was added lately to the API.
Here is her text in german language: http://www.angelikalanger.com/Articles/EffectiveJava/80.Java8.Optional-Result/80.Java8.Optional-Result.html
So I would use Optional.of only when null is an error, which should be found early. This is what Tagir Valeev said in:
Why use Optional.of over Optional.ofNullable?
The practical answer is: on most occasions, no. As you mention, if the whole point of using Optional is not knowing if a value can return null, and you want to make it explicit in certain API, the fact that .of() can throw a null exception does not make any sense. I always use ofNullable.
The only situation I can think of is if you have a method that returns Optional (to make explicit this null-value possibility), and that method has a default/fallback value under some circumstances, you will return a "default value" Optional, using .of().
public Optional<String> getSomeNullableValue() {
if (defaultSituationApplies()) { return Optional.of("default value"); }
else {
String value = tryToGetValueFromNetworkOrNull();
return Optional.ofNullable(value);
}
}
Then again, someone can question whether in that case you can return this default value in case of a null.
Metaphysical discussions aside, IMHO if you use Optionals, and want them to make any sense and not throw exceptions, use ofNullable().
I agree that Optional.of is counterintuitive and for most use cases you would want to use Optional.ofNullable, but there are various purposes for Optional.of:
To explicitly throw a NullPointerException if the value is null. In this case Optional.of functions as a Guard.
When the value simply cannot be null. For instance, constants like Optional.of("Hello world"!). This is a programming esthetics thing. Optional.ofNullable("Hello world!") looks weird.
To turn a non-null value into an Optional for further chaining with map or filter. This is more a programming convenience thing. Just like Optional.stream() exists to turn an Optional into a Stream for further chaining.
"What if we remove the Optional.of() method and only allow Optional.ofNullable() in Java 9, would there be any problem except backwards-compatibility?"
Yes, of course there will be compatibility issues. There's just too much code out there using Optional.of.
I agree with your general sentiment though: Optional.of is doing too much (wrapping the value and null-checking). For null-checks we already have Objects.requireNonNull which is conveniently overloaded to accept a descriptive text.
Optional.of and Optional.ofNullable should have been discarded in favor of a constructor made available for users:
return new Optional<>(value);
For null-checks this would have sufficed:
return new Optional<>(Objects.requireNonNull(value, "cannot be null!"));
Is it generally considered bad practice to structure code with embedded expressions in method parameters? Should variables be declared instead?
(Android code snippet for an example)
((EditText)view.findViewById(R.id.fooEditText))
.setText(
someExpression
? getResources().getString(R.string.true_expression_text)
: getResources().getString(R.string.false_expression_text)
);
Personally I think it looks fine, but am just wondering if this is considered repulsing :)
I would almost certainly simplify that, in a number of ways:
EditText editText = (EditText) view.findViewById(R.id.fooEditText);
String resourceName = someExpression ? R.string.true_expression_text
: R.string.false_expression_text;
editText.setText(getResources().getString(resourceName));
Doing it all in one statement makes it harder to read and harder to debug, IMO. Note that I've also removed duplication here, but using the fact that you were calling getResources().getString(...) in both operands of the conditional operator, just with different resource names.
My main beef with the original code is calling a method on the result of a cast - aside from anything else, it introduces more brackets than you need, which is generally confusing.
I'd say this depends on the situation, for instance.
player.setName(User.getName());
Would be fine, however, train wrecking such as below...
player.setName(getGroup().getUsers().get(0).getName());
I'd say is bad practice and is mentioned in Clean Code by Bob Martin regarding the dangers of train wrecks. Also duplicate calls as mentioned by #Jon Skeet is another reason to use a variable rather than a method call.
The word "repulsing" was yours, but it certainly describes my reaction. I can't focus on what this statement is doing because it has an if statement, a search, and at least 5 dereferences happening before it gets started.
I find the trinary operator particularly pernicious, since I have to hold two disjoint sets of state in my mind while I parse everything else. Some folks prefer brevity to local variables (I'm not one of them) but trinary operators (or any other branch) embedded in other statements are especially unloveable. If you ignore the rest of Clean Code or similar works because you enjoy complex statements, at least separate the conditionals out.
At the company I work for there's a document describing good practices that we should adhere to in Java. One of them is to avoid methods that return this, like for example in:
class Properties {
public Properties add(String k, String v) {
//store (k,v) somewhere
return this;
}
}
I would have such a class so that I'm able to write:
properties.add("name", "john").add("role","swd"). ...
I've seen such idiom many times, like in StringBuilder and don't find anything wrong with it.
Their argumentation is :
... can be the source of synchronization problems or failed expectations about the states of target objects.
I can't think of a situation where this could be true, can any of you give me an example?
EDIT The document doesn't specify anything about mutability, so I don't see the diference between chaining the calls and doing:
properties.add("name", "john");
properties.add("role", "swd");
I'll try to get in touch with the originators, but I wanted to do it with my guns loaded, thats' why I posted the question.
SOLVED: I got to talk with one of the authors, his original intention was apparently to avoid releasing objects that are not yet ready, like in a Builder pattern, and explained that if a context switch happens between calls, the object could be in an invalid state. I argued that this had nothing to do with returning this since you could make the same mistake buy calling the methods one by one and had more to do with synchronizing the building process properly. He admitted the document could be more explicit and will revise it soon. Victory is mine/ours!
My guess is that they are against mutable state (and often are rightly so). If you are not designing fluent interfaces returning this but rather return a new immutable instance of the object with the changed state, you can avoid synchronization problems or have no "failed expectations about the states of target objects". This might explain their requirement.
The only serious basis for the practice is avoiding mutable objects; the criticism that it is "confusing" and leads to "failed expectations" is quite weak. One should never use an object without first getting familiar with its semantics, and enforcing constraints on the API just to cater for those who opt out of reading Javadoc is not a good practice at all— especially because, as you note, returning this to achieve a fluent API design is one of the standard approaches in Java, and indeed a very welcome one.
I think sometimes this approach can be really useful, for example in 'builder' pattern.
I can say that in my organization this kind of things is controlled by Sonar rules, and we don't have such a rule.
Another guess is that maybe the project was built on top of existing codebase and this is kind of legacy restriction.
So the only thing I can suggest here is to talk to the people who wrote this doc :)
Hope this helps
I think it's perfectly acceptable to use that pattern in some situations.
For example, as a Swing developer, I use GridBagLayout fairly frequently for its strengths and flexibility, but anyone who's ever used it (with it's partener in crime GridBagConstraints) knows that it can be quite verbose and not very readable.
A common workaround that I've seen online (and one that I use) is to subclass GridBagConstraints (GBConstraints) that has a setter for each different property, and each setter returns this. This allows for the developer to chain the different properties on an as-needed basis.
The resultant code is about 1/4 the size, and far more readable/maintainable, even to the casual developer who might not be familiar with using GridBagConstaints.
I am starting to learn Android programming with Java, mainly from online Android documentation. I also looked through several books but they don't seem to address this issue: a feature of Java syntax which I have come across several times and which is a mystery to me. Here is just one example from about half-way through the Contacts Provider documentation at
http://developer.android.com/guide/topics/providers/contacts-provider.html
I have removed the comments to unclutter the code snippet:
op =
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType);
This is all one statement, I think. What is confusing me is all those "dot operators" that look as though they belong in a Visual Basic "with clause". Where can I find out what all this means?
youre looking at a builder pattern, where the return value of each such with* method is the builder itself (or the object, if its not a builder exactly). theyre handly when you want to chain a lot of setters, or when there are a lot of constructors for the underlying object and you dont want people using it to get confused. or, as fge stated below, when you want the returned object to be immutable (so it cant have setters).
more specifically to your case, the return value of ContentProviderOperation.newInsert() is a ContentProviderOperation.Builder, all of who's methods return itself. usually such a chain of configuration calls will end in a call to build(), which will produce an operation.
This is an instance of so called fluent interfaces (link to wikipedia). There is noting special about it: the value returned from the previous call is being used as the target of the subsequent call.
API like this present a useful alternative to methods with lots of optional parameters, because the resulting code is much easier to read and understand. The code is somewhat more verbose, but in this case it is a good thing, because the parameters passed to constructors get better "tagging". This style is also preferable when you have multiple parameters of the same type (say, strings) next to each other, because it lets the readers avoid parameter counting.
each of those methods returns an ContentProviderOperation.Builder object that has been modified by the method. So you can chain together calls to methods like that and do everything in a more compact way. It's similar to how jQuery works in the javascript world.
It may clear things up a bit to look at the newInsert method on the Android documentation, then look at the documentation for the ContentProviderOperation.Builder class. note that all of the methods on that object also return ContentProviderOperation.Builder objects.
I am sure this is more of a subjective question however I am curious people's oppinions...
Today at work I saw the following method....
public T execute(T dto){...return dto;}
This seemed redundant to me, in my mind this was better....
public void execute(T dto)
For now in this method lets say the following is called....
dto.setProperty(something);
But a colleague (and a few StackOverflow posts) suggest this is bad because it doesn't suggest that the method may be altering the T object. However this should be reflected on the object in the stack so why do I need a return.
Is this a valid reason, to me it seems to me this has to cause increases in overhead (although in all fairness we are using Java here)
Any insight as to which is better?
This depends on what T is, whether T is immutable, and what execute does. This question couldn't really be more generic and specifics matter.
void addPerson(Club clubFullOfPeople, Person person);
T clone(T t);
would both be valid and strike me as good design.
To answer your exact question - should you return to signal mutability? That absolutely strikes me as something that would signal IM-mutability if anything so, no, absolutely not, but you need clearer variable names, documentation etc. to communicate this.
It's not an unreasonable style, it's simply a decision that should be made (project by project) - go with the style used in the working environment. Next project/job may choose differently.
Neither style implies that the DTO can or cannot be altered. In fact, if anything, the first form would rather suggested that the parameterized DTO is not being altered, but if there are changes that are being made, they will be made in the returned object.
Advantages of returning the DTO:
Calls can be chained (this may be good or bad depending on the coding style and the use of the actual methods/objects). For example jQuery is built such that just about every call can be chained.
You can return a null value or some other object/form of the DTO to signify a failure of some sorts
In your "preferred" notation, the only way you can signify a failure is via Runtime Exceptions. Without know what the execute method is supposed to accomplish, this may be okay, or may indicate a larger problem in that Exceptions are being used to handle flow control (a bad thing).
Net result? I don't think there is a "better" solution - just something that matches more what you are currently doing in your existing codebase.