DonationCoder.com Forum

Main Area and Open Discussion => General Software Discussion => Topic started by: Josh on December 30, 2012, 11:02 AM

Title: Good coding conventions - Discussion
Post by: Josh on December 30, 2012, 11:02 AM
OK, a little background on the reason behind this post.

I have recently started teaching myself Java in an effort to start dabbling in Android development. I am using the Eclipse (http://eclipse.org/) IDE in combination with the Sam's Teach Yourself Java in 21 days - Covering Java 7 and Android (http://my.safaribooksonline.com/book/-/9780132841641) book.

As a course of habit, I find myself skimming each chapter so that I can see what things I might possibly miss by assuming I knew all of the material (yes, even variable types. I actually learned something reading through the types). This is where the discussion I want to have arises from.

When coding, I know common coding conventions such as coding indentation for readability, CONST/Finals being written in ALL CAPS in order to identify them as such. I was wondering, what other practices do each of you follow as you code and which are considered industry best practice?
Title: Re: Good coding conventions - Discussion
Post by: Renegade on December 30, 2012, 11:41 AM
Ah... I see someone is looking to start a war! ;D

Pascal for this, camel for that, CAPS for another, and _these get underscores, while strThose get a pretty prefix, and so do btnThese. :D

Object.toString() or Object.ToString() or Object.tostring()?

I stick mostly to C#, Java, C and VB naming conventions. I like a bit of this and a bit of that. e.g. I like private field names with an _underscore and camel case:

_somePrivateFieldName

I'm not fond of:

m_something

I like public properties in Pascal case:

SomePublicPropertyName

I also like method names in Pascal case.

I like controls in Hungarian:

btnGoButton
pbxBigPictureBox
wbrMainWebBrowser
lblInputLabel
txtTextbox
etc.

While this is short:

if (condition)
   DoSomething();

I prefer:

if (condition
{
   DoSomething();
}

It's just easier to see/read when skimming. I'm not usually very fond of:

condition ? DoSomething() : DoNothing();

It has its uses, but often it's harder to read. Sometimes it is easier... depends... No right answers as far as I can see. Verbose and terse both serve a purpose.

I think following conventions is more important when you work in larger teams, and especially when other people, that you will never meet, end up using/modifying your code.

I do like lots of comments though.

Reading on variable types really is essential for a language though. Some languages do things that you would NEVER expect with some types, and as you're reading through, you end up going, "Ah... now I see what that didn't work..." They usually all make sense in their own contexts. Just different flavours. e.g. If you allocate memory for an integer but don't assign a value, what is the value? zero? null? Both are valid assumptions. Same for a string. Is it null or empty?
Title: Re: Good coding conventions - Discussion
Post by: Ath on December 30, 2012, 12:18 PM
+1 on all Renegade said :up:

@Josh, when working with Eclipse, I always use the default format layout (Ctrl-Shift-F), as it's a Java-layout standard on it's own, only I've made line and comment widths a bit wider then the default 80 characters, 160 is usually most optimal.
Aligning variable declarations does make source more readable, so that's an option I tend to enable for projects with larger sources as well.
Title: Re: Good coding conventions - Discussion
Post by: wraith808 on December 30, 2012, 12:22 PM
another +1 on what renegade said.  But in the end, I think it's a matter of audience and consistency when dealing with any project rather than slavish attention to anyone else's rules.

Other than I hate the rule we have at work with no underscores!  so private variables are thisIsAProperty and public ones are ThisIsAProperty.  I know they did it because we should be using autoimplemented properties now... but in some cases you can't and that rule sucks!
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 12:37 PM
Ah... I see someone is looking to start a war! ;D

Pascal for this, camel for that, CAPS for another, and _these get underscores, while strThose get a pretty prefix, and so do btnThese. :D
...
I stick mostly to C#, Java, C and VB naming conventions. I like a bit of this and a bit of that. e.g. I like private field names with an _underscore and camel case:
_somePrivateFieldName
I'm not fond of:
m_something

Heh I'm no coder, so allow me to be a pest as a Humanities type intruding where I don't belong!  ;D

I like CamelCaps aesthetically. I hate Under_scores. : )
Title: Re: Good coding conventions - Discussion
Post by: 40hz on December 30, 2012, 01:30 PM
I'm not much of a coder. But I do work a lot with administrative scripting as part of my job.

My only suggestion is that whatever coding conventions you adopt, you use them consistently.

I often transfer scripts to people. And I sometimes inherit scripts written by others. And within the community of sysadmins I work with, the key factor for what constitutes "good" or "best" coding practice is consistency. As long as your coding conventions are applied logically and consistently, they can be understood and modified - or fixed - if in error.

That also makes them easy to change if you learn (or discover) a better (for you) way to do something. In my case, I currently dislike underscores - and very much like CamelCaps - although there was a time when I preferred the exact opposite. (Aging eyesight has a lot to do with it.)

I also agree with Renegade about comments. Good comments make the difference between partial and complete insanity when you revisit something you previously wrote, or when you have somebody else's zen-telegram dropped on your desk for a fix, mod, or rewrite.

Ditto with Renegade's general preference for not getting "fancy" with what you can get away with when it comes to formatting or putting multiple statements on one line. I was taught: When in doubt - spell it out. And over time I also learned that it's usually better to "spell it out" even when you aren't. Because your "style" will change as you learn more and gain experience. And there's nothing worse or more embarrassing than confronting a piece of code you wrote a few years previously and no longer knowing exactly how it works. Most times I've had it happen to me was when I picked up a "little trick" someplace, or decided to get cute just to show off how savvy I was about what I was doing. I've since learned better and have become a much happier sysadmin because of it.

That's about all I can suggest. I'll leave the rest of the discussion to the real pros we've got here. 8)

Good luck and happy coding! :Thmbsup:
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 01:41 PM
I'm not much of a coder. But I do work a lot with administrative scripting as part of my job.
 In my case, I currently dislike underscores - and very much like CamelCaps - although there was a time when I preferred the exact opposite. (Aging eyesight has a lot to do with it.)

My eyes have sorta held steady for 20 years, I just somehow conceptually hate underscores. When pushed, I'l use dashes. When did the battle over Dashes vs Underscores happen? Does someone have a nice meaty 3000 word blog to link to?
Title: Re: Good coding conventions - Discussion
Post by: mouser on December 30, 2012, 01:41 PM
40hz said the most important thing, imho, and where i often fail, to my deteriment:
My only suggestion is that whatever coding conventions you adopt, you use them consistently.

Particularly when it comes to variable and function naming -- pick a convention and stick with it.

I suppose when it comes to style choices, my view is to always aim for clarity and avoid cleverness.

Cleverness always ends up meaning "hard to maintain" in the long run.

Most things are clearer in 3 lines of code than crammed into 1 line.  Choose the 3 line way.

In a similar vein, don't be afraid of nice long variable names and function names.. I personally have no problem with names made up of whole long phrases.

And my #1 suggestion to new coders:  Look for places where you repeat yourself.. When you find such an occurrence, that's your signal that you need to restructure your code and use a function or object.  Avoid repetition of code and you are half way there.

If you want to try to meditate on good coding -- from my stand point it all boils down to writing code so that it's easy to MAINTAIN (modify, extend, etc.).  You should always be organizing code so that it would be easy to change how something works.  The more likely you are going to actually need to change something, the more you need to modularize your code around that component to make it easier to replace that piece of code.
Title: Re: Good coding conventions - Discussion
Post by: Stoic Joker on December 30, 2012, 09:40 PM
My coding style is an ecclectic mixture of thing I picked up along the way. This is a side effect of being self taught, as thre was no one to force me to do things their "correct" way. However one thing that has proven handy is that in addition to commenting I always put a header comment above each function stating (in short) what it is/does.

This header is outlined with some manner of (basically lamed assed) ASCII "art" so for example:

Code: C [Select]
  1. //===========================================================
  2. //--0000---------+++--> This Rewards Good Input With a Cookies:
  3. BOOL isInputGood(int iPut) { //--0000----------------+++-->
  4.     if(iPut) GiveCookie = TRUE;
  5.    else GiveCookie = FALSE;

This allows me to do 2 things:
Title: Re: Good coding conventions - Discussion
Post by: Renegade on December 30, 2012, 09:48 PM
My coding style is an ecclectic mixture of thing I picked up along the way. This is a side effect of being self taught, as thre was no one to force me to do things their "correct" way. However one thing that has proven handy is that in addition to commenting I always put a header comment above each function stating (in short) what it is/does.

In Visual Studio with C# you can add comment documentation above a method very easily by using 3 slashes:

///

In the past I've kind of ignored doing that, but I've learned that it is a very, very nice little feature, and that it's best to take advantage of it whenever possible.

Here's a simple example:

Code: C# [Select]
  1. /// <summary>
  2.         /// A simple constructor override to let you set the HTML of the browser and create an arbitrary number of buttons.
  3.         /// </summary>
  4.         /// <param name="html">The HTML for the browser.</param>
  5.         /// <param name="buttonTexts">The text for each button. The form returns the text value for the clicked button when it closes.</param>
  6.         public HelpWindow(string html, string[] buttonTexts)

You get the summary and a field for each parameter all for free when you type ///. Very simple, fast and elegant.
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 09:54 PM
Other than I hate the rule we have at work with no underscores!  so private variables are thisIsAProperty and public ones are ThisIsAProperty.  I know they did it because we should be using autoimplemented properties now... but in some cases you can't and that rule sucks!

I sorta get the use of dividers, but what am I missing about Underscores vs Dashes? I somehow mind dashes less, and I have no idea why.

Edit: Oops, per Mouser, I repeated myself. I'll go slink into a corner now. : (
Title: Re: Good coding conventions - Discussion
Post by: Renegade on December 30, 2012, 09:57 PM
I sorta get the use of dividers, but what am I missing about Underscores vs Dashes? I somehow mind dashes less, and I have no idea why.

What language are you using? Dashes aren't legal in a lot of languages (I can't think of one where they are legal) because that creates ambiguity, e.g.:

Code: C# [Select]
  1. int something = an-integer - another-integer;

Compared with:

Code: C# [Select]
  1. int something = an_integer - another_integer;
Title: Re: Good coding conventions - Discussion
Post by: Stoic Joker on December 30, 2012, 09:57 PM
In Visual Studio with C# you can add comment documentation above a method very easily by using 3 slashes:

///

That depends on which version of VS you're using. For some reason three slashes will break your code in VS2005 (yes I still use it frequently). But I (am nutz and still) primarily work in pure Win32 API C++
Title: Re: Good coding conventions - Discussion
Post by: Renegade on December 30, 2012, 09:59 PM
In Visual Studio with C# you can add comment documentation above a method very easily by using 3 slashes:

///

That depends on which version of VS you're using. For some reason three slashes will break your code in VS2005 (yes I still use it frequently). But I (am nutz and still) primarily work in pure Win32 API C++

I haven't used 2005 in a long time. I'm using 2010 now, with no plans to migrate to 2012 at the moment.

But I didn't know that it broke in 2005. Might have been a reason that I didn't use them way back then.
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 10:01 PM
What language are you using? Dashes aren't legal in a lot of languages (I can't think of one where they are legal) because that creates ambiguity, e.g.:

