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
Sorry for posting a rather vague question here - but I've been struggling to find a definitive answer to this one - maybe there is none, but just thought asking fellow developers.
Last week, a colleague of mine mentioned that the length of constructors (In Java and in OOP in general) should be kept to a minimum. While I do agree the approach in general, he went on to say that it should be only a few lines - 3-4 lines at maximum.
I'm not sure how he arrived at this number and I wonder how useful that approach is. If you have some complex initialisation to perform, your constructors will exceed that limit.
You can split and break and refactor your code into smaller functions till cows come home, I prefer to keep related code into one method and avoid un-necessary functions as it makes code more readable.
This at times does lead to situations where constructors are fairly moderate in size - 50-100 lines of code in worst scenarios, but then even if I break it up into functions, technically speaking, that code is still "called as part of initialisation". So, 100 lines of code might be replaced by a single function call, but that 100 lines still get called when you call the function?
I also looked at checks type default definitions and it has default constructor length set to 150, which sounds more reasonable "Than a few lines code".
Would love to know what you guys follow as rule of thumb or if there is, indeed, such a accepted upon limit.
Good rule of thumb is that any method (or constructor) should fit on one screen in your IDE so you don't have to scroll down when you are trying to read and understand what is this method doing (so it improves readability).
Nothing prevents you from making exception from time to time but you should generally split really long methods to smaller chunks because I've really seen methods few hundred lines long and it really made me cry when I had to change the code.
This is just a common practice but not anything. I have made classes that had a lot of code in constructors. I also had classes with no constructor. As mentioned above, there is no such thing that you should not contain a lot of code in constructors, and JVM loads them too.
So why this concept came up? It is because people think that constructors are for initializing variables in objects since they are called only when new instances are created. Also doing a lot of work in the constructors makes no point in using OOP principles. OOP itself means 'Object Oriented Programming' which is meant to structure code as objects. So I'm leaving the conclusion to you. See the both examples and think which one is better.
Example 1:
public Dog(String name)
{
System.out.println("Dog " + name + ": Bark!Bark!");
}
Example 2:
public Dog(String name)
{
this.name = name;
}
public void bark()
{
System.out.println("Dog " + name + ": Bark!Bark!");
}
In the first example, the dog barks only once, but in the second example, you can make the dog bark as many times as you want. And for this same reason, they say to use constructors only for initializing values.
Hope this helps.
I've been struggling to find a definitive answer to this one - maybe there is none
You are right. There isn't a definitive answer. It is subjective.
Would love to know what you guys follow as rule of thumb ...
I don't. I use my judgement on a case-by-case basis. Subjectively.
... or if there is, indeed, such a accepted upon limit.
There isn't. You won't find any specified limits in the main-stream Java coding standards. A decent coding standard won't be prescriptive about this because it is counter-productive.
On the other hand, this is the kind of situation where code reviews can be beneficial. If you see an "overly long" constructor or method, it is worth pointing out, especially if there is a good refactoring available; i.e. one that your colleagues would agree improves readability.
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 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 7 years ago.
Improve this question
There is an explanatory code of what I'm trying to ask. Sureley, the difference between the codes below is ignorable, yet it describes the point.
Which one is the most efficient in terms of memory usage and performance?
if( MathUtil.CalculateSin(angle) > Angles.ACUTE){
// Something is done
}
or
double angleSin = MathUtil.CalculateSin(angle);
if( angleSin > Angles.ACUTE){
// Something is done
}
It simply depends if you are going to re-use the variable.
If yes, use the second case.
If no use the first case.
There is no reason to store the value in a variable if you are not going to re-use it.
Edit :
As per your comment, it seems you are mostly asking this question for performance concern...
Actually my question is not about the algorithm nor the way I
implement it. I'm curious about the memory usage of the approaches,
therefore efficiency is the purpose.
Don't expect any difference in term of memory usage for both approaches, the JVM and JIT will optimize it as much as possible so that both case become the same.
To extend the other answers, you should also consider readability of your code. In this case, the meaning of MathUtil.CalculateSin(angle) is pretty obvious. However, if you have a more complex condition, it would be a good idea to precompute that condition, give the variable a meaningful name and then use the variable in the if-statement.
In your case it also depends on the context of the if-statement. Again, MathUtil.CalculateSin(angle) > Angles.ACUTE is quite easy to grasp at a glance. However,
final boolean angleIsAcute = (MathUtil.CalculateSin(angle) > Angles.ACUTE);
if(angleIsAcute) { ... }
would carry the meaning better. In this case, of course, both possibilities are quite similar, but I hope you see where I am going with this.
Do not worry about the overhead that is introduced by storing that extra variable. Even though the java-compiler does not optimize your code, any JVM worth its salt will optimize the bytecode and the performance overhead will be negligible.
I often use the first pattern even when I won't need the variable later in the code. The advantage is for debugging.
You can examine and change the value of the variable when stepping through the code in a debugger.
If an exception occurs in the call on the right-hand side of the statement, it is sometimes clearer what happened than if the call is embedded in an if or as an argument to another call.
If you're concerned about memory usage for the variable, don't be. Trust the compiler to optimize away variables that it knows aren't going to be used later. If you declare the variable final, it will be optimized aggressively as described in the JLS.
References do take memory. So if you are not going to use angleSin anywhere else then second option is what you should go for. Besides it does not pollute the namespace. That is one reason people make Comparator as an anonymous class instead of creating a new one. If they do not need to use somewhere else.
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
I've seen some legacy code that uses lengthproperty on some objects and others that uses length() method. Currently I'm working with a NodeList from the org.w3c.dom package and I found that it have the getLength() method to get the numbers of elements.
My Question is how as Java developer I can know how to determine when to use length, length(), size(), getLength()? obviously it depends of the object type and the API is there for read... but the point is how the Java Development select which of that implements in their classes.
Note: In the Question When to use .length vs .length() Makoto answer's indicates that .length is a property on arrays. That isn't a method call, and length() is a method call on String. But, why is the reason? why not use ever a method or ever a property for maintain the consistency around all the API.
how would Java developers select which of [the methods] to implement in their classes?
When you implement classes that contain other objects, it's almost always going to be size(), the method provided by theCollection interface.
As far as other choices go, you should avoid exposing member variables, even final ones, because they cannot be accessed through an interface. Java gets away with it for arrays because of some JVM trickery, but you cannot do the same. Hence, length should be out: it remains in Java because it's not possible to change something that fundamental that has been in the language from day one, but it's definitely not something one should consider when designing new classes.
When you implement your own type that has length (say, a rectangle or a line segment) you should prefer getLength() to length() because of Java Beans naming conventions.
obviously it depends of the object type and the API is there for read...
You already have answered your question yourself: look in the API documentation of whatever class you are using.
but the point is how the Java Development select which of that implements in their classes.
The classes in Java's standard library have been developed over a long period of time by different people, which do not always make the same choice for the name of methods, so there are inconsistencies and unfortunately you'll just have to live with that.
There is no clear rule, otherwise we wouldn't see such a mixup in the jdk itself. But here are some things to consider when making such a design decision.
Don't worry to much. It is a minor thing and won't make to much of a difference. So when you think longer then 5 minutes about this, you are probably wasting money already.
Use getters when a frameworks need them. Many frameworks depend on the getter style. If you need or want such frameworks to work nicely with your class it might be beneficial to use that style.
Shorter is better. the 'get' part doesn't increase clarity. It just generates to characters of noise to the source code, so if you don't need it for some reason, don't use it.
Methods are easier to evolve. Length is often a quantity that is not set directly but somehow computed. If you hide that behind a method it gives you the flexibility to change that implementation later on, without changing the API.
Direct field accesses should be a tiny bit faster, but if you aren't working on high volume online trading or something, the difference isn't even worth thinking about. And if you do you should do your own measurements before making a decision. The hotspot compiler will almost for sure inline the method call anyways.
So if there aren't any external forces driving you in a different direction I would go with 'length()'
According to OOPS principles, length should be attribute and getLength() should be method. Also length attribute should be encapsulated should be exposed through methods, so getLength() sounds more appropriate.
Unfortunately not all Java library classes follow standards. There are some exceptions and this is one among them.
In a pure OO language it should be probably always a method like length(). So in a class hierarchy you can override the attribute length.
But Java is not pure OO. And the main reason for fields (.length) vs method (length()) is/was performance issues.
And even Sun/Oracle programmers did some bad class design.
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 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);
}