Clean code

Anable

Newbie
Joined
Nov 21, 2003
Messages
270
Reaction score
0
The deeper into programming I get, the more conflicting views I hear about "clean code" or "proper code". I realize that technically, as long as the program runs without exploding you're good to go. I was just wondering if you guys had any personal tips about how to best keep your code organized.

The thing that brought this to my attention was when I read from my Sam's C++ book that function prototypes aren't a good idea. I love prototypes and I don't have any desire to give them up so I probably won't listen to the book. Then again, I'm sure the author knows a lot more than I do...
 
The Definition of clean code is a bit tricky, generally I'd say clean code is code that always follows the same style, level of indentations, and commenting system throughought the entire project. That can be a bit difficult sometimes. In fact right now I'm debating taking a day or so to run through a bunch of my older code to a project I'm working on, and cleaning it up in the above manner, as my commenting style isn't always consistent.
 
If I got rid of prototypes in my programs they would cease to work and in some cases there would be no way to get them to without useing prototypes.

Personally I always make sure my code looks good that way it might be easier to understand, also I never ever use goto's ever. I also add brackets and other such things when they are sometimes not needed to make the code easier to follow.
 
'clean code' is as said, code which is easy to read;

A couple of important points;

  • Dont over comment - comments are important but too many can detract from the code, really your code should be clear enuff that reading it gets the point across
  • Consistance varible naming, this includes case and any pre/post fix you might use
  • Consistant spacing between things
  • Dont try to be overly clever with how you do things, i've been guilty of this in the past, it comes back to bite you

And as personal preference, hungerian notation on varibles is EVIL, EVIL I TELL YOU!!!! *koff* yeah, so i dont use it, i prefer descriptive varible names to short names with type infomation put in them.

The 'never use gotos, ever' rule is a bit of an iffy one, if you can avoid it do so, however its part of the language and as such if it is the correct way to do it and doing it any other way makes the code complicated then using a goto does have its uses.
 
I don't use prototypes. If i have to implement it in a function, then i just wirte the whole thing in above any code. However, i usually program only with classes, so this has never really been an issue with me.

using discriptive variable names and using a convention in your naming standards helps as well. For example, if you ALWAYS name something in a class as myVariableName, then you , or any maintence programmer that comes along, wil be able to use or read it easily.

All that has been mentioned before is wise. Strive to make our code as clean as possible, unless of course you are working as a contractor, then you know that you want them to NOT be able to read your code. If that is the case, read here: http://mindprod.com/unmain.html.
 
bobvodka said:
The 'never use gotos, ever' rule is a bit of an iffy one, if you can avoid it do so, however its part of the language and as such if it is the correct way to do it and doing it any other way makes the code complicated then using a goto does have its uses.

There only any good for hacks and hacks are the reason for windows instabuility.
 
popular misconception, the trick is to know WHEN to use them, i admit i've never come across a point where a goto has been a logical choice, normaly a small rewrite of the code does the job, however there are cases and i belive both the STL and Boost libraries use goto in them :)
 
10 PRINT "phantom sucks"
20 GOTO 10


WIN!
 
Watch your back, Mr Vodka. Watch your back....
 
Something I'd also like to ask, what's so wrong with prototyping functions? The fact is if you're going to be making derrived classes and the like it's a necessity. I've never heard it was bad and for the life of me can't think of why.
 
I had someone tell me that my code was nasty and when I asked him why he said it was because of my functions. He said I should try to fit as much as I can into my main(). After that I proceeded to ignore everything else he ever said.
 
but it is true. The main() is the place where a person looks first. And then after going to the functions and all there is ALOT of scrolling needed. So more in the main(), the less scrolling and finding the functions is needed.

also, being able to show clear seperation of parts is neccassary. along with indenting. (bad indenting is very sloppy)
 
btw

do
{
cout << "Submerge owns all" << endl;
x=0;
}while(x==0)

