Skip to main content
gamedev.net
🔒 Locked

Is my code readable?

Started by King of Men Apr 6, 2005 at 10:05 PM 27 replies 4.4k views
Original Post
King of Men
King of Men
I sometimes wonder if my coding style is totally idiosuncratic, understandable only by me, or if I could give my code to someone else and have them read it. So I'm asking you to judge - do I need to change? Here's an example picked at random from the project I'm working on :

private void updateCross () {
   crossection = 0;
   for (int i = 0; i < moduleGeometry.length; i++) {
      for (int j = 0; j < moduleGeometry[0].length; j++) {
	 for (int k = 0; k < moduleGeometry[0][0].length; k++) {
	    crossection += moduleGeometry[j][k].getCrossSection();
	 }
      }
   }
}


private void fire() {
   // Order of ships : First the assigned target, then
   // the detected ones in order of detection. Sorting 
   // already done in detect method. For each ship, try
   // to assign each weapon to fire at it. 

   if (targetShip != -1) {
      fireAt(targetShip);
   }

   for (int i = 0; i < detectedShips.length; i++) {
      if (detectedShips != -1) fireAt(detectedShips);
   }
}

private void fireAt (int target) {
   Vector3d forward = new Vector3d(Math.cos(myAngle), 0, Math.sin(myAngle));
   Vector3d toTarget = new Vector3d(allShips[target].position.x - position.x, 0, allShips[target].position.z - position.z);

   for (int i = 0; i < myGuns.length; i++) {
      if (myGuns.canFire(forward, toTarget)) {
	 // TODO : May want to consider things like volley fire, etc - hence 
	 // separate method for canFire and doFire.
	 myGuns.fireAt(allShips[target]);
      }
   }
}


[Edited by - King of Men on April 7, 2005 12:49:32 PM]
To win one hundred victories in one hundred battles is not the acme of skill. To subdue the enemy without fighting is the acme of skill.
load_bitmap_file
load_bitmap_file
I'm no expert but your code looks fine to me. I don't like spaces after function names, for's, and if's but that's just my preference. I also prefer lining up the vertical curly braces but again, that's just my preference. [smile]
SumDude
SumDude
It's perfectly readable. More comments could make it better though.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                          
Looking for video game music? Check out some of my samples at http://www.youtube.c...ser/cminortunes            
                                                          
I'm currently looking to create music for a project, if you are inte
kingnosis
kingnosis
I would try to be consistant with the curly braces: leave the unnecessary ones out, or leave them in, but don't switch. But then, maybe you've got a reason for doing it that way.

Other than that, looks good to me.
smart_idiot
smart_idiot
You code like a Linux programmer. Well, if you ignore the CamelCase, anyway.

I have no idea what updateCross is supposed to be doing, so maybe it could use a few more comments, but for the most part it looks good.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other
me22
me22
I, on the other hand, prefer K&R style, so I'm glad your braces are on the same line as the if's, for's, and etc's :P

In response to kingnosis : I do my braces like that as well -- if the single statement is on the same line as the if, then I don't put them, but otherwise they're always there, which seems to be how KoM is doing it

For the stuff other than pointless formatting disputes, it looks good. Your variables seem to be consistantly named and sufficiently verbose. For the small functions, the names are reasonable hints at what they do, and the algorithms appear simple enough to not need more commenting. I couldn't tell you more without a larger sample that, for example, included the exposition of the public interface to the class and the associated comments.
ChaosEngine
ChaosEngine
the only thing I'd change is this
if (detectedShips != -1) fireAt(detectedShips);// becomesif (detectedShips != -1)     fireAt(detectedShips);


That way it's easier to tell where the condition ends and the statement begins.
I also always use {}, even on one line ifs. It avoids this kinda problem
if (detectedShips != -1)     identify(detectedShips);// oops this will always be called    fireAt(detectedShips);

but that's just personal preference
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Promit
Promit
Quote:
Original post by Anonymous Poster
Quote:
Original post by smart_idiot
You code like a Linux programmer. Well, if you ignore the CamelCase, anyway.
Java programmer would be a better example, considering also how he allocates Vector3ds and never releases the memory. (I doubt Vector3d is a smart pointer)


Careful inspection reveals that the code is Java.

Or possibly C#.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
Frank Henry
Frank Henry
Sometimes the '{' is out of view on smaller code windows (UltraEdit) when I have all the other windows open. Even then I sometimes overread the '{' at the end of the line.

