Is using output parameters considered bad practice? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Every time I see a method were one of the parameters is an output parameter like
void addTokenErrorsToReport(List<String> tokens, Map<String, Integer> report)
I get the feeling that this is just plain wrong. From my point of view, parameters in general should be immutable, and not changed within a method. E.g., the above method could be rewritten to
Map<String, Integer> createTokenErrorsReport(List<String tokens)
The returned Map could then be merged with the original report Map.
Is this assumption right? Or are both versions equally acceptable?

As with most things, it's only "bad practice" if it leads to poorly functioning / unreadable / hard-to-maintain code or if you don't know why you're doing it.
In most cases using an output parameter doesn't have those effects.
In your addTokenErrorsToReport, it certainly is an appropriate approach. You are adding token errors to a report - the function needs to know the tokens it is adding and the report it is adding to. The function clearly performs precisely the operation it was designed to perform with no disadvantages.
If you were to take the createTokenErrorsReport approach, you would have to follow every call to it by inserting the new tokens in the existing report. If adding tokens to an existing report is a common operation, it most definitely makes sense to have a method that adds. That's not to say that createTokenErrorsReport shouldn't exist as well - if creating new reports from a token list is a common operation, then you would want a function that does that.
A great example of a good use of an output parameter is Collections.sort, which sorts a list in place. The performance hit of creating a new copy of the list and returning the sorted copy is avoided, while at the same time it does not limit you from creating a copy and sorting the copy if you want to.
Just use the best tool for the job and keep your code succinct.

How would you add something to the map in the second example? I think it would be bad practice if you have to pass an empty map that gets filled in addTokenErrorsToReport. But in this case: no, I don't think it's bad practice. How would you implement otherwise if you have several List<String> tokens that you want to process? I think the first example is the straightforward one.

I think it depends on where you come from (language). If you used to write c or c++, where you could use pointers as parameters, which is nice and practical, you could easily write code like your first example. I don't really think there is some kind of good or bad but just how your style of coding is.

I have seen this coding practice reasonably often and found it quite elegant. It allows you to 'return' multiple Objects.
For instance, in your above example, you could return an integer value corresponding to an error code.

Related