muhahaha?!?!?!
 
As long as you tab everything out and cluster similar portions of code, everything is fine. That's assuming your code is efficient to begin with.
 
A friend of mine was taking C++ classes at OU and after the first semester his teacher automatically failed anyone who's main() was larger than five lines.
 
thats total bullcrap

that isn't efficient coding at all

I'm assuming that's in reference to the OU teacher's views on code?

Also, you didn't declare x correctly. It should be:
int x=o;

pwnd!
 
Anable said:
I'm assuming that's in reference to the OU teacher's views on code?

Also, you didn't declare x correctly. It should be:
int x=o;

pwnd!
x would've been declared before the do-while loop. any coder should know this. hell, the program wouldn't run..!!!

i never declared iostream, main(), a return 0, etc.

pwnzored
 
Code:
while(1)
	std::cout << "Submerge doesn't really own all." << std::endl;

Much better, this loops infitely as yours does, saves variable space, doesn't require a using directive above and takes up three less lines.

Do...While loops are fairly useless, like goto. But of course all have their uses. I am forced to cite the occurance of goto in a little game called Quake you might have heard of it?

As for main() well, main is the entry point for your application (standard C/C++), where you go after that is up to you, but generally I don't do much in main().
 
HybridM said:
Code:
while(1)
	std::cout << "Submerge doesn't really own all." << std::endl;

Much better, this loops infitely as yours does, saves variable space, doesn't require a using directive above and takes up three less lines.

Do...While loops are fairly useless, like goto. But of course all have their uses. I am forced to cite the occurance of goto in a little game called Quake you might have heard of it?

As for main() well, main is the entry point for your application (standard C/C++), where you go after that is up to you, but generally I don't do much in main().

Actually I'v used do {} while(); alot, it's usefull when you want to reuse a variable whithout haveing to make sure it's been reset to a value which will cause it too skip the loop altogether. I would say it's much more usefull than GOTO.

As for main() I use it quite a bit because I havn't wrote any extremely complicated programs yet. I normally put the menu and initialization code in main(), I try not to make it over a page long though, but thats the same with any function I write.

Also I was wondering what people's opinions on global and static variables are? in a small program (e. g a pong clone I'm makeing) I don't see any problem with them, but I was wondering what problems people run in to when useing them in a larger program? Alot of people are against them, but I'v seen them used in many API's.
 
OK, do{} while() isnt fairly useless, infact if you think that you're an idiot and dont understand the point of it, do{} while() insures that a loop is run at least once and is much saner than trying to crow bar a while(){} loop to do it.
Know the tools for the job, things exist in the language for a reason.

Secondly, putting all your stuff in a main() function is complete bollox and utterly utterly wrong wrong wrong. While i disagree with failing ppl on more than 5 lines your code should be properly structured. Assuming you have named your functions correctly it should be clear from the function name which the code in it does, thus reduces the reading that someone has to do in the main function to understand what it does, infact same applies to all code.

Before someone tries a 'function call overhead' issue with me, dont even bother, its trivial at best in 99.9% of the situations and where it isnt you can often inline code using the inline keyword enables you to maintain program readability and get around the overhead on functions which require it.

Globals... meh, this tends to break down into a holy war, however it is best to avoid them because it ties code together too much, introduces an external dependancy and reduces the control over the varibles. Properly coded there are very few times when a global is required.
For varibles/objects you require to access in alot of places you should really pass down the line, however there are a couple of design patterns which help get around it in various ways.
Firstly there is the singleton pattern, which is technicaly speaking a global with lifetime control, which the object controls its self. There are a few variations on it so best to google around :)

I've currently forgotten the other design pattern, but it works by using static varibles for all its data members and functions, so that any instance of the object created acesses the same data/functions as all the other instances.