Personally I favor always using '{}' and putting the '{' in a new line. IMHO makes it easyer to find the matching '}'.
Plus when the '()' and '{}' start to add up in complex ifs it helps when you format them in a way that is easy to read.
Cygon
Cygon
I also like to put the { on the same line, because I think its more consistent with other brace types:

int simpleMethod() const { return m_x; }int complexMethod() const {  return (m_x * m_x) + (m_y * m_y);}callMethod(arg1, arg2);callMethodWithAFarTooLongName(  arg1, arg2);float value = plainArrayAccess[index];float value = nastyIndexCalculatedArrayAccess[  getDesiredIndex() + startingOffset - arrayBase];


Whether a block is started or not can be seen from the indentation, at least it never happened to me that I overlooked the opening brace.

-Markus-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
jollyjeffers
jollyjeffers
That whole issue about lining up (or not) of {}'s is a bit silly. We had a university lecturer who marked you DOWN if you didn't exactly follow his style [oh].

FWIW, I've come across the general convention that in Java you put { on the end of the line with the statment, indent all subsequent items in the block, and then close } on the same column as the initial statement started:
if( true ) {    if( false ) {        //This is never executed    }}

However, in C/C++ and pretty much every other language I've come across it seems to be convention to make the { and } start/finish at the same column:
if( true ){    if( false )    {        //Same as above    }}//OR:if( true )    {        if( false )            {                //Same again            }    }

I don't subscribe to language-bashing if I can help it, but it does seem to me that Java is the odd one out - wanting to do it it's own special way...

Bottom line is - being consistent is whats important [smile]. If you work for a big company (like I do) then coding standards documents will tell you which one to use (the 2nd example in my case)..

Jack
<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ |
CloudNine
CloudNine
Yup, consistency is important. I think the 'put the { on the same line' originated when most people programmed in 80x25 text mode terminals, but I might be wrong there. My personal style is camelBack notation, I think it works well :) Coding style is a kind of religion to many people tho.
jollyjeffers
jollyjeffers
Quote:
Original post by CloudNine
Yup, consistency is important. I think the 'put the { on the same line' originated when most people programmed in 80x25 text mode terminals, but I might be wrong there. My personal style is camelBack notation, I think it works well :) Coding style is a kind of religion to many people tho.

A lot the developers I work with still use mainframe 80x25 style programming/editing. They often tell me that:

IF ( X ¬= 10 ) THEN DO    SAY "X is not 10"END


should be:

IF ( X ¬= 10 ) THEN    DO        SAY "X is not 10"    END


I do prefer their style, but I'd been programming in Java for a while before this and slipped into "Java style" formatting [smile]

Jack
<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ |
CloudNine
CloudNine
Quote:
Original post by jollyjeffers
Quote:
Original post by CloudNine
Yup, consistency is important. I think the 'put the { on the same line' originated when most people programmed in 80x25 text mode terminals, but I might be wrong there. My personal style is camelBack notation, I think it works well :) Coding style is a kind of religion to many people tho.

A lot the developers I work with still use mainframe 80x25 style programming/editing. They often tell me that:

IF ( X ¬= 10 ) THEN DO    SAY "X is not 10"END


should be:

IF ( X ¬= 10 ) THEN    DO        SAY "X is not 10"    END


I do prefer their style, but I'd been programming in Java for a while before this and slipped into "Java style" formatting [smile]

Jack


Out of interest, what are those developers programming?
CyberSlag5k
CyberSlag5k
Yup, looks good to me. As a matter of preference I prefer this style:

while(true)
{
//stuff
}

instead of while(true) {
//stuff
}

but that's only my preference and I don't really mind the other way.
Without order nothing can exist - without chaos nothing can evolve.
_Madman_
_Madman_
I hate
if(stuff) {morestuff}

style, I'm almost ready to make some blue eyes for that...

But then again I code in C/C++, and VS higlights mathing braces. I like when they gets highlighted on same column...

Moreover
#ifndef STUFF#define STUFF#endif


is in no way equivalent to:
#ifndef STUFF #define STUFF#endif
______Madman
tolleyc
tolleyc
Personally, I usually put a comment after all my closing curly brackets.
Example:
for( int n = 0; n < 10; ++n ){ < do stuff > }// End for n


That way I know what is ending what, but thats just me. I don't know if anyone else does that.
jollyjeffers
jollyjeffers
Quote:
Original post by tolleyc
Personally, I usually put a comment after all my closing curly brackets.
Example:
for( int n = 0; n < 10; ++n ){ < do stuff > }// End for n


That way I know what is ending what, but thats just me. I don't know if anyone else does that.

We were required to at university or we lost marks [rolleyes]. I dropped it as soon as it wasn't marked. If you have a decent IDE (currently I'm using Eclipse more than VStudio) then it'll tend to highlight the scope of a given bracket/brace - I find that it be just as useful/easy...

Quote:
Original post by CloudNine
Out of interest, what are those developers programming?

That example was "REXX" a really old scripting language. It's really powerful, but amazingly simple - I learnt it in about 2-3hrs [grin]. However, the developers I referred to actually code in PL/X (an IBM owned derivative of PL/1), C and Assembly. It's more the fact that it's mainframe software that they're writing than the particular languages that require them to use 80x25 displays [smile]

Jack
<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ |
load_bitmap_file
load_bitmap_file
Quote:
Original post by Promit
Quote:
Original post by Anonymous Poster
Quote:
Original post by smart_idiot
You code like a Linux programmer. Well, if you ignore the CamelCase, anyway.
Java programmer would be a better example, considering also how he allocates Vector3ds and never releases the memory. (I doubt Vector3d is a smart pointer)


Careful inspection reveals that the code is Java.

Or possibly C#.


Wait, then in his post why does he say specifically [ code = "cpp" ] ? Wouldn't he do [code = "java" ] if it was Java?
Wildfire
Wildfire
Quote:

Wait, then in his post why does he say specifically [ code = "cpp" ] ? Wouldn't he do [code = "java" ] if it was Java?

Probably because he didn't say anything and the default is "cpp".

'private void updateCross () {...}' is definitly not C++. Either C# or Java.
How do I set my laser printer n stun? o

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.