Home | Blog | Software | Reviews and Features | Forum | Help | Donate | About us
topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • December 07, 2016, 02:38:48 AM
  • Proudly celebrating 10 years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

Last post Author Topic: Good coding conventions - Discussion  (Read 6296 times)

superboyac

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 6,070
  • Is your software in my list?
    • View Profile
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #25 on: December 31, 2012, 01:04:41 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.  >:(

Ath

  • Supporting Member
  • Joined in 2006
  • **
  • Posts: 2,779
    • View Profile
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #26 on: January 01, 2013, 06:31:50 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

Renegade

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,220
  • Tell me something you don't know...
    • View Profile
    • Renegade Minds
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #27 on: January 01, 2013, 07:44:41 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.
Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker

fenixproductions

  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 1,184
    • View Profile
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #28 on: January 02, 2013, 11:51:31 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.microsof...260844(v=vs.60).aspx
http://msdn.microsof...33w0%28VS.71%29.aspx
http://msdn.microsof...studio/ff926074.aspx

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,029
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #29 on: January 02, 2013, 03:44:51 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.

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.
- carpe noctem

ewemoa

  • Honorary Member
  • Joined in 2008
  • **
  • Posts: 2,845
    • View Profile
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #30 on: January 02, 2013, 08:33:51 PM »

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,029
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #31 on: January 03, 2013, 01:08:02 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?" ;-)
- carpe noctem

Jibz

  • Developer
  • Joined in 2005
  • ***
  • Posts: 1,126
    • View Profile
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #32 on: January 03, 2013, 07:47:50 AM »
When it comes to naming conventions, I largely adhere to 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:

CamelCaseHighLight.png

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,029
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #33 on: January 03, 2013, 11:43:30 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)
Works fine in the fox of fire, but definitely looks funky in Chrome.
 
- carpe noctem

Renegade

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,220
  • Tell me something you don't know...
    • View Profile
    • Renegade Minds
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #34 on: January 03, 2013, 11:56:21 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.c...proved-names-allowed

Quote
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. :)
Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,029
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #35 on: January 03, 2013, 12:05:04 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... >_<
- carpe noctem

Renegade

  • Charter Member
  • Joined in 2005
  • ***
  • Posts: 13,220
  • Tell me something you don't know...
    • View Profile
    • Renegade Minds
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #36 on: January 03, 2013, 12:11:28 PM »
I probably should add this:

http://xkcd.com/327/

exploits_of_a_mom.png

 :Thmbsup:

Slow Down Music - Where I commit thought crimes...

Freedom is the right to be wrong, not the right to do wrong. - John Diefenbaker

Jibz

  • Developer
  • Joined in 2005
  • ***
  • Posts: 1,126
    • View Profile
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #37 on: January 03, 2013, 01:11:43 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 :-[.

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,029
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Good coding conventions - Discussion
« Reply #38 on: January 03, 2013, 03:37:09 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
- carpe noctem