Java - long one line statements vs multiple lines [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 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
)
);

Related

Is there a way to use python and java in the same program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want to use both python and java in the same program. Since the print() function of python is better, but java's int variable; is more efficient.
If I'm interpreting correctly, you want to use to use both interchangeably in the same file, so you'd end up with code like:
def main():
int x = 5;
print(x)
This is impossible, because there would be ambiguity when trying to interpret code if you allowed constructs from both languages. For example, "X" + 1 is allowed in java, and would give you the string "X1". In python, it would give you an error because you can't add an int to a string. This would mean that there would be no way to know what your code should do because it's runnable in both languages.
This is a problem that all of us face, where we like some parts of some languages and other parts of other languages. The solution is pretty much just to decide what's most important, choose one language based on that, and then put up with the parts you don't like.
You can use Jython, which is a Python implementation based on the JVM/JDK. This allows calling between Java and Python code in both directions.

Should I put if(variable < 10) in own method? [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 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.

Does using the Random class "unnecessarily complicate" things? [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 7 years ago.
Improve this question
I handed in an assignment recently, for my Computer Science course. In it I used the Random classover the Math.random() method in order to generate random numbers. My lecturer marked me down for this, stating that it was an "unnecessary complication" and that I should avoid importing classes when not absolutely needed.
I've nothing against her for this, and I accept that this is her preferred method that does have it's merits, but I would appreciate the opinion of a wider (perhaps more experienced) group- since Math.random() calls the Random class anyway and (afaik) creates a new Random object each time the method is called, wouldn't it make sense to just cut out the middleman?
Thanks
Math.random() does use Random, but it uses a single instance.
However since Math.random() is equivalent to Random.nextDouble(); which is usually not very useful, it would be foolish to use it instead of the Random class, which has plenty of convenience methods that make your intention clear and bugs less likely, as demonstrated in the following snippet.
int x = (int)(Math.random() * 100); // Without parentheses you'll always get 0
int y = rnd.nextInt(100);
I suspect your lecturer has a strong theoretical knowledge about programming.
I'd argue that your instructor is flat-out wrong. Maintainability should be one of your primary goals, and reproducibility is essential to debugging and maintainability. Math.random() gives you no control over the seeding, and consequently no reproducibility if something weird is noted during testing and debugging.
I would not be surprised if this question became closed for being too subjective.
But anyway -
I would say this depends on the context. Did your 'mistake' of using Random cause bad perfomance, unreadable code, or anything at all? If not, then I think it is fine.
One can nitpick about these kind of things, but in reality - in my opinion at least - there are larger things to worry about than such theoretical problems.

Where to put braces in Java While loop? [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
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
}

Is introducing underscores in literals in java beneficial or a drawback? [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
Though oracle technotes state that :
In Java SE 7 and later, any number of underscore characters (_) can
appear anywhere between digits in a numerical literal. This feature
enables you, for example, to separate groups of digits in numeric
literals, which can improve the readability of your code.
example : float pi = 3.14_15F;
is same as
float pi = 3.1415F;
But does it not become confusing to the developers working on code written by someone else?
Also does the use of underscore put any overhead on compiler or not?
But does it not become confusing to the developers working on code written by someone else?
Only if the developers don't understand the Java language! This construct has been been supported for long enough that every Java professional should recognize it ... even if they don't use it in their own code.
On the other hand, if your Java developers have not bothered to keep up to date with the new things in Java 7, they may be (temporarily) baffled. But the real solution is to educate your developers.
Also does the use of underscore put any overhead on compiler or not?
The overhead would be so small that it is impossible to measure.
There is no performance issue here.
The only time it would make any sense to use underscores is in a very large integer or with a binary integer. Like almost any bit of syntactical freedom the language provides, people are free to misuse it and write difficult to read code. I doubt this underscore thing will become a problem any more than the freedom to add extra white space is a problem.
The best example for when you would want to use this is with binary numbers where it is customary to place a space between every 4 bits.
For instance, compare:
int bitField = 0b110111011111;
int bitField2= 0b1101_1101_1111; //clearly more readable.
Other examples might include a credit card number or SSN as given in Oracle's documentation of this feature.

Categories

Resources