Code: C# [Select]
  1. int something = an-integer - another-integer;

Compared with:

Code: C# [Select]
  1. int something = an_integer - another_integer;

(Ghetto) None, becuz I' no programmer bro. I just be a dumb humanities birdie. (/Ghetto)

So my only use case is naming files when I don't feel like seeing a lot of %20's in my file names on remote sites. I use spaces the rest of the time in Windows. So I never ever had a use case for Under_Scores, and now that I'm cranky and senile at an early age they annoy me. : )
Title: Re: Good coding conventions - Discussion
Post by: Renegade on December 30, 2012, 10:05 PM
(Ghetto) None, becuz I' no programmer bro. I just be a dumb humanities birdie. (/Ghetto)

So my only use case is naming files when I don't feel like seeing a lot of %20's in my file names on remote sites. I use spaces the rest of the time in Windows. So I never ever had a use case for Under_Scores, and now that I'm cranky and senile at an early age they annoy me. : )

Ah. Got it. I was thinking way back to when spacing was significant and a single space could break things. Under those conditions, it would be possible to have dashes in variable names with the further condition that operators like minus were padded on the left & right with a space. Couldn't think of a language that did it, but I could imagine it being possible.
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 10:08 PM
Ah. Got it. I was thinking way back to when spacing was significant and a single space could break things.

