Clean code & Smooth development

Ahoy!

I am looking for some tips on keeping clean code. I generally keep my code pretty organized, however whenever I struggle on some implementation, it gets messy. I’m curious on how I can avoid this. Also, whenever developing something, how can I keep on task and motivated? Often, I’m not quite sure what I am going to create. I just go into development with an image in my mind… which has proven to fail for me.

Thanks!

  • A

Comments and Ctrl+Shift+F to auto format code in Eclipse. Ctrl+Shift+O Organizes imports.

You can even set those to occur every time you save. Along with other niceties.

it depends what organized and messy to YOU

I’m very big on human readability. Maybe you should post some of your examples and we give advice.
However opinions will differ.

This is actually java code convention


public class HardToRead{	
 public static void main(String[] args) {
  for (int i=0;i<10;i++) {
   System.out.println(""+i);
  }
 }
}

This is what I like:


public class EasyToRead
{
	public static void main(String[] args)
	{
		for (int i=0;i<10;i++)
		{
			System.out.println(""+i);
		}
	}
}

Apparently Allman style.
I think the proximity between lines make individual lines hard to read.

But there is also how to call variables and methods.
And I am a big fan of doing a simple thing is 3 or 4 lines instead of 1 hard to read one.

But you like things like this:

int foo=bar+25/(14*25)-24+Integer.parseInt("234");

Don’t you think whitespaces offer you something? :wink:

I think the OP was asking how to keep clean code structure, not the text.

Clean code structure starts with the text, believe it or not.

A programmer’s mind can glean vast amounts of information with just a single glance at a page of code, subconsciously, if it is laid out in a manner consistent with expectations, and therefore, conventions. So always autoformat your code on a save and make liberal use of //formatter:off/on tags where necessary to make things neat.

Stick to Sun’s bracket conventions or you’ll be making code that already upsets 99% of other Java developers on the mere sight of it. And make sure you have whitespace around operators (except brackets).

And finally, at least attempt to Javadoc anything public, and sprinkle comments around in your code for anything that’s not completely obvious… which you’d be surprised to learn is almost everything you write that’s longer than 3 lines.

Cas :slight_smile:

One technique I would recommend to keep code clean is to follow the principle of high cohesion. In my mind, this is another way of saying “don’t write classes or methods that try to do everything under the sun”. They should each do one job, and do that one job well. One of the many side effects of not doing this is you end up with scoping issues - lots of variables in the same space, all trying to do a similar but not quite the same job. You then end up elaborating on variable names in an attempt to group them together or differentiate between all the other variables. It’s a mess.

As a general rule, if I have any methods that don’t all fit within the one screen (and I use fairly liberal amounts of white space) then this is an indicator that it’s doing too much. It’s not a hard and fast rule, but a solid guideline I like to follow.

On the other hand, having 17 classes that all do very little and are only used together is pretty annoying.
As always there’s a balance, knowing the right balance is often simply a matter of experience, because you’ll have seen good and bad balances.

It’s a very good guideline, and the reasoning behind it is based on what I just said too: if you can see the whole code for some operation in a single glance, your subconscious mind can actually process the entire thing in one go without you thinking about it consciously. It’s extraordinary the difference it makes to understanding code.

Cas :slight_smile:

Readability 8)! I try to keep method and class to a size that I can understand in one viewing. If I have to think too hard about it I break the task up into methods that can be understood. I agree that most of the time a class should do one thing, a balance needs to be attained, the code should work for you.

If a section of code is used more than once it often goes in a method :point:. If there are a lot of helper methods in a class that are useful in general they get put in a new class for reuse, tested and documented.

Divide and conquer ftw! ;D

Refactor frequently and avoid comments if you can. If code needs a comment it’s probably too complex. I can never trust a comment - there is nothing guaranteeing it is in synch with the nearby code. Write tests.

The exact opposite happens to me. The more I am struggling with an implementation or with debugging, the more I I spend cleaning up the messes I have made in order to figure out WTF I just wrote.

I’d try to make methods the most basic unit of cohesion. Whatever is done in a method should be summarized by the name of the method. Then, when you string a bunch of these methods together, what is going on is automatically described and readable (pretty much).

When princec says “Sun’s bracket conventions” that means either of the two types that Cero demonstrated, yes? I certainly hope so, as I also prefer what Cero calls the Allman style, and would hate to think this would upset 99% of other programmers. Cero’s first example is not exactly correct though, is it? Shouldn’t there be more than a single space for the nesting?

I do think so, all programmers I have met that saw Allman style and use the “normal” style just say “oh you do that, yea its fine”

I’m no expert, I stopped caring what is convention many years ago actually

@noctarius
ah yes you are right

for (int i=0;i<10;i++)

should be

for (int i = 0; i < 10; i++)

something like that

also why I usually dont use the if else shorthand: if (blah ? then : else)
first of all I ALWAYS forget which one comes first ? or : , second its just harder to read. words make it more simple. its not like I have limited lines to work with
and I dont think having many lines in a file is bad in any way, you have an method outline on the side and cold folding…

[quote=“syszee,post:1,topic:51511”]
You’re kind of answering your own question there :stuck_out_tongue: Think about it a bit more before starting to code!

Maybe do a 5 minute sketch of what the screen’ll look like, or visualise how the code’ll flow, maybe do a flowchart. Sketching out a class relationship diagram can be surprisingly helpful. Not saying always do those things, they’re just ways of helping yourself think about the program before actually starting to code it and (as you point out) more often than not getting in a mess.

Ideally then when you open Eclipse you’ll find the code flows cleanly and smoothly from your fingertips, quite naturally :point:

[quote=""]

[quote=""]
I say comment quite a lot, and do it as you code (not as an afterthought at the end, as if it was a homework assignment and comments would score a few extra marks!) Yes code with good comments is easier to read later, but just as important is that thinking about explaining the code to someone else makes you think about what the code’s actually doing. A lot of the time it’ll become clear some bit of code is dumb just from writing a comment to explain it. Other times you’ll realize you don’t actually quite understand what you’ve done yourself, which can’t be good :smiley:

Actually, Sun’s recommendations with regard to curly braces is only “opening curly NOT on a separate line.”

Note its style recommendations have not been updated since 1999; see this StackOverflow thread for a relatively recent discussion about this and a link to the (archived) “official” documentation from Oracle.

Anecdotally, I find most Java programmers prefer Sun/Oracle’s recommendation for curly brace placement, but I’ve also met some traditionally-C-style separate-liners. Personally I’m in the “use whatever the standard formatting is for the particular language you’re working with” camp.

I’m of the opinion that the code should probably actually be formatted by SVN before commits/compares, but be automatically displayed in the IDE in the format the progammer prefers. Much like syntax highlighting is independent of what’s stored in SVN, so I think formatting should be.

Cas :slight_smile:

Like CSS for code :slight_smile:

Exactly that.

Also any language that makes a virtue of whitespace can take a flying fuck at a rolling doughnut. There, I said it.

Cas :slight_smile:

you just blew my mind.