Stylistic Question: Using White Space

I have a particularly stupid uncertainty about the aesthetics of my code ... my use of space is frankly uncomfortable. My code looks like geek dancing; not really scary, but uncomfortable that you feel bad, but you can’t look away.

I'm just not sure when I should leave a blank line or use a line-end comment instead of a line comment above. I prefer to comment above my code, but sometimes it seems strange to interrupt the stream for a three-word comment. Sometimes throwing an empty line before and after a block of code is like putting a speed hit in the otherwise smooth part of the code. For example, in a nested loop separating three or four lines of code block in the center, the visual indentation effect almost vanishes (I noticed that K & R edges are less prone to this problem than Allman / BSD / GNU styles).

My personal preference is a dense code with very few “speed bumps,” with the exception of functions / methods / comment blocks. For complex sections of code, I like to leave a large block of comments telling you what I'm going to do and why, and then a few “marker” comments in this section of code. Unfortunately, I found that some other people usually use generous vertical white space. On the one hand, I could have a higher density of information, which, according to some others, does not flow very well, and on the other hand, I could have a better current code base by reducing the signal-to-noise ratio.

I know that this is such a petty, stupid thing, but this is what I really want to work on when I improve the rest of my skills.

Can anyone suggest any hints? What do you think is good flowing code and where is it appropriate to use vertical empty space? Any thoughts at the end of the comment line for two or three word comments?

Thanks!

PS Here is a method from the code base I was working on. Not my best, but not my worst.

/** * TODO Clean this up a bit. Nothing glaringly wrong, just a little messy. * Packs all of the Options, correctly ordered, in a CommandThread for executing. */ public CommandThread[] generateCommands() throws Exception { OptionConstants[] notRegular = {OptionConstants.bucket, OptionConstants.fileLocation, OptionConstants.test, OptionConstants.executable, OptionConstants.mountLocation}; ArrayList<Option> nonRegularOptions = new ArrayList<Option>(); CommandLine cLine = new CommandLine(getValue(OptionConstants.executable)); for (OptionConstants constant : notRegular) nonRegularOptions.add(getOption(constant)); // --test must be first cLine.addOption(getOption(OptionConstants.test)); // and the regular options... Option option; for (OptionBox optionBox : optionBoxes.values()) { option = optionBox.getOption(); if (!nonRegularOptions.contains(option)) cLine.addOption(option); } // bucket and fileLocation must be last cLine.addOption(getOption(OptionConstants.bucket)); cLine.addOption(getOption(OptionConstants.fileLocation)); // Create, setup and deploy the CommandThread GUIInteractiveCommand command = new GUIInteractiveCommand(cLine, console); command.addComponentsToEnable(enableOnConnect); command.addComponentsToDisable(disableOnConnect); if (!getValue(OptionConstants.mountLocation).equals("")) command.addComponentToEnable(mountButton); // Piggy-back a Thread to start a StatReader if the call succeeds. class PiggyBack extends Command { Configuration config = new Configuration("piggyBack"); OptionConstants fileLocation = OptionConstants.fileLocation; OptionConstants statsFilename = OptionConstants.statsFilename; OptionConstants mountLocation = OptionConstants.mountLocation; PiggyBack() { config.put(OptionConstants.fileLocation, getOption(fileLocation)); config.put(OptionConstants.statsFilename, getOption(statsFilename)); } @Override public void doPostRunWork() { if (retVal == 0) { // TODO move this to the s3fronterSet or mounts or something. Take advantage of PiggyBack scope. connected = true; statReader = new StatReader(eventHandler, config); if (getValue(mountLocation).equals("")) { OptionBox optBox = getOptionBox(mountLocation); optBox.getOption().setRequired(true); optBox.requestFocusInWindow(); } // UGLY HACK... Send a 'ps aux' to grab the parent PID. setNextLink(new PSCommand(getValue(fileLocation), null)); fireNextLink(); } } } PiggyBack piggyBack = new PiggyBack(); piggyBack.setConsole(console); command.setNextLink(piggyBack); return new CommandThread[]{command}; } 
+4
source share
13 answers

It does not matter.

1) Design your own style. No matter what you find the easiest and most convenient, do it. Try to be as consistent as possible, but do not become subordinate to the sequence. Shoot about 90%.