And so was I, and for that dashes worked for me because you don't do math on file names. So somewhere underscores made me grumpy. :)
Title: Re: Good coding conventions - Discussion
Post by: wraith808 on December 30, 2012, 10:30 PM
In Visual Studio with C# you can add comment documentation above a method very easily by using 3 slashes:

///

That depends on which version of VS you're using. For some reason three slashes will break your code in VS2005 (yes I still use it frequently). But I (am nutz and still) primarily work in pure Win32 API C++

Maybe it's the Win32 API C++?  Because the /// convention works for me in VS2005, and I've been using them religiously.  I didn't pay attention to the C++ code- it's mostly get in and get out without making a mess.
Title: Re: Good coding conventions - Discussion
Post by: Stoic Joker on December 30, 2012, 10:42 PM
In Visual Studio with C# you can add comment documentation above a method very easily by using 3 slashes:

///

That depends on which version of VS you're using. For some reason three slashes will break your code in VS2005 (yes I still use it frequently). But I (am nutz and still) primarily work in pure Win32 API C++

Maybe it's the Win32 API C++?  Because the /// convention works for me in VS2005, and I've been using them religiously.  I didn't pay attention to the C++ code- it's mostly get in and get out without making a mess.

Now that is a good possibility, as I almost never use C#. I had one C# project that I was doing for the office but it hit the wall early last spring due to "Scope Conflicts" (e.g. Nobody could/would nail down exactly WTF'ing thing was supposed to do).
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 11:33 PM
I had one ... project that I was doing for the office but it hit the wall early last spring due to "Scope Conflicts" (e.g. Nobody could/would nail down exactly WTF'ing thing was supposed to do).

Eew Scope clashes. I just ran into that today with my commission. : (
Title: Re: Good coding conventions - Discussion
Post by: Renegade on December 30, 2012, 11:43 PM
I've had people define scope as "good". I mean that quite literally. Huh? Yep. Not a joke.
Title: Re: Good coding conventions - Discussion
Post by: TaoPhoenix on December 30, 2012, 11:51 PM
I've had people define scope as "good". I mean that quite literally. Huh? Yep. Not a joke.

Good scope is good! What's the problem? Who are you to argue with Good Scope?  :)
Title: Re: Good coding conventions - Discussion
Post by: 40hz on December 31, 2012, 11:04 AM
When pushed, I'l use dashes. When did the battle over Dashes vs Underscores happen? Does someone have a nice meaty 3000 word blog to link to?

I was always under the impression that back when coding was mostly done on a slightly fuzzy green screen in all upper case that most programmers felt that:

    THIS_IS_SOMETHING

was more obvious and easier to read than:

    THIS-IS-SOMETHING

At least I remember being told to use underscores rather than hyphens when I was doing things in BSD "because_that_was_the_way_it's_done."

There was also something about the hyphen being an official part of ASCII - whereas the underscore was not. But I forget why some people felt that was significant. Probably had something to do with the underscore being considered more a 'dealer's choice' sort of thing, whereas the hyphen was already spoken for.

Then I got into networking and you soon learned that some implementations of DNS and NETBIOS (and possibly early versions of AD?) had huge problems with names containing underscores. So much so that it often resulted in a broken network when they encountered them. So the word then became never to use underscores (with Microsoft) until Redmond finally got that fixed quite a bit later. However, some network devices still have problems with underscores to this day - so for network applications and environments, underscores are best avoided. But I don't think any of that was ever much of an issue with general programming unless one or the other character was illegal or reserved by the specific language.

FWIW - in most network situations I avoid using both those characters.

 8)
Title: Re: Good coding conventions - Discussion
Post by: Jibz on December 31, 2012, 11:37 AM
Don't know if that had anything to do with it, but AFAIR hyphens were not (originally) allowed in filenames on CDs (ISO_9660w from 1988).
Title: Re: Good coding conventions - Discussion
Post by: Stoic Joker on December 31, 2012, 12:35 PM
FWIW - in most network situations I avoid using both those characters.

+1  :)
Title: Re: Good coding conventions - Discussion
Post by: superboyac on December 31, 2012, 01:04 PM
Here's a question...
your choice: space, underscore, hyphen...which one do you use if you know none of these things mentioned above?  i always was under the impression that spaces are terrible for anything, so that leaves hyphens and underscores.  And when you are trying to indicate a space, and underscore is the preferred choice.  I only use hyphens when i want to distinguish a space that is less important than an underscore.  such as " book-title_author-full-name".  in cases where no special characters are desireable, i'll use uppercase and lowercase to distinguish, like "BookTitleAuthorFullName".  I've actually thought about this way too much.  >:(
Title: Re: Good coding conventions - Discussion
Post by: Ath on January 01, 2013, 06:31 AM
What language are you using? Dashes aren't legal in a lot of languages (I can't think of one where they are legal)
The (good?) old language Cobolw has them. The dialect I've been using (MF) doesn't even accept underscores as a valid character in variable-names, AFAIK :o
Title: Re: Good coding conventions - Discussion
Post by: Renegade on January 01, 2013, 07:44 AM
What language are you using? Dashes aren't legal in a lot of languages (I can't think of one where they are legal)
The (good?) old language Cobolw has them. The dialect I've been using (MF) doesn't even accept underscores as a valid character in variable-names, AFAIK :o

