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);
}
Related
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
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!)
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
My computer science course wants me to start descriptively commenting out my code so that the teacher and other students can better understand it while reading it. Being 50% lazy and 50% elitist, I don't want to have to comment out every line just so that people can understand my code. I don't want to comment out every method unless that is really necessary either (the teacher only requires what is necessary for him to understand going on without having to try to interpret individual lines of code). What is accepted in the computer science universe as "enough commenting?"
Generally accepted guidelines for commenting are:
Non-trivial classes should have JavaDoc describing their usage / purpose. Documenting an object's thread safety is also frequently useful.
Non-trivial / non-obvious methods based on the method name should have JavaDoc. Ideally any requirements on the parameters should be noted (behaviour in regards to nulls etc), as well as any modifications to passed in Objects. Good rule of thumb is to answer:
What does this method require
What does it produce / guarantee (and when does it throw an exception)
What (if anything) does it modify
Any complicated or non-obvious lines of code should be commented
Where did this magic constant come from
Why is this being done (if not obvious)
Class variables can be commented when necessary. This is less standard, but it is sometimes useful to comment variables to indicate what it is to be used for.
Avoid comments that merely repeat what the code is doing. E.g.
// Set x to 4 before the loop
x = 4;
for (int i = 0; i < x; i++)
But, if appropriate, comment why it is being done:
// Set x to 4 since we are guaranteed to only have 4 threads
x = 4;
for ...
At a minimum, you should have good method comments (consider this the most important), and rough overview comments for your classes. I would consider anything less than this to be unprofessional and a reason for rejecting a code review.
In Java comments are used to generate a javadoc from the source code you have written. Format your comments according javadoc spec. That's enough for commenting in Java, other comments are optional and how someone mentioned comments are versus commented out code. If you keep such code in files you'd better leave a reasonable comment (i.e. referencing some issue, etc.). Note that using Java naming conventions and properly named Java elements greatly reduce needs for commenting inside the code. These comments are only intended for uses who will proof read or debug your code are optional as I mentioned above. Other optional comments are project related and tagged for example todo. You should concentrate more attention on javadoc comments, as general rule are placed on all public methods and classes including interfaces. if your class implements some interface method then you should not duplicate comment there, just reference a corresponding interface method comment.
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.
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.