2) When you modify another developer code or work on a group project, use the stylistic conventions that exist in the code base or that were outlined in the style guide. Do not complain about it. If you are able to define style, present your preferences, but be prepared to compromise.

If you complete both of these options, you will all be configured. Think of it as the same language in two different ways. For example: speaking differently about your friends than with your grandfather.

+11
source

This does not prevent you from making beautiful code. When I write something that I'm really proud of, I usually can take a step back, look at the whole method or class and understand exactly what it does at first sight - even after a few months. Aesthetics plays a role in this, although not as big as a good design. Also, understand that you cannot always write beautiful code (untyped ADO.NET?), But when you can, please do it.

Unfortunately, at this higher level, at least I’m not sure that there are some strict rules that you can follow to always create aesthetically pleasing code. One piece of advice I can offer is to simply read the code . A lot of. In many different frameworks and languages.

+5
source

I like to break the logical "phrases" of the code with a space. This helps others easily visualize the logic in the method - or remind me when I get back and look at the old code. For example, I prefer

 reader.MoveToContent(); if( reader.Name != "Limit" ) return false; string type = reader.GetAttribute( "type" ); if( type == null ) throw new SecureLicenseException( "E_MissingXmlAttribute" ); if( String.Compare( type, GetLimitName(), false ) != 0 ) throw new SecureLicenseException( "E_LimitValueMismatch", type, "type" ); 

instead

 reader.MoveToContent(); if( reader.Name != "Limit" ) return false; string type = reader.GetAttribute( "type" ); if( type == null ) throw new SecureLicenseException( "E_MissingXmlAttribute" ); if( String.Compare( type, GetLimitName(), false ) != 0 ) throw new SecureLicenseException( "E_LimitValueMismatch", type, "type" ); 

The same gap can be achieved with braces, but I find that it actually adds visual noise and reduces the amount of code that can be visually consumed at the same time.

Subscribe to the line of code

As for the comments at the end of the line - almost never. This is not very bad, just skip when scanning the code. And they clutter up the line taking away from the code, which makes it difficult to read. Our brains are already connected to line by line. When the comment is at the end of the line, we must divide the line into two specific concepts - code and comment. I say if it is important enough to comment, put it on a line, continuing the code.

In doing so, I find one or two comments on the line prompt about the value of a certain value, sometimes it’s OK.

+4
source

I find code with a very small space that is difficult to read and navigate, since I really need to read the code to find the logical structure in it. The clever use of spaces to separate logical parts in functions can increase the ease of understanding the code, not only for the author, but also for others.

Keep in mind that if you work in an environment where your code is likely to be supported by others, they will spend most of their time finding code that you haven’t written. If your style is distinctly different from what they are used to seeing, your smooth code can be fast for them.

+3
source

I minimize the gap. I put the main comment block above the code block and additional comments at the end of the line, which may not be obvious to another developer. I think you already do it

+1
source

My preferred style is probably anathema to most developers, but I will add random blank lines to separate what looks like the corresponding “paragraphs” of the code. This works for me, no one complained during code reviews (yet!), But I can imagine that this may seem arbitrary to others. If other people don't like it, I will probably stop.

+1
source

The most important thing to remember is that when you join an existing code base (since you will almost always be in your professional career), you need to adhere to the code style guidelines dictated by the project.

Many developers, when starting a project anew, prefer to use a style based on a document with Linux kernel code. The latest version of this document can be viewed at http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob;f=Documentation/CodingStyle;h=8bb37237ebd25b19759cc47874c63155406ea28f;hb= HEAD

In addition, many maintainers insist that you use Checkpatch before submitting changes to version control. You can see the latest version that comes with the Linux kernel in the same tree that I linked to above on /checkpatch.pl scripts (I would contact it, but I'm new and can only publish one hyperlink for each answer).

While Checkpatch is not specifically related to your question about using spaces, it will certainly help you eliminate spaces in spaces, spaces in front of tabs, etc.

+1
source

I use exactly the same number of spaces as you :) Spaces before methods, before comment blocks. In C, C ++, brackets also provide some "pseudo-spaces", since on some lines there is only one opening / closing bracket, therefore it also serves to decompose code density.