Ah! We have one! Didn't know that.


Another option for things like file names is the period. e.g.

this.is.a.file.with.periods.txt

Of course, you can't use them in a lot of programming languages as they already have a meaning, e.g. Perl, PHP, C#, Java, etc.

I sometimes use periods in file names. All depends on where the file will be used.
Title: Re: Good coding conventions - Discussion
Post by: fenixproductions on January 02, 2013, 11:51 AM
Although I am spaghetti master I would recommend to look here:
http://stylecop.codeplex.com/
Just throw few c# sources from Internet into it to see general styles.

Also worth to check:
http://msdn.microsoft.com/en-us/library/aa260844(v=vs.60).aspx
http://msdn.microsoft.com/en-us/library/xzf533w0%28VS.71%29.aspx
http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
Title: Re: Good coding conventions - Discussion
Post by: f0dder on January 02, 2013, 03:44 PM
Fair amount of sensible things have already been said - I agree with a lot of it.

I prefer well-named and small (private) functions/methods over comments. Comments are fine for documenting your public APIs, as well as some implementation details, quirks and hacky workarounds - but other than that, I prefer to split into small and well-defined steps, and let the code speak for itself. If you end up with method names that are long or weird, that's often a good indication of a code smell.

However, what one person might find "clever" is what another finds "DRYw". I don't advocate using esoteric language features just for the heck of it, but I'm also not a fan of avoiding anything-but-the-basics because you need to cater to throwaway unskilled outsourced programmers. I routinely use the ternary operatorw, as I find it can make code easier to read (yes, sometimes even with nested ternaries!). It isn't suitable in every situation, and bad use can make code unreadable. I often use it when declaring final variables conditionally, when the logic isn't bad enough to warrant factoring out to it's own method.

