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
I understand that Java ignores indentation and that curly-brace hierarchies are recommended to increase readability of code. I come from Python with decent experience and I am learning Java right now. I am completely new to Java and I don't yet know the "Good Coding Practice" that comes with writing while loops.
Here are 2 ways to create a basic while loop:
while ( booleanCondition = true ) {
// do stuff
}
And the second way:
while (booleanCondition = true )
{
// do stuff
}
I am not one for splitting hairs over the number of lines of code, so the fact that the first loop is one line shorter is irrelevant to me. Personally, I like the second better because the loop is left-justified with only the condition on the top line. However, I don't want to start using this format if it is not recommended for Good Practice. Is the first way to do the while loop more/less recommended? What is the most common format if there is one?
Both works. This is actually based more towards the programmer's preference and style.
The second one is better since the bracket should start right below its name. It would be least confusing if you use nested loops or conditions. Anything nested would go one level inner and you would never make mistake of brackets and code would be perfectly readable.
while (booleanCondition = true )
{
//do stuff
while (booleanCondition = true )
{
//do stuff
}
}
In this you perfectly know which bracket is ending where. Every bracket ends right below it and there are no brackets in between. Simple and elegant style of coding.
Two schools of thought:
1) In 1997 Sun published a set of "Coding Conventions" for Java. They specify pretty much everything you can think of when it comes to writing Java code - indentation, variable naming, etc, etc: http://www.oracle.com/technetwork/java/codeconventions-150003.pdf . Follow those rules.
2) Do it however you'd like, but keep it consistent. There's any number of styles, etc out there (See: http://en.wikipedia.org/wiki/Indent_style) - pick one, use it in all files in a project.
Java conventions prescribe the first method.
7.6 while Statements
A while statement should have the following form:
while (condition) {
statements;
}
This is also the most commonly used one.
But in the end, it's up to yourself. Just keep it consistent within the project.
It depend on the developer , but basically java doc and IDE prefer the 1st option.
Also if the booleanCondition is boolean you dont need to check == with true :
while (booleanCondition) {
// do stuff
}
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 4 years ago.
Improve this question
I have a check in a loop where I have to check if the number of occurrence is less than 10 which could be written as either
if(occ < 10){
}
or
if(checkIfOccurencyIsLessThan10(occ)){
values.add(current+"0"+occ);
}
else{
values.add(current+occ);
}
I'm reading Clean Code a handbook of agile software craftsmanship, where they say a method should do the least amount, and code should be hacked up into more pieces. Is this necessary right here? I'm trying to get a better grasp on how long a method should be, and how much it should be doing.
It depends on if this condition is spread across multiple pieces of code, and if this check could change in the future to include checking additional edge cases. If both of those things are true or could be true, then sure, extracting the check to its own function is wise. However, I would definitely say you should rename the function to not specify the functions implementation, because that defeats the purpose of being able to change out the conditional, right? Naming it something like occurenceNeedsZero is a much more flexible solution. Because if you come up with other use cases that need checking you can add them to this function as well!
However, if your question is "should I always make a simple conditional check such as "is x < 10" into its own function, then I would say no. That would be overengineering, in my opinion. Functions should be used to 1) separate logical portions of code, 2) increase readability, or 3) extract small pieces of code that are spread across multiple locations and likely to change in the future, as it simplifies future refactoring.
There are probably more cases than those 3, but those are the big ones.
It's better to use a static final variable to store this 10, instead hard code.
If there are other places need to check if occ < 10, you need extract it as a method. Otherwise it is unecessary.
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
My question is general. When should I consider splitting a statement to multiple lines?
I'm writing code on my own, and never worked in a team. I always prefer to make my code as compact as it can get.
For instance, instead of writing:
depth = depth - randomNumbers.nextInt(depth) -1;
Expression expA = createRandomExp(depth);
Expression expB = createRandomExp(depth);
SubtractionExpression subExp = new SubtractionExpression(expA,expB);
return subExp;
I will just write:
return new SubtractionExpression(createRandomExp(depth - randomNumbers.nextInt(depth) - 1), createRandomExp(depth - randomNumbers.nextInt(depth) - 1));
The pros as I see it are:
Less lines of code.
No need for declaration of variables.
Cons:
Can be less readable
Some stuff are written multiple times, like: randomNumbers.nextInt(depth) -1
What are the standards in the industry? And what should I consider when writing statements? Some guidelines might help.
I came over this, but it doesn't really answer my question.
Multiple lines make easy to read when another developer needs to read your code, and use comment lines to clarify functions, variables, classes, etc. Also, You may leave the company you work and someone needs to improve your code or there may be a dysfunctionality in your code so in case of those reasons, you should write your code with multiple lines in order to makes it easier to read and understand.
There should not be any standarts to my knowledge but above reasons will be enough to write codes with multiple lines not in a one line.Additionaly, when you get compiler error while writing single line codes, compiler will say "error found in X line" and you may not be able to understand where is the error in that line. However, multiple lines will ease the situation. I suggest you to write multiple lines instead of single line.
It is good practice to not declare one-use variables. I really like aproach, when you use your "(" bracket as "{" bracket, like:
return new SubtractionExpression(
createRandomExp(
depth - randomNumbers.nextInt(depth) - 1
),
createRandomExp(
depth - randomNumbers.nextInt(depth) - 1
)
);
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 code that looks like this:
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your name"); name = scan.nextLine();
As opposed to:
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your name");
name = scan.nextLine();
Which one is generally regarded as better practice?
The usual convention is to put each statement on its own line. According to Google's style guide:
4.3 One statement per line
Each statement is followed by a line-break.
The second snippet in your question complies with this rule. Following conventions makes it easier for people to read each others' code.
Note you can use an IDE to format your code (CTRL+SHIFT+F in Eclipse) and it will move this around for you.
Regardless of standards, following the style used in existing code is usually a good idea. Especially, reformatting in the same check-in as code changes makes it hard to see what changed when bringing in new versions.
In a team situation, formatting is not the place to express your individuality. Use the same formatting as the other people on the team. Reformatting wars between team members who have their IDEs set with different formatting rules are really annoying.
Also, not declaring variables until they're used is the preferred style. Declaring a local variable without assigning a value means it can't be used until something assigns it a value anyway.
You should always try to make your code as readable as possible. And generally, your code is more readable the better formatted it is. Placing two statements on the same line is usually seen as harder to read then having each statement get it's own line.
The rule (yahoo) when modifying; code exactly like (in the style of) the programmer who wrote the original code. When writing new code code exactly like the other programmers on the team. If it's just you then whatever you think is the most readable. Keep in mind some source indentation tools will separate multi statement lines.
Your example seams to make a little more sense to me if coded in-line.
String name = scan.nextLine();
Either of course, are allowable. This comes down to personal preference and what you see as more readable. Seeing that a program is written out line by line, and there's logic in each line, I'd opt for the second one. It makes it a little easier to understand what's going on, and easier to debug in my eyes. Performance wise, there's absolutely no difference between the two. To more directly answer your question, in my eyes, it's never appropriate.
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 4 years ago.
The community reviewed whether to reopen this question 8 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I ran my program successfully when declaring a class name starting with a lower case letter. I don't understood why it is asked to start with first capital letter.
You can declare it with lower case, but the convention is to start with a capital letter. The conventions were created to make it easier on others to read and understand your code.
Unlike this definition :
class someClass
{
otherClass b = null;
}
Sticking with the conventions even helps Stack Overflow color your code in a way that makes it more readable :
class SomeClass
{
OtherClass b = null;
}
It's not a matter of can but rather a matter of should. Java naming conventions dictate that class names should begin with an upper case letter. By following conventions, others (including us and your instructors, bosses and co-workers) can better understand and evaluate your code. If you need our help in the future with your code, this can make a big difference. There can be some local variability in some specific rules, so you will want to learn and follow all the specific rules of your office / school.
For more on this, please see Java Naming Conventions.
Also, some code editors/IDEs will hyphenate or space out related generated code file names based on capitalization in your class file.
For instance, Android Studio(https://developer.android.com/sdk/installing/studio.html) will read a Java Activity's class name, and insert a hyphen or underscore when you transition from a capital to a lower case letter for the file name of the layout.
An example: When creating a new activity(which is just a new class) called "MyActivity.java", Android Studio will also create a new layout file called "activity_my.xml" and link to it in the java file.
By sticking to the convention of capitalizing your class names, not only is your source code easier for others to follow and learn, but it will be much easier for you to navigate and keep track of files in your project. Naming conventions are everything.
Nothing happens if class names are lower case or upper, as long as the the code runs, then it shouldn't be a problem.
Its doesn't matter whether you choose uppercase or lower case but just for code to be readable without ambiguity.
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
I'm taking an online intro-to-Java course. In the lesson on ArrayLists, there's an exercise in which we're given an ArrayList of Picture objects, and asked to call draw() on the first Picture that's in portrait orientation. We're given some code to start with:
// BlueJ project: lesson7/gallery8
// Find and draw the first portrait in the gallery.
// Notice the pseudocode from the instructions has been started for you; your task is to complete it.
import java.util.ArrayList;
public class ListOfPictures
{
public static void main(String[] args)
{
ArrayList<Picture> gallery = new ArrayList<Picture>();
gallery.add(new Picture("degas1.jpg"));
gallery.add(new Picture("gaugin1.jpg"));
gallery.add(new Picture("monet1.jpg"));
gallery.add(new Picture("monet2.jpg"));
gallery.add(new Picture("renoir1.jpg"));
int i = 0;
boolean found = false;
while ()
{
}
if (found)
{
....draw();
}
}
}
It seemed pretty clear to me what they expected us to do. Still, I thought it would be better to make a function and return from a for-each loop, rather than using a found and a counter variable. This is what I came up with:
public static void main(String[] args)
{
// declare/initialize/populate gallery
Picture firstPortrait = findFirstPortrait(gallery);
if (firstPortrait != null)
firstPortrait.draw();
}
private Picture findFirstPortrait(ArrayList<Picture> gallery)
{
for (Picture pic : gallery)
if (pic.getHeight() > pic.getWidth()) // pic is in portrait
return pic;
return null; // there aren't any images in portrait
}
They seemed to really dislike it, though. When I submitted my code, I got this back:
ListOfPictures.java: Keep looking for matches while found is false
Score
0
Which is the better way of doing this? In general, should I avoid using “flag” variables like that?
EDIT: Yes, it is automatically graded. I've actually gotten an error on other exercises saying that the grader didn't know how to deal with my code and that I should post it on the forum (which looks suspiciously like Stack Overflow, only that no one seems to know how to use it).
I will be linking to this question on the forum. :)
You're asking for an opinion, of course. Both ways, if implemented correctly, will produce identical output.
That said, your way is:
cleaner
clearer
more reusable
and avoids unnecessary variable use.
Whoever graded your question either doesn't know much Java or is being unnecessarily pedantic or harsh.
Claasic example of teacher wanting student to know difference between when to use for loop and when to use while loop. Use while loop when you don't know how many ierations it will take to find what you're looking for. Use 'for' loop when you know the exact number of iterations
Use the for-each-return pattern. In this case, the flag is an unnecessary state variable that would easily lead to code rot in a more complicated program.
Your way is better, if that's what you're asking.
My programming prof would have preferred the ẁhile solution. He said that every exit of a method or loop (loop condition, break, return, continue) makes it more difficult to trace an error or to prove a property of a method.
In my opinion, this is a personal decision. There are good reasons for both options.
For each is generally geared towards operating on EVERY item in the arraylist. With the found flag, you are basically stopping at the first instance when it is found.