As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Apart from readability, are there any differences in performance or compile-time when a single-line loop / conditional statement is written with and without brakets?
For example, are there any differences between following:
if (a > 10)
a = 0;
and
if (a > 10)
{
a = 0;
}
?
Of course there is no difference in performance. But there is a difference in the possibility of introducing errors:
if (a>10)
a=0;
If somebody extends code and writes later,
if (a>10)
a=0;
printf ("a was reset\n");
This will always be printed because of the missing braces. Some people request that you always use braces to avoid this kind of errors.
Contrary to several answers, there is a finite but negligible performance difference at compile time. There is zero difference of any kind at runtime.
No, there is no difference, the compiler will strip out non-meaningful braces, line-breaks etc.
The compile time will be marginally different, but so marginally that you have already lost far more time reading this answer than you will get back in compile speed. As compute power increases, this cost goes down yet further, but the cost of reducing readability does not.
In short, do what is readable, it makes no useful difference in any other sense.
A machine code does not contain such braces. After compilation, there is no more {}. Use the most readable form.
Well, there is of course no difference between them as such at runtime.
But you should certainly use the 2nd way for the sake of maintainence of your code.
Why I'm saying this is, suppose in future, you need to add some more lines to your if-else block to expand them. Then if you have the first way incorporated in your old code, then you would have to add the braces before adding some new code. Which you won't need to do in 2nd case.
So, it is far easier to add code to the 2nd way in future, than to the 1st one.
Also, if you are using the first way, you are intended to do typing errors, such as semi-colon after your if, like this: -
if (a > 0);
System.out.println("Hello");
So, you can see that your Hello will always get printed. And these errors you can easily remove if you have curly braces attached to your if.
It depends on the rest of the coding guidelines. I don't see any
problem dropping the braces if the opening brace is always on a line
by itself. If the opening brace is at the end of the if line,
however, I find it too easy to overlook when adding to the contents. So
I'd go for either:
if ( a > 10 ) {
a = 0;
}
regardless of the number of lines, or:
if ( a > 10 )
{
// several statements...
}
with:
if ( a > 10 )
a = 0;
when there is just one statement. The important thing, however, is that
all of the code be consistent. If you're working on an existing code
base which uses several different styles, I'd alway use braces in new
code, since you can't count on the code style to ensure that if they
were there, they'd be in a highly visible location.
Related
This question already has answers here:
Is it ok if I omit curly braces in Java? [closed]
(16 answers)
Closed 9 years ago.
I am using if condition without braces in java something like
if(somecondition)
//Only one line Business logic
but some told use braces always even one line statement something like this
if(somecondition){
//Only one line Business logic
}
What is the better way according to java sandard?
there's no real "standard". i prefer always using braces because if you dont you risk someone adding an innocent looking logging statement turning your code from
if(somecondition)
//Only one line Business logic
into
if(somecondition)
log.debug("condition was true");
//Only one line Business logic
and then things stop working :-)
That's a matter of taste. I would use braces or else no braces but write all code in one line to improve readability.
Also you might consider using a ternary operator
booleanExpression ? value1 : value2
In addition to #radai answer, if you are a real evil mind, when you see a if with no braces you can do something that will make you ennemies by adding a semi-colon on the same line of the if but at the 800th column of the line(or something).
like
if(condition) /*a loooot of whitespace*/ ;
//Only one line Business logic that will get executed whatever is the condition
This is why i prefer to use braces and recommend people to use them
No naked if statements. You're just asking for trouble. Always use { }
it is better to use braces when checking for errors or updating the code.
imagine.
if(answer.equals("add"))
addedValue += Scanner.readInt();
but you have a new requirement to add only the absolute value, so you change to.
if(answer.equals("add2))
valueToBeAdded = Scanner.readInt();
if(valueToBeAdded < 0) valueToBeAdded = - valueToBeAdded;
addedValue += valueToBeAdded;
this is not a really correct algorithm, is just an example of what can happens.
Using if statement with braces is better way to java standard, because it increase the readability and reduce unwanted error.
The two statements have exactly the same effect but I have suffered so often from the lack of braces that I also always comment that there should be braces even around 1 line statements. This makes the code easier to maintain and can save a lot of headache. My experience shows that one line if statements often turn into multi-line statements on later iterations so what you save by not writing two { the first time, you will give later on.
According to java standard braces are better because if they are not there compiler has to work around more and also would be performance issue.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Alright so I have to write a LaTeXParser in java, I'm going to be taking in a file much like this one below and reading it for validity and errors. Now I am not looking for help really or code but more of a conceptual understanding, how to attack the problem. I am going to be using Stacks to store the blocks and make sure everything is sorted properly. So my question to you is, how to handle it?
For example, Should I begin by getting all the "\begin{_}" and putting them in a stack and then pop them with their corresponding "\end{}"? I was wondering using a String based case switch system that, when particular strings were found, would perform the actions necessary based on that string, on my stack.
Or maybe 2 Stacks that cancel each other out, all the \begins in one and the \ends in another and has their {__} match up, I start poping them out and what not.
So yeah, just wondering what the bright minds of SOF had to say about how I should be thinking about this problem and how to deal with it. Thanks for your input!
\documentclass{article}
\usepackage{amsmath, amssymb, amsthm}
\begin{document}
{\Large \begin{center} Homework Problems \end{center}}\begin{itemize}\item\end{itemize}
\begin{enumerate}
\item Prove: For all sets $A$ and $B$, $(A - B) \cup
(A \cap B) = A$.
\begin{proof}
\begin{align}
& (A - B) \cup (A \cap B) && \\
& = (A \cap B^c) \cup (A \cap B) && \text{by
Alternate Definition of Set Difference} \\
& = A \cap (B^c \cup B) && \text{by Distributive Law} \\
& = A \cap (B \cup B^c) && \text{by Commutative Law} \\
& = A \cap U && \text{by Union with the Complement Law} \\
& = A && \text{by Intersection with $U$ Law}
\end{align}
\end{proof}
\item If $n = 4k + 3$, does 8 divide $n^2 - 1$?
\begin{proof}
Let $n = 4k + 3$ for some integer $k$. Then
\begin{align}
n^2 - 1 & = (4k + 3)^2 - 1 \\
& = 16k^2 + 24k + 9 - 1 \\
& = 16k^2 + 24k + 8 \\
& = 8(2k^2 + 3k + 1) \text{,}
\end{align}
which is certainly divisible by 8.
\end{proof}
\end{enumerate}
\end{document}
EDIT: Lol I think everyone is overthinking this wayyyyyy too much, I am not looking for anything that recognizes and compiles code, or actually performs the actions of the LATEX language via this file. I simply want to be able to write up a text file, like the one above, have my program open it, read it, and say "hey! this would work because every block that begins also ends!" Or "hey theres an error on line 10!" Nothing more, nothing less. Just a simple validator/error checker that uses Stacks to contain the blocks and then pops them when the end is found and so on. Again I AM NOT LOOKING FOR CODE OR HANDOUTS! All I would like is some good ideas and methods for attacking this problem, maybe some pseudo code structuring at best!
For example...I was thinking of having this all contained in 1 class, in my main, and making a Stack that would hold all of the Strings in the file that were coded like such " \begin{_} " then when I found the corresponding " \end{} " just popping it out and check it off a list or something. If every beginning block is popped by the end of my run through the file, I have a valid .txt file.
Trying to roll your own parser is a big task. There are a number of Parser Generators that take some of the busy work out of the task. ANTLR is a popular one for java.
One of the first things you're going to need to do is find out what kind of language latex is? More complicated languages like C++ can't be parsed with the same kinds of parsers that you can use for a more regular language like forth.
The following Jules Bean post leads me to think that latex is harder to parse than most programming languages.
I'm pretty sure it's not an LALR language. It's context dependent and is capable of modifying it's own syntax. I think it is probably technical impossible to parse without actually executing the macros. I.e. you need a TeX state machine to parse it in full generality.
'well-behaved' LaTeX is probably LALR, though.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I need suggestion for the right approach to apply conditions in Java.
I have 100 conditions based on which I have to change value of a String variable that would be displayed to the user.
an example condition: a<5 && (b>0 && c>8) && d>9 || x!=4
More conditions are there but variables are the same more or less.
I am doing this right now:
if(condition1)
else if(condition2)
else if(condition3)
...
A switch case alternative would obviously be there nested within if-else's i.e.
if(condition1)
switch(x)
{
case y:
blah-blah
}
else if(condition2)
switch(x)
{
case y:
blah-blah
}
else if(condition3)
...
But I am looking for some more elegant solution like using an Interface for this with polymorphic support , What could be the thing that I could possibly do to avoid lines of code or what should be the right approach.
---Edit---
I actualy require this on an android device. But its more of a java construct here.
This is a small snapshot of conditions that I have with me. More will be added if a few pass/fail. That obviously would require more if-else's with/without nesting. In that case would the processing go slow.
I am as of now storing the messages in a separate class with various string variables those I have kept static so if a condition gets true
then I pick the static variable from the only class and display that
one. Would that be right about storing the resultant messages.
Depending on the number of conditional inputs, you might be able to use a look-up table, or even a HashMap, by encoding all inputs or even some relatively simple complex conditions in a single value:
int key = 0;
key |= a?(1):0;
key |= b?(1<<1):0;
key |= (c.size() > 1)?(1<<2):0;
...
String result = table[key]; // Or result = map.get(key);
This paradigm has the added advantage of constant time (O(1)) complexity, which may be important in some occasions. Depending on the complexity of the conditions, you might even have fewer branches in the code-path on average, as opposed to full-blown if-then-else spaghetti code, which might lead to performance improvements.
We might be able to help you more if you added more context to your question. Where are the condition inputs coming from? What are they like?
And the more important question: What is the actual problem that you are trying to solve?
There are a lot of possibilities to this. Without knowing much about your domain, I would create something like (you can think of better names :P)
public interface UserFriendlyMessageBuilder {
boolean meetCondition(FooObjectWithArguments args);
String transform(String rawMessage);
}
In this way, you can create a Set of UserFriendlyMessageBuilder and just iterate through them for the first that meets the condition to transform your raw message.
public class MessageProcessor {
private final Set<UserFriendlyMessageBuilder> messageBuilders;
public MessageProcessor(Set<UserFriendlyMessageBuilder> messageBuilders) {
this.messageBuilders = messageBuilders;
}
public String get(FooWithArguments args, String rawMsg) {
for (UserFriendlyMessageBuilder msgBuilder : messageBuilders) {
if (msgBuilder.meetCondition(args)) {
return msgBuilder.transform(rawMsg);
}
}
return rawMsg;
}
}
What it seems to me is "You have given very less importance to design the product in modules"
Which is the main factor of using OOP Language.
eg:If you have 100 conditions and you are able to make 4 modules then therotically for anything to choose you need 26 conditions.
This is an additional possibility that may be worth considering.
Take each comparison, and calculate its truth, then look the resulting boolean[] up in a truth table. There is a lot of existing work on simplifying truth tables that you could apply. I have a truth table simplification applet I wrote many years ago. You may find its source code useful.
The cost of this is doing all the comparisons, or at least the ones that are needed to evaluate the expression using the simplified truth table. The advantage is an organized system for managing a complicated combination of conditions.
Even if you do not use a truth table directly in the code, consider writing and simplifyin one as a way of organizing your code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In many cases, mostly when you are looping through an array and assigning values to the elements, there is a scope to use post increment operator. Is it considered a good practice.
For example, in the following code where the copying is being done which one is better.
int [] to_assign;
int [] to_include;
int [] from_assign;
// Version 1
int count = 0;
while(i<<some_value>){
if(to_include[i]==1)
to_assign[count++] = from_assign[i];
}
// Version 2
int count = 0;
while(i<<some_value>){
if(to_include[i]==1)
{
to_assign[count] = from_assign[i];
count++;
}
}
It's purely a matter of style. Personally, I'd use whichever one makes the most logical sense. If the increment is logically part of the operation, then use the post-increment. If not, use a separate increment operation.
Also, when you use an increment operator alone, it is generally preferred to use a pre-increment. While it won't matter with simple types like integers, with more complex types, it can be much more efficient in languages like C++ that have operator overloading because a pre-increment doesn't need two instances to be around at the same time. There's no performance impact with Java, because it doesn't have operator overloading, but if you want a consistent style rule, it should be pre-increment rather than post-increment.
I'd argue that the second solution is perhaps slightly cleaner to read. I.e. the eye observes that an assignment is being made, and then that there is an increment. Having them both together on the same line makes it slightly less easy to read at a glance. So, I'd prefer solution two.
That said, this is a matter of preference. I don't think one can speak of an established best or better practice here.
In the days when every last ounce of performance mattered, the first version would have been preferred, because the compiler has a higher change of emitting slightly more optimal assembly in the first solution.
Any good compiler will optimize this for you anyway. All are good as long as they are human-readable.
"++" is a leftover from the days of pointer arithmetic -- there are some of us who prefer "+= 1" for integers. But the compiler should manage simple cases like this correctly, regardless.
Modern compilers optimize this kind of code anyway, so in the end it doesn't matter how and where you're incrementing the variable.
From a style perspective, the first version is smaller, and for some easier to read.
From a code comprehension point of view, the second version is easier to understand for beginner developers.
From a performance point of view, ignoring compiler optimizations, this is even faster:
// Version 3
int count = -1;
while(i<<some_value>){
if(to_include[i]==1)
{
to_assign[++count] = from_assign[i];
}
}
It's faster because in theory count++ creates a temporary copy of the value before the increment, while ++count increments and uses the same variable. But again, this kind of premature optimization is not needed any more, since compilers can detect such frequent cases and optimizes the generated code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
In near future we might be enforced by a rule by which we can not have any hard coded numbers in our java source code. All the hard coded numbers must be declared as final variables.
Even though this sounds great in theory it is really hard/tedious to implement in code, especially legacy code. Should it really be considered "best practice" to declare numbers in following code snippets as final variables?
//creating excel
cellnum = 0;
//Declaring variables.
Object[] result = new Object[2];
//adding dash to ssn
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9);
Above are just some of the examples I could think of, but in these (and others) where would you as a developer say enough is enough?
I wanted to make this question a community wiki but couldn't see how...?
Definitely no. Literal constants have their places, especially low constants such as 0, 1, 2, ...
I don't think anyone would think
double[] pair = new double[PAIR_COUNT];
makes more sense than
double[] pair = new double[2];
I'd say use final variables if
...it increases readability,
...the value may change (and is used in multiple places), or
...it serves as documentation
A related side note: As always with coding standards / conventions: very few (if any) rules should be followed strictly.
Replacing numbers by constants makes sense if the number carries a meaning that is not inherently obvious by looking at its value alone.
For instance,
productType = 221; // BAD: the number needs to be looked up somewhere to understand its meaning
productType = PRODUCT_TYPE_CONSUMABLE; // GOOD: the constant is self-describing
On the other hand,
int initialCount = 0; // GOOD: in this context zero really means zero
int initialCount = ZERO; // BAD: the number value is clear, and there's no need to add a self-referencing constant name if there's no other meaning
Generally speaking, if a literal has a special meaning, it should be given a unique name rather than assuming things. I'm not sure why it is "practically" hard/tedious to do the same.
Object[] result = new Object[2]; => seems like a good candidate for using a Pair class
cellnum = 0; => cellnum = FIRST_COLUMN; esp since you might end up using an API which treats 1 as the starting index or maybe you want to process an excel in which columns start from 2.
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9) => If you have code like this littered throughout your codebase, you have bigger problems. If this code exists in a single location and is shielded by a sane API, I don't really see a problem here.
I've seen folks consider 0 and 1 accepted exceptions.
The idea is that you want to document why you have two Objects as above for example.
I agree with you about the dashes in SSN. The comment describes it better than 4 named constants.
In general, I like the idea of no magic numbers, but as with every rule, there are pragmatics involved. Legacy code, brings its own issues. It's a lot of work without a lot of productivity in terms of changed behavior to bring old code up to date this way. I would consider doing it in an evolutionary fashion: when you have to edit an old file, bring it up to date.
It really depends on the context doesn't it. If there are numbers in the code that does not indicate why they exist then naming them makes teh code more readable. If you see the number 3.14 in code is it PI? is there any way to tell or is that just a coincidence? Naming it PI will clear up the mystery.
In your example, why is cellnum = 2? why not 10? or 20? That should be named something, say INITIAL_CELL or MAX_CELL. Expecially if this same number, meaning the same thing appears again in the code.
Depends if it needs to be changed. Or for that matter, it can be changed.
If you only need 2 objects (say, for a pair like aioobe mentioned) then that isn't a magic number, it's the correct number. If it's for a variable tuple that, at this moment, is 2, then you probably should abstract it out into a constant.