Use of the ternary operator doesn't mean I'm in the "as few lines of code as possible" camp, though. I often break condition of if-statements into (properly named) booleans or method calls, which obviously results in more code lines... but also in better readability.

As an example of what some people might find "clever", here's a small snippet of code for dealing with JCRw nodes. It's a somewhat low abstraction to be operating at, but sometimes it's the right tool for the job - but there's so much red tape and overhead to deal with, when all you really want is "possibly the value at some subnodes property, or a default value if subnode or property doesn't exist or something goes wrong." - Java doesn't have Lambdas, but it does have the (much clunkier, syntax-wise) anonymous inner classes (http://c2.com/cgi/wiki?AnonymousInnerClass).

Without further ado:
Code: Java [Select]
  1. public class NodeHelper {
  2.         public static final Logger log = LoggerFactory.getLogger(NodeHelper.class);
  3.  
  4.         // ...other overloads omitted
  5.  
  6.         /**
  7.          * Returns a property (or, on error, a default value) from a subnode of a given node.
  8.          * @param node root node
  9.          * @param path "path/to/subnode@property"
  10.          * @param defValue default value
  11.          * @return given property of subnode, or default value
  12.          */
  13.         public static Calendar safeGetProperty(Node node, String path, Calendar defValue) {
  14.                 return safeGetPropertyInternal(node, path, defValue, new Transformer<Calendar>() {
  15.                         public Calendar transform(Property prop) throws Exception {
  16.                                 return prop.getDate();
  17.                         }
  18.                 });
  19.         }
  20.        
  21.         private interface Transformer<T> { public T transform(Property prop) throws Exception; };
  22.         private static <T> T safeGetPropertyInternal(Node node, String path, T defValue, Transformer<T> transformer)
  23.         {
  24.                 try {
  25.                         final String[] pathAndProperty = path.split("@");
  26.                         final String subPath = pathAndProperty[0];
  27.                         final String property= pathAndProperty[1];
  28.                        
  29.                         if(node.hasNode(subPath)) {
  30.                                 final Node subNode = node.getNode(subPath);
  31.                                 if(subNode.hasProperty(property)) {
  32.                                         return transformer.transform(subNode.getProperty(property));
  33.                                 }
  34.                         }
  35.                 }
  36.                 catch(Exception ex) {
  37.                         log.error("safeGetPropertyInternal: exception, returning default value", ex);
  38.                 }
  39.                 return defValue;
  40.         }
  41. }

