I am studying for an upcoming AP Computer Science Exam and I have a quick question on syntax within brackets. In the book I'm working through shows the open bracket to always be on the next line rather than being on the same line as the statement. Does it matter either way? I am used to placing the open bracket on the same line when coding, and I want to make sure I won't get docked points for continuing that habit.
Example:
if(1==1){
//do something
}
or
if(1==1)
{
//do something
}
I'm assuming it does not matter but I would like to make sure
The first is more commonplace in java, but both should compile just fine and will function exactly the same.
EDIT: It should be noted, however, that if you wish to use the former I personally prefer to add some spaces like so:
if (1==1) {
//do something
}
No, it does not matter. Both will be repeated in the same manner, and they both will have scopes allocated to them.
That being said, certain IDEs (and possibly the compiler) may whine about 1==1 being always true.
The bracket position makes no difference; white space is not relevant in java. You can write everything on one line if you like; even the entire program.
Though, for readability sake, you should split it up! :)
You're correct, it doesn't matter. It's a matter of personal preference. Putting the opening bracket on a new line allows the coder to more easily keep track of opening and closing brackets, and the other method is more space efficient.
Take a look at the Java Programming Style Guideline point 6 about Layout and Comments.
//1
while (!done) {
doSomething();
done = moreToDo();
}
//2
while (!done)
{
doSomething();
done = moreToDo();
}
The first one is recommended EXCEPT for class, interface and method should use the block layout of number 2. So it means, in your example, if you want to follow the right guideline, the layout should be like:
if (1==1) {
//do something
}
Note that there is a space before and after the parenthesis. But although you doesn't follow the standard layout, it doesn't matter and doesn't change anything on your code.
As other people have said, it doesn't matter for the compiler. It's more about readability, and I prefer your first method (having the opening bracket on the same line as the if statement, or any other place that may require an opening bracket.
This is effective if you're writing larger blocks of code, and your screen might be too small for you to see whether you need a closing bracket or not. You can simply hover your mouse over a closing bracket, and the IDE will show the line with the opening bracket at the top of the screen. This way, you can see which line your closing bracket lines up with, and you can fix bracket pairing problems much more easily.
Related
Is there a way to quickly change both opening and closing parentheses to a different type?
For example: (...some code...) to {...some code...}
I know that Cmd + Shift + M jumps between matching braces, so you could select the block, surround it with new bracket type, then jump around to remove the old set of braces but was wondering if there is a better way.
Update
While making a screen recording of it "not working", I saw for the first time this feature in action. However, it only seems to work from () to {}. As the capture shows, it doesn't work the other way. I guess that is why I couldn't get it to work before.
Sorry the GIF is a slowed down version of the original video.
I wonder why it only works one way.
Mark the opening (, type a { and IntelliJ changes the closing part accordingly. This apparently does not work when editing the closing part.
I'd love to have a way of IntelliJ letting me fold for loops and if/else statements. But, I can't seem to find a way to do it automatically. I know you can use the //region and //endregion comments, or that you can do it manually with Ctrl+Shift+period, but is there a way to avoid all that and have it fold like methods or classes, without doing all that other stuff?
You can fold and unfold:
Code blocks, i.e. code fragments surrounded by a matched pair of curly braces {}.
To collapse a code block, place the cursor within that block and then select Code | Folding | Fold Code Block or press ⇧+⌘+. (mac) or ctrl+⇧+. (Linux / Windows).
Note Code folding works for the keywords if/ while/ else/ for/ try/ except/ finally/ with in case of at least two statements.
See: https://www.jetbrains.com/help/idea/2016.3/code-folding.html
Under Editor > General > Code Folding, you can enable this functionality expressly.
By default, if you wish for it to collapse method bodies, you can tick that selection. There are a lot of other options available, which should cover your needs.
If there's something that isn't covered, you can always enable "Show code folding outline" and use that to fold certain elements, although loops aren't foldable.
Put the cursor anywhere in the line of method definition for which you want the code fragments to be folded and press ctrl+shift+- this will collapse the whole method and press ctrl++ right after. this will keep the if and for loop fragments inside the method collapsed (intellij 2020.1.1 linux)
Eclipse is awesome for writing java programs but today I find that it's awesome to trick new coders like me. #_#
I write a snippet as following,
public static void main(String[] args) {
for(int i=0;i<3;i++){
System.out.println("i = " + i);
}
}
then I add a breakpoint at the line of "System.out.print....", click "Debug" button, eclipse goes to the "Debug" perspective and the line of breakpoint is highlighted, then I move the cursor over variable "i", its value is "0" as expected.
And then, I select the "i++" and click "Inspect"(or press "Ctrl+Shift+I") once, I move the cursor over variable "i", its value changed to "1". I repeat "Inspect" again, the value of i changed to "2"......(its value will add by 1 every time I clicked the "Inspect")!!
Why does this happend!? I ONLY want to watch the value of "i" for debug propuse, DO NOT want to really change its value until I step into next statement. I think that "Inspect", as well as "Display" are only for viewing the variable/expression, they should not impact the value, but in this case, it doesn't work as I expect to.
Could anyone tell me what went wrong?
My eclipse version info:
Version: Indigo Service Release 2
Build id: 20120216-1857
If you inspect an expression, eclipse has to execute that expression so you can get the value. Therefore, if you inspect i++, eclipse adds one to i.
Think about it this way: If instead of i++, you inspected myFunction(i), would you expect eclipse to execute the function "myFunction" to get the value? It's the same with i++.
If you are concerned about displaying/showing values while debugging and do you want to be sure not affecting the value, you should select the variable or expression and use the "Watch" option.
This will track the variable/expression value without executing, just updating the new value each time this is run. I think is the most secure way.
As Pablo mentioned, it has to evaluate the code in order to tell you what value it returns. You could instead put a watch on "i+1" and that would give you the value you want without the side effect you don't want.
Basically, you need to be aware of any side effects of anything you launch, whether from the "main" code or from the debugging tools. As Erhannis mentioned, this is very useful at times for modifying values while debugging your code. (For example, you can verify that a tweak/fix is indeed helpful before actually tweaking your code.)
You were expecting "an isolate area" but this would be extremely hard to do, especially in an object-oriented context where many objects are linked to many other objects. Running the whole thing in parallel might sometimes work, but you'd lose the tweaking ability above. And in any context, you'd run into tons of problems with fighting over resources; e.g. both copies trying to read/write a particular file such as a log file. Also, the two execution paths could diverge, leading to incorrect/misleading watch values.
So, preventing such side effects is not really a feasible option here and would rarely be useful anyway. Just expect that the watches can both reflect and affect the code execution.
I've been recently using sonar for code analysis. When I go thorough violation drilldown, I found many java files with if statement defined without braces (thousands of places). Is there a simple way to replace or add braces to if statements or what are the steps that I can perform to achieve this task without doing it manually in each of the files.
I'm currently using intelliJ.
Is there a simple way to replace or add braces to if statements or what are the steps that I can perform to achieve this task without doing it manually in each of the files.
I don't know if there is a tool to do this automatically. (There probably is ...) But assuming that such a tool exists, I'm not convinced it would be the right approach.
Step back for a moment and consider why the code analysis has reported this as a problem. A lot of people (like #pst and me) think that the braces always should be there, even though various style guides don't insist on this. There is a good reason for this ... apart from "it looks ugly". Consider these example code snippets:
if (i == 1)
i++;
doSomething();
while (i < 1)
i++;
doSomething();
If you don't read those carefully, your eyes will trick you into thinking that doSomething(); is called conditionally ... due to the incorrect indentation. And it happens.
(Aside: labelling someone as "inept" for misreading that code is not helpful. If you are desperately trying to fix a show-stopper bug and you've been working for 14 hours straight, then you are likely to miss this kind of thing. And not because you are inept. Once you've been in that situation a couple of times, the lesson sinks in ...)
OK, now suppose that you run an automatic tool to add the braces. What you will get is this:
if (i == 1) {
i++;
}
doSomething();
while (i < 1) {
i++;
}
doSomething();
It means exactly the same thing as the original code. BUT ... what if the original code was actually a bug? What if the programmer intended the doSomething() calls to be conditional?
In short, by adding the braces automatically, we've obscured the original programmer's intention, and made these bug(s) harder to track down.
Bottom line - I think it would be prudent to manually review each of these occurrences ... rather than just "fixing" them automatically. Indeed, I'd argue that if you don't have the time or patience to review them manually, it would be better to leave the code alone. It would be better to turn off the warning ... IMO.
I can reformat the code to make intelliJ do the thing for me, but I need to go through all the files and reformat it. Yes, I might turned off the check but wondering if there is a good tool to do the task. I've good set of tests to check whether it introduce bugs during the process.
If you are sure that you have some ways to test that you will not introduce bugs then use the IntelliJ Reformat Code feature.
Just make sure that the Code Style you have in IntelliJ is in line with your company's policies. Otherwise you will force your style on everybody else too.
To force braces just mark them as Always on the Wrapping and Braces tag in the Code Style settings dialog in IntelliJ.
Mark the source folder in the project view and press Ctrl-Alt-L. A dialog pops up and there you can chose All files in directory <...>.
Then press Run and see what happens. If you are not satisfied then just revert from your VCS.
IntelliJ IDEA has an inspection for this as well, and it has a quick fix to automatically add the braces.
Invoke Analyze | Run Inspection by Name and enter inspection name Control flow statement without braces. Run it on the desired part of your project. In the inspection results you can apply the quick fix Add braces to statement.
Note that this inspection will also report control flow statement other than if, like for example while statements. Invoking the quick fix will also add braces to those statements.
This question already has answers here:
Does Eclipse have line-wrap
(12 answers)
Closed 7 years ago.
I already have word wrap for Eclipse PHP (How can I get word wrap to work in Eclipse PDT for PHP files?). What about Eclipse Java? Is there a similar tool to wrap Java code lines?
Ctrl+Shift+F will format a file in Eclipse, breaking long lines into multiple lines and nicely word-wrapping comments. You can also highlight just a section of text and format that.
I realize this is not an automatic soft/hard word wrap, but I don't think the question was asking for anything fancy.
Just like to point out that word wrapping is a terrible idea in code. I suppose everyone has their own style, but typically you should refactor or rethink blocks of code that take much more than a single average horizontal screen. (about 1280 pixels)
Of course there are always exceptions... like verbose exceptions for example, but these are not critical for code understanding.
Scanning a line that goes beyond a single horizontal screen, or having to read a thought that stacks on multiple lines will make your code much more difficult to figure out.
Additionally, line counts will be weird, as word wrapping will make a single line seem like it takes up 2, 3, or shudder the thought... 4 lines of code.
As far as comments go, line returns should not be much of a problem for anyone.
Also keep in mind, word wrapping code is not a common practice, and you are essentially saying that everyone reading your code should turn word wrapping on, which is, I'm sorry to say, an unnecessarily painful thing to make others working with your code do....
If nesting is causing you the need for word wrap... well this is also a very bad code smell.
That's my two-cents.
This is for anyone who is having the following problem with the "Ahtik" word-wrap plugin in Texlipse: the plugin installs fine, but selecting the "word-wrap" option using the context menu (or pressing ctrl+alt+w) causes the text to wrap momentarily, and then just flick back to being unwrapped (this probably includes anyone using Windows 7).
Here is a fix...straight from the developer himself! I emailed Ahti Kitsik in a last-ditch attempt to find a way round, and was amazed when he actually found a solution, and sent it to me the next day. He suggested that in return I could just make this information widely available.
So, the way to fix it as follows:
Look up the texlipse plugin location. This will probably be in the Eclipse folder, and the address will probably end: ...\eclipse\plugins\net.sourceforge.texlipse_1.5.0.
Backup the plugin.xml file there just in case, and then edit the original by deleting the following chunks of code:
-Firstly, the "action" (starting at line 843):
action
class="net.sourceforge.texlipse.actions.TexWordWrapAction"
definitionId="net.sourceforge.texlipse.commands.texWordWrap"
icon="icons/wrap.gif"
id="net.sourceforge.texlipse.actions.texWordWrap"
label="W&rap text"
menubarPath="net.sourceforge.texlipse.menus.latex/latexGroup"
style="toggle"
toolbarPath="latexGroup"
tooltip="Use word wrap"
-Secondly, the "command" (starting at line 972):
command
categoryId="net.sourceforge.texlipse.latexEditingCategory"
name="Wrap text"
id="net.sourceforge.texlipse.commands.texWordWrap"
(When you have done this, the file should be 1257 lines long, instead of 1271).
Finally, Ahti says: "Start eclipse with -clean command line argument to force reloading of plugin.xml." (Personally I had no idea how to do this, so I just removed and reinstalled his plugin, then exited Eclipse, and edited the code before I restarted it).
The function should work fine now. Hope this helps someone. And thanks again Ahti!
In the meantime, there has been an fork to Ahtik's word wrap plugin which, I must say, works very nice and fixes jumbled line numbering bug: Eclipse Word-Wrap Plug-In
Open Eclipse -> Help -> Install New Software -> Click "Add.." button and copy this line "http://dev.cdhq.de/eclipse/updatesite/luna/" into field Name and Location -> Click OK
Check -> Line Number Ruler and Word Wrap Feature -> Next -> Next -> Finish -> Restard Eclipse!