Java 8 stream vs List [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a set of private methods that are used in a main public method (that receive a list) of a class, these methods will mainly use java 8 classic stream operations as filter, map, count e.t.c. I am wondering if creating stream single time in public api and passing to others method instead of passing list have any performance benefits or considerations as .stream() is called single time.
Calling stream() or any intermediate operation would actually do nothing, as streams are driven by the terminal operation.
So passing a Stream internally from one method to another is not bad IMO, might make the code cleaner. But dont return a Stream externally from your public methods, return a List instead ( plz read the supplied comments, might not hold for all cases)
Also think of the case that applying filter for example and then collecting to a toList and then streaming again that filtered List to only map later is obviously a bad choice... You are collecting too soon, so dont chain methods like this even internally.
In general it's best to ask for what is actually needed by the method. If every time you receive a list you make it a stream, ask for the stream instead (streams can come from things other than lists). This enhances portability and reusability and lets consumers of your api know upfront the requirements.
Ask for exactly what you need, nothing more, nothing less.

Assign result of single operation method to variable before returning or just return? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
do you prefer writing method with immediate return of result to assigning it firstly to variable? To be clear we only consider situation presented below when no other operations are done in method body.
First option:
private List<Integer> getIdsOfUsersLoggedWithinLastHour() {
return userDAO.getUsersLoggedWithinLastHour().stream().map(User::Id).collect(Collectors.toList());
}
Second option:
private List<Integer> getIdsOfUsersLoggedWithinLastHour() {
List<Integer> ids = userDAO.getUsersLoggedWithinLastHour().stream().map(User::Id).collect(Collectors.toList());
return ids;
}
IMHO there is no need to assign result of method operations to variable when you do nothing with it and just return. The return type is declared in method signature so you can easily check it. The code cleanliness is about the same. You use some additional memory and cpu operations (maybe not so important today but it is always something additional). Friend of mine claims that initializing variable is better for easier debugging and further code development but I think it is redundant and can be done when you really need this, not 'for future'. What is your opinion?
In many cases I plump for the second option and, in the cited case, I almost certainly would.
This allows you to place a breakpoint on return ids; which can be helpful when debugging. (Inspecting the contents of a CPU register is an option in low level languages like C, but I don't think that is available for JVM-based languages).
A series of functions that return an anonymous temporary up the stack can be difficult to debug.
I wouldn't worry about any overhead that the second choice introduces: that ought to be optimised out and declaring an extra reference variable is unlikely to cause a performance bottleneck even if it was not optimised out. (Note that in C++ it will be optimised out via a process called Named Return Value Optimisation and I imagine that Java would follow suit.) Remember that being able to debug and maintain code is as important as elegance; whatever that means in this particular instance.
I assign result to the variable only when need to do some logic with it before returning value from the method. Otherwise I use coding style from the first example - makes code concise.
Second code style can help during debug process sometimes, but you shouldn't commit this IMHO
Also, if you inspect second example with any popular static analysis tool it would give a result like "local variable is redundant" which is one more reason to eliminate those vars in real projects.
Good article about this design issue: http://www.yegor256.com/2015/09/01/redundant-variables-are-evil.html
But you must understand that it's only a common practice, nobody can make you do not use redundant variables - code works with them correctly, it's only a question of taste like many other design principles

Should constructors do the computation for once needed long running tasks? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The following example is tailor made to make my doubts clear.
EG: WAP, with a method getAllWordsStartingInputChar to return the frequency of a word in the dictionary. The dictionary in form of a hashmap would be provided to the constructor.
Now, before getAllWordsStartingInputChar is called for the first time, I need to create another map of char->list of words begining with that char
Where should this map be created ?
In the constructor ?
Lazy initialization ?
Anything else ?
Please try to avoid being specific about my example, the idea i am trying to convey is 'some computation that needs to be done, whose results would be stored and used over and over again'.
Where should such computation be done.
Please try to avoid being specific about my example
Thats's no problem, because I cannot be too specific about this example when the example itself is not very specific (just kidding a little).
Seriosly, there is no problem to initialize a HashMap in the constructor
as long as you don't start a thread which uses these variables or call a method which do that or, also evil, call a overridable method in the constructor. Probably I forgot something.
Strategie of creation
If your Map list of words beginning with that char is used in each case, which means, there is no case in which you don't need the map, than you should create it during construction.
If these map is used very seldom, chose lazy initiaization, e.g. at the first call of a getter.
That is just my opinion without knowing very much about your needs.
Where should this map be created ?
1) In the constructor ?
Possibly.
2) Lazy initialization ?
Possibly.
3) Anything else ?
Probably not.
In purely performance terms, the choice between 1) and 2) depends on the probability that the constructed object won't use the second map. You need to balance the cost of the laziness (extra tests each time the map is used) versus the cost of creating the map unnecessarily.
The only "anything else" that I can think of is creating the second map each time that you use it. That only makes sense from a performance perspective if the map is only ever used zero or one time.
Where should such computation be done.
From a performance perspective, that's probably not relevant. From a design perspective ... you can make make a variety of arguments about where the code belongs. It is a matter of personal taste (IMO).
But looking back at the above comparison of 1) versus 2), the other observation is that this smells of "premature optimization", and premature optimization is often a complete waste of time. For more on that topic, read this: https://softwareengineering.stackexchange.com/a/80092/172.
If you have perfect information of how the costs will work out in practice, then the optimization is just "maths". But in practice, you rarely have enough information, and the mathematics is frequently too complicated. And general "rule of thumb" answers are not going to be reliable. Hence, each situation needs to be optimized on its merits ... based on real performance measurement. (If the effort is warranted!)