It's pretty quick-and-dirty code, but it works well enough for production (*knock on wood*). There's still a lot of Java red tape, Scala or C# (or even C++11) lambdas would have made the various safeGetProperty() into oneliners. Still, no superfluous exception handling all over the place, a fair armount of code lines saved (but most importantly, the core logic is centralized - one place to bugfix). And the "cleverness" is hidden as an implementation detail behind a simple-to-use public API.
Title: Re: Good coding conventions - Discussion
Post by: ewemoa on January 02, 2013, 08:33 PM
May be some day this year?

  Closures (Lambda Expressions) for the Java Programming Language (http://www.javac.info/)
  Project Lambda (http://openjdk.java.net/projects/lambda/)
Title: Re: Good coding conventions - Discussion
Post by: f0dder on January 03, 2013, 01:08 AM
May be some day this year?
Oh, perhaps. If they don't pull it again (Java7 was one big friggin' letdown). And even if/when it's included in the language, there's the issue of enterprise adoption. Java usually means enterprise, and enterprise tends to mean tardy. I'm glad we're at least on Java6, there's several projects out there still running Java5 or worse.

...the above should also answer "so, why don't you just use Scala on your current Java6?" ;-)
Title: Re: Good coding conventions - Discussion
Post by: Jibz on January 03, 2013, 07:47 AM
When it comes to naming conventions, I largely adhere to when in Rome (http://en.wiktionary.org/wiki/when_in_Rome). Personally, I prefer lowercase with underscores. I am not terribly fond of Hungarian notationw -- I feel 90% of the time it is extra typing with no benefit. I can see some benefit in CamelCasew for long names, as long as your editor has some kind of auto-completion, but like f0dder puts it:

If you end up with method names that are long or weird, that's often a good indication of a code smell.

I prefer well-named and small (private) functions/methods over comments. Comments are fine for documenting your public APIs, as well as some implementation details, quirks and hacky workarounds - but other than that, I prefer to split into small and well-defined steps, and let the code speak for itself.

I must admit, I am a big fan of comments :-[. I believe commenting the "intent" of your code is usually worth it. There is not a lot of code outside of textbooks that is really self-documenting, and what seems obvious to you while you are writing the code may take a little time for the next coder (or yourself in a month or two) to figure out. Reading a short line of text is always easier than interpreting a few lines of code. Also, when you look at a function, I think it is a lot easier to grasp what it does if you can skim over it only reading the comment lines (which most text editors highlight in some way), and that gives you a kind of "storyboard". As an example, if you take this simple function

Code: C [Select]
  1. BOOL sut_open(SUPTIME *sut)
  2. {
  3.     wchar_t szCounterPath[PDH_MAX_COUNTER_PATH + 1];
  4.  
  5.     if (sut == NULL) return FALSE;
  6.  
  7.     /* construct path to localized system up time counter */
  8.     if (!make_counterpath(szCounterPath, sizeof(szCounterPath) / sizeof(szCounterPath[0]))) return FALSE;
  9.  
  10.     /* check path is valid */
  11.     if (PdhValidatePath(szCounterPath) != ERROR_SUCCESS) return FALSE;
  12.  
  13.     /* create query */
  14.     if (PdhOpenQuery(NULL, 0, &sut->hQuery) != ERROR_SUCCESS) return FALSE;
  15.  
  16.     /* add counter to query */
  17.     if (PdhAddCounter(sut->hQuery, szCounterPath, 0, &sut->hCounter) != ERROR_SUCCESS)
  18.     {
  19.         PdhCloseQuery(sut->hQuery);
  20.         return FALSE;
  21.     }
  22.  
  23.     return TRUE;
  24. }

and only read the comments you get

Code: C [Select]
  1. BOOL sut_open(SUPTIME *sut)
  2. {
  3.     /* construct path to localized system up time counter */
  4.  
  5.     /* check path is valid */
  6.  
  7.     /* create query */
  8.  
  9.     /* add counter to query */
  10. }

which sums up what it does. Granted, the single lines of code in that particular example are so simple here that you could probably easily understand the function without the comments if you know what the API calls do, but I am guessing it would still take you at least twice as long as just reading the comments.

And like you say, always make a comment about any hackish code, because even though you know how it magically does what it does right now, nobody (including you) will know in a month :huh:.

Use of the ternary operator doesn't mean I'm in the "as few lines of code as possible" camp, though. I often break condition of if-statements into (properly named) booleans or method calls, which obviously results in more code lines... but also in better readability.

I like and use the ternary operator as well, in some situations it lets you express more clearly what you want in less code. Of course you can make unreadable code with it as well, but it's always like that (with great power comes etc. ;D).

Btw, I don't know if it's GeSHI or Chrome, but it looks like most of the identifiers are raised a little above the line (or the operators and keywords lowered) in the code blocks, which is slightly annoying to read:

[ You are not allowed to view attachments ]
Title: Re: Good coding conventions - Discussion
Post by: f0dder on January 03, 2013, 11:43 AM
I must admit, I am a big fan of comments :-[. I believe commenting the "intent" of your code is usually worth it. There is not a lot of code outside of textbooks that is really self-documenting, and what seems obvious to you while you are writing the code may take a little time for the next coder (or yourself in a month or two) to figure out.
Sure thing - it's a delicate balance, and what seems "self-commenting" to one person is an unreadable mess to somebody else. I've rarely revisited code that I thought was "self-commenting" while writing it which I then couldn't grok later on... but I've often been confused by code which I neither commented nor thought through properly.

I prefer "too many" comments over "too little", but at the same time I often take a step back when I find myself adding individual comment lines. Am I doing something a bit too complex that can be simplified? Can I think up better variable/function names?

As an example, if you take this simple function
Well... your sut_open is actually an example of what I consider to be "noise" comments - IMHO they don't really tell anything that the individual API calls don't already (I'm not familiar with those APIs, though I guess they're related to performance counters). Personally I'd probably rename make_counterpath() -> make_uptime_counter_path(), and get rid of all the comments...

But I might add a comment on how to actually get at the counter value, since that's not evident from the code if you're not familiar with the Pdh API (hm, you add a counter to the query, but there's no "execute" thingy, and you close the query handle right after the add? That looks quirky, but none of the comments say anything about it.) Oh, and I'd replace sizeof(array)/sizeof(elem) with a lengthof macro (for C++, I'd probably use a template function for it, since it's slightly ever more typesafe, but this seems to be über-pure C code, from the single-line block comments :P).

But there's definitely other cases where I would do individual comment lines, or at least a comment for a related group of lines... and heck, possibly even comment individual API parameters... the Win32 API is nasty enough to warrant that at times.

Btw, I don't know if it's GeSHI or Chrome, but it looks like most of the identifiers are raised a little above the line (or the operators and keywords lowered) in the code blocks, which is slightly annoying to read:
 (see attachment in previous post (https://www.donationcoder.com/forum/index.php?topic=33484.msg312740#msg312740))
Works fine in the fox of fire, but definitely looks funky in Chrome.
 
Title: Re: Good coding conventions - Discussion
Post by: Renegade on January 03, 2013, 11:56 AM
And now for something completely different! :P

This is kind of wildly off-topic, but it's still damn funny (well, kind of unfunny too) and completely on-topic for naming conventions:

http://www.thestar.com/news/world/article/1309917--girl-fights-government-for-right-to-use-name-given-by-her-mother-only-approved-names-allowed

Girl fights government for right to use name given by her mother; only ‘approved’ names allowed

REYKJAVIK, ICELAND—Call her the girl with no name.

A 15-year-old is suing the Icelandic state for the right to legally use the name given to her by her mother. The problem? Blaer, which means “light breeze” in Icelandic, is not on a list approved by the government.

Like a handful of other countries, including Germany and Denmark, Iceland has official rules about what a baby can be named. In a country comfortable with a firm state role, most people don’t question the Personal Names Register, a list of 1,712 male names and 1,853 female names that fit Icelandic grammar and pronunciation rules and that officials maintain will protect children from embarrassment. Parents can take from the list or apply to a special committee that has the power to say yea or nay.

In Blaer’s case, her mother said she learned the name wasn’t on the register only after the priest who baptized the child later informed her he had mistakenly allowed it.

“I had no idea that the name wasn’t on the list, the famous list of names that you can choose from,” said Bjork Eidsdottir, adding she knew a Blaer whose name was accepted in 1973.

This time, the panel turned it down on the grounds that the word Blaer takes a masculine article, despite the fact that it was used for a female character in a novel by Iceland’s revered Nobel Prize-winning author Halldor Laxness.

Given names are even more significant in tiny Iceland that in many other countries: Everyone is listed in the phone book by their first names. Surnames are based on a parent’s given name. Even the president, Olafur Ragnar Grimsson, is addressed simply as Olafur.

Blaer is identified as “Stulka” — or “girl” — on all her official documents, which has led to years of frustration as she has had to explain the whole story at the bank, renewing her passport and dealing with the country’s bureaucracy.

Her mother is hoping that will change with her suit, the first time someone has challenged a names committee decision in court.

I had no idea that Iceland, Denmark and Germany were strict about what you can name your kid. Just seems bizarre to me.

I figured that a bit of naming insanity would serve as a bit of comic relief that some would find pseudo-related and humourous.

I tried to get my wife to agree to let me name our daughter "Goddess", but... well... I failed. :P "God" if a boy, and "Goddess" if a girl. ;D


Anyways, back to your regularly scheduled thread. :)
Title: Re: Good coding conventions - Discussion
Post by: f0dder on January 03, 2013, 12:05 PM
I had no idea that Iceland, Denmark and Germany were strict about what you can name your kid. Just seems bizarre to me.
The urban legend (which I have done no research of whatsoever) goes that the naming laws were introduced after a girl who was conceived during a bombing in WWII was named "Raketta Bombardina". I personally do find that name laws are sane, considering how mean children are to eachother, and given that some parents are clusterfsck insane - as an adult, you can change your name anyway, and the rules there are somewhat more lax.

But it's all going down the drain anyway, in 2012 "Ninja" (and several other just as silly names) were added to the approved list. "Aloha Ninja" should be approved, for instance... >_<
Title: Re: Good coding conventions - Discussion
Post by: Renegade on January 03, 2013, 12:11 PM
I probably should add this:

http://xkcd.com/327/

[ You are not allowed to view attachments ]

 :Thmbsup:

Title: Re: Good coding conventions - Discussion
Post by: Jibz on January 03, 2013, 01:11 PM
As an example, if you take this simple function
Well... your sut_open is actually an example of what I consider to be "noise" comments - IMHO they don't really tell anything that the individual API calls don't already (I'm not familiar with those APIs, though I guess they're related to performance counters). Personally I'd probably rename make_counterpath() -> make_uptime_counter_path(), and get rid of all the comments...

But I might add a comment on how to actually get at the counter value, since that's not evident from the code if you're not familiar with the Pdh API (hm, you add a counter to the query, but there's no "execute" thingy, and you close the query handle right after the add? That looks quirky, but none of the comments say anything about it.) Oh, and I'd replace sizeof(array)/sizeof(elem) with a lengthof macro (for C++, I'd probably use a template function for it, since it's slightly ever more typesafe, but this seems to be über-pure C code, from the single-line block comments :P).

I am sorry, I thought it was obvious that this was a single function taken from a file -- there are functions to access the values and close the query as well :Thmbsup:.

And (if you'll excuse the tongue-in-cheek) if you think it closes the query right after adding, then I'll take that as an example that even simple code is not easy to read compared to comments :-[.
Title: Re: Good coding conventions - Discussion
Post by: f0dder on January 03, 2013, 03:37 PM
I am sorry, I thought it was obvious that this was a single function taken from a file -- there are functions to access the values and close the query as well :Thmbsup:.
I guessed that much :) - it's just that, coming back to the code after several months & given the other comments in the function, I'd be wondering "why isn't *this* part being commented?". See next comment, though :P

And (if you'll excuse the tongue-in-cheek) if you think it closes the query right after adding, then I'll take that as an example that even simple code is not easy to read compared to comments :-[.
Ah yes (double-tongue-in-cheek), I obviously got distracted by the comments and didn't read the code properly ;-p