+1
source

Code Complete, Steve McConnell (available in regular places) is my Bible about this. It has a whole chapter on layout and style that is just superb. The whole book is simply full of useful and practical tips.

+1
source

Your code is fine, just do what you (and others with whom you could work) are comfortable with.

The only thing that I see wrong with some (inexperienced) programmers regarding spaces is that they may be afraid to use it, which is wrong in this case.

However, I noticed that you did not use more than one consecutive empty line in your code example, which in some cases you should use.

+1
source

This is how I would reorganize this method. Things can certainly be improved, and I haven't reorganized the PiggyBack class yet (I just moved it to the top level).

Using the Composed Method pattern , code becomes easier to read when it is divided into methods that each do one thing and work on a single level of abstraction. Less comments are also required. Comments that answer the question “what” are the smells of the code (i.e. the code must be reorganized in order to be more readable). Useful comments answer the question of “why,” and even then it would be better to improve the code so that the reason is obvious (sometimes this can be done with a test that fails without the hateful code).

 public CommandThread[] buildCommandsForExecution() { CommandLine cLine = buildCommandLine(); CommandThread command = buildCommandThread(cLine); initPiggyBack(command); return new CommandThread[]{command}; } private CommandLine buildCommandLine() { CommandLine cLine = new CommandLine(getValue(OptionConstants.EXECUTABLE)); // "--test" must be first, and bucket and file location must be last, // because [TODO: enter the reason] cLine.addOption(getOption(OptionConstants.TEST)); for (Option regularOption : getRegularOptions()) { cLine.addOption(regularOption); } cLine.addOption(getOption(OptionConstants.BUCKET)); cLine.addOption(getOption(OptionConstants.FILE_LOCATION)); return cLine; } private List<Option> getRegularOptions() { List<Option> options = getAllOptions(); options.removeAll(getNonRegularOptions()); return options; } private List<Option> getAllOptions() { List<Option> options = new ArrayList<Option>(); for (OptionBox optionBox : optionBoxes.values()) { options.add(optionBox.getOption()); } return options; } private List<Option> getNonRegularOptions() { OptionConstants[] nonRegular = { OptionConstants.BUCKET, OptionConstants.FILE_LOCATION, OptionConstants.TEST, OptionConstants.EXECUTABLE, OptionConstants.MOUNT_LOCATION }; List<Option> options = new ArrayList<Option>(); for (OptionConstants c : nonRegular) { options.add(getOption(c)); } return options; } private CommandThread buildCommandThread(CommandLine cLine) { GUIInteractiveCommand command = new GUIInteractiveCommand(cLine, console); command.addComponentsToEnable(enableOnConnect); command.addComponentsToDisable(disableOnConnect); if (isMountLocationSet()) { command.addComponentToEnable(mountButton); } return command; } private boolean isMountLocationSet() { String mountLocation = getValue(OptionConstants.MOUNT_LOCATION); return !mountLocation.equals(""); } private void initPiggyBack(CommandThread command) { PiggyBack piggyBack = new PiggyBack(); piggyBack.setConsole(console); command.setNextLink(piggyBack); } 
+1
source

For C #, I say that "if" is just a word, and "if (" code is a space after "if", "for", "try", etc. does not help readability at all, so I’d better think without space.

Also: Visual Studio> Tools> Options> Text Editor> All Languages> Tabs> KEEP TABLES!

If you are a software developer who insists on using spaces that have tabs, I will insist that you are slob, but whatever - in the end, it all compiled. On the other hand, if you are a web developer with a bunch of consecutive spaces and other extra spaces throughout HTML / CSS / JavaScript, then you either don’t know about the client code, or you just don’t give a shit. Client code is not compiled (and not compressed with IIS default settings) - meaningless spaces on the client side of the script are similar to adding meaningless calls to Thread.Sleep () in the server code.

+1
source

I like to maximize the amount of code that can be seen in the window, so I use only one empty line between functions and rarely inside. Hope your functions are not too long. Looking at your example, I don't like the empty string for the open curly bracket, but I will have one to close. To display the structure there should be enough indentation and coloring.

0
source

Source: https://habr.com/ru/post/1286395/


All Articles