Is it better to use local variables or chain methods inline? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
If I have a series of method invocations, the value of each used for the next call, should I store them in local variables, like so:
DynamicForm filledForm = Form.form().bindFromRequest();
String shareIdStr = filledForm.get("data[shareId]");
UUID shareId = UUID.fromString(shareIdStr);
Share share = Share.find.byId(shareId);
or as a single invocation chain, like so:
Share share = Share.find.byId(UUID.fromString(Form.form().bindFromRequest().get("data[shareId]")));
In this case, the only value that is used again is share. Perhaps the answer is somewhere in-between, or is something completely different. What's your opinion?
Not chaining Methods :
ADV
Enhances readability.
Gives an opportunity for re-usage.
Pin pointing exceptions (if any) becomes easier.
Debugging becomes easier, i.e. setting breakpoints on specific invocation is easy.
DisADV
Increases length( I wont say size :) ) of code.
IDE warnings (if any).
Chaining Methods
ADV
Reduces the need for creating multiple temp. variables.
Is a syntactic sugar
Reduces the number of lines to be written.
DisADV
Reduces readability of code.
Commenting becomes difficult (if any) for particular methods called.
Debugging the whole chain of invocation becomes very difficult.
The first way is only useful if you re-use these variables later in the method. If not, Eclipse will tell you they are not used. So the second way is better, I think.
To clarify a long line of code, I like to write it like this :
Share share = Share.find
.byId(UUID.fromString(Form.form()
.bindFromRequest()
.get("data[shareId]")
)
);
You can only compare these two forms if you consider you will not reuse variables. Otherwise, it doesn't make sense to compare them.
Generally the first variant gives your code more readability and potentially makes it easier to maintain.
Personally I develop a lot for embedded systems where the target platform has big constraints on computation power and size. Therefore I typically inline the code, so that my bytecode is smaller.
If I am to develop an application to run on a powerful server, or even the regular PC, then I would most likely opt for variant one.
Depends how you want to read your code. Local variables are useful if you are going to use them again. Otherwise proceed with chain invocation.

shortening method/variable names? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it considered bad style to use long, but descriptive method names such as "adjacentLocationsByState()" and if so, would it be better to shorten it to something like "adjLocByState" which is definitely shorter, but also less readable in my opinion
Don't make me think.
When I read your code, if I have to stop and think about what the method name might mean, it usually means that the method name is wrong. Longer method names are preferable when it adds useful context to the method.
There are two rules I basically follow when writing code:
Must be readable as a normal text to which a human eye got used from books and mass media (so adjLocByState is not the case)
Maximize brevity, utilize programming techniques - code conventions and default states. These could be applied when some of the terms start appear to repeat too often.
So, adjacentLocationsByState() reads perfectly fine, but it could be shortened to just:
adjacentLocations()
which by default would return locations by their state and adjacentLocations(STATE) or chaining with fluent interface technique which allows more options for having the criteria: adjacentLocations().by(STATE). STATE here is a member of an enum LocationCriteria.
So in the end of the day it could look like:
adjacentLocations()
adjacentLocations().by(STATE)
adjacentLocations(STATE)
Of course, there is a time sacrifice which is spent on coding the 2nd and the 3rd forms.
Longer version is more readable and the the code is self documenting. So a good method name = method responsibility. Adj can be understand as adjust or adjacent, etc.
Keep in mind: Code is read 10 times more than it is written.!
You really write code that will often be read again and again. The more meaningful your names are, the more understandable is the code.
You are declaring classes, fields, methods, variables, and many more. You are thinking about them, you are developping a well-defined structure. All the time, you make hard decisions. The names that you give to your entities (classes, fields, ...) reflect all your thoughts on that. They reflect the intention of your code.
Conclusion: Names are the most important properties of your code. So, you always should think deeply about the names you give to your variables, methods, and so on. And you always should not abbreviate them in what way ever.
Its part of Documentation.
Usually everybody like to write Code in two phases before commit:
Implementation
Documentation
By example (phase 1):
ObjectOutputStream oos = ...
List a : ob.getSOE();
for(Object a: b){
oos.writeObject(a);
}
Then phase 2:
ObjectOutputStream stackOverflowElementOuputStream = ...
List stackOverflowElements : ob.getStackOverflowElement();
for(Object currentStackOverflowElement: stackOverflowElements){
stackOverflowElementOuputStream.writeObject(currentStackOverflowElement);
}

Categories