statics are fine as long as you know what you are doing with them, statics in C++ work differently to statics in C which iirc work slightly differently to statics in Java. From a C++ pov what static does depends on its scope, i would go into more detail but having taken a shifty at the spec and seen it refered to across a few pages i'll let you go and learn yaself ;)

Clear seperation of parts is important, so is scoping, sometimes its handy to shove things in a { } block to avoid scoping problems :)

btw, i assume you all declare your for loops correctly in C++, yes ?
Code:
for(int i = 0; i < j; ++i)
{
    // do stuff
}
// and not
int i;
for (i = 0; i < j, ++i)
{
    // do stuff
}
 
bobvodka, why is it important to declare it in the loop rather than before it?

I'm not challenging that logic, I'm simply ignorant of its reasons.
 
its a scope thing, in the first loop the 'i' comes into scope and is valid until the end of the loop at which point it goes out of scope and is allowed to be used again.
In the second example the varible 'i' hangs around from its creation point to the end of the function (or { } block) it is in, which can lead to problems if you go to use it again in another loop and forget to reset it.

side note: VC6.0 doesnt do it right, but then its horribly borken when it comes to standard C++ anyways and you should avoid using it if you can, and VS.Net requires you set a compiler flag to enforce scoping rules (its off by default to prevent the breaking of old code), however its worth getting into the habit of doing it :)

This also brings me onto a related point, in C++ you should delay declaring varibles until you need to as its possible you might not need them at all during the functions life time thus you have suffered the creation 'cost' for no reason. Any C++ code you see with varibles declared at the top isnt wrong, its just bad and is probably the result of the person having coded in C or having been taught C++ by someone who coded in C.

btw, Anable; I can understand you being ignorant to the reason behind varibles being declared in for loops, i wasnt taught that way until recently and its only since VS.Net that MS have produced a compiler which conformed to the standard well enuff that it makes sense to pay attension to the rules 100%.
 
I'm not so sure declareing variables just before you need them is a good idea, personally I would like to see all the variables that are going to be used in the function, in one place at the top, apart from a variable like 'I' as mentioned in the above example. Although I never forget to reset variables that are going into a for loop and i would have thought it would be slower to redeclare a variable everytime you need it, although I suppose you would never notice the difference.
 
for an int the cost of redeclare vs set to zero is probably the same thus you are better off writing correct code instead of micro-optermising which gains you nuffin and loses safety.

It might not seem like a good idea, but the main issue is construction cost, if say you have to declare 5 varibles at the top and then have a quick out exit on the next line you've wasted the time setting up those 5 vars and then removing them. Now, for an int it might not be a huge issue but once you start constucting and destroying objects on the stack, complete with non-trivial constructor/destructor, that cost starts to mount.
Thus declare and initalise at the time needed delays that cost and improves function efficency.

btw, by 'declare and initalise' i mean doing the following:
Code:
int i = 5
// instead of 
int i;
i = 5;
and given that you cant initalise at the top of a function as you might not have the infomation to set the varible as required.

btw, this isnt just me saying this, most of this infomation comes from the book "C++ Gotchas" by Stephen C. Dewhurst which is a well respected book in the C++ field.
 
Well I guess if I was doing something more advanced and/or speed conscious, I would follow what your saying, but for me keeping my code simple is more important. Plus my teacher says to put all the declarations at the top... not that i give a shit what she says.
 
your teacher is wrong, simple as :)

its better to do the correct thing all the time then sometime, otherwise you get out of the habit of doing it and end up not doing it all the time.
With correctly named varibles and correct initalisation its no less clear declaring at the top than half way though, and with C++ doing it when you need it is the CORRECT way to do it, doing it any other way is basicaly wrong...
 
heh, it's not the teacher thats wrong it's the AQA (exam board).... actually I'm wrong, we're being taught Pascal in college, your forced to declare variables at the top in that.
 
ah, well, in that case fair enuff ;)
Different languages have different setups so beyond C++ i cant really comment on whats right and whats not beyond a general sense :)
 
Back
Top