Lance's Whiteboard

Random scribbling about C#, ASP.NET, Sql Reporting, etc.

News

BlogMailr Enabled




Sponsored Ad
Sponsored Ad

Blogs I Read

Developer Sites

Googling, etc...

MSDN Resources

Tutorials & Reference

Update: C# Coding Standards v1.13

You can now download version 1.13 of my C# Coding Standards for .NET.

I havent posted on this topic for a while, so here is the change log since v1.09:

 

1.10

05/25/2004

Modified naming conventions for Internal and Protected identifiers.  Added, modified, & removed misc rules.  Corrected grammar, code, and some verbiage.

1.11

06/08/2004

Modified formatting.  Restructured “Language Usage” section.  Corrected language, and added code examples.  Consolidated conflicting rules.

1.12

06/30/2004

Modified code commenting and formatting rules.  Modified various code examples.  Modified Exception Handling and Flow Control sections.

1.13

08/17/2004

Modified layout & added License Agreement.  Misc. grammar adjustments.  Removed rules on foreach vs for pending additional research.  Added rules on switch/case statements.

After my previous update, Anon and I had a lively discussion on K&R Style, for/foreach, and switch/case statements which have been felt in the latest series of changes.   So keep your questions and comments coming!  They are being seriously considered and do impact my thought process.

 

 

 

Comments

Wim Hollebrandse said:

Good stuff Lance!

One tiny remark: custom exceptions should be inherited from the base class 'Exception', not ApplicationException as it add unnecessary depth to the exception hierarchy.

Check out Brad's blog post: http://blogs.msdn.com/brada/archive/2004/03/25/96251.aspx
# August 17, 2004 7:58 PM

AndrewSeven said:

No direct comments this time.
The stuff from Anon was interesting.
I had to look up K&R : Just say NO. Don't make it fit in the window by removing all whitespace, do it by refactoring.

The clone trick is quite nice.

if(condition)ThisIsOK();
if(condition)
ThisIsnt();
SomeoneAlwaysTriesToAddThisCall();

This is bad, blow this thing up with a whole bunch of braces and save yourself (whoever you are) 5 paragraphs of comments.
if(condition)W();
else if(a&&b||c)T();
else if(c&&d&&f)F();
else if(o&&(f&&a))IsGoiongOn();

If code, by looking clean and clear, also looks like it needs refactoring, that is a Good Thing. Refactor it.
# August 17, 2004 10:24 PM

TrackBack said:

# August 18, 2004 7:59 AM

Lance said:

Thanks for catching the mistake to derive from ApplicationException instead of Exception. I'll correct that at once!

I wrote some of this stuff over a year ago, so there are still remnants of old thinking in there.
# August 18, 2004 10:49 AM

Lance said:

Understanding the philosophy behind K & R has always been an elusive thing for me.

My coding style generally is a very defensive one. I try to write code that is maintainable by less-disciplined developers without them getting themselves into trouble by making hard-to-find mistakes.

If you keep the mental-picture in mind of a new developer or intern trying to read, comprehend, and modify your code, then your likely to end up with things like whitespace, liberal commenting, good variable name selection, and simplified conditionals & expressions.

To me, this is a reasonable approach, to others it is sacrilege - to each his own.

I hope this provides some insight into some of my thought processes behind selecting rules, standards, and guidelines.
# August 18, 2004 11:06 AM

Lance said:

I just posted a slight revision(1.13a) that changes the comment about deriving from ApplicationException.

Thanks!
# August 18, 2004 12:21 PM

Travis said:

This is all good and all. But is there anywhere that is explained "Why" some of these standards are standards? Example: "Avoid invoking methods within a conditional expression." Ok, but why should I avoid that?
# August 18, 2004 3:59 PM

Lance said:

The rule you mention is something I discovered through years of experience. After performing hundreds of code-reviews on code from contractors, interns, and new programmers, I saw a trend where bugs were frequently introduced by such statements.

This has been especially true with C# Code written by old VB6(or earlier) programmers due to the different compiler behavior around AND and OR operators in conditional expressions. In VB6, both tests of a statement like "If..X..AND..Y..Then..." are evaluated prior to determining true/false. Yet in most other languages (like C#), the statement is evaluated from left-to-right and short-circuits the remaining expression if the boolean result is already determined by the 1st test. When VB.NET was created, this scenario lead to their creation of the notorious keywords "AndAlso" and "OrElse" which differentiate the choices in conditional operator behavior.

Why should this be a C# standard instead of a VB-to-C# migration tip?

Because it is a good defensive-coding technique that ensures that exceptions, unexpected results, and misunderstandings like the one above do not crop-up during maintenance cycles (often by other developers) when that inline method changes and adds more complex logic. To Avoid the issue, simply invoke the offending method prior to the condition and store-off the result in a local variable, then use that variable in the conditional expression instead of the inline method call.

I hope that all makes sense....
# August 18, 2004 6:08 PM

Lance said:

I'm actually surprised your question hasnt been asked earlier. This is something I need to explain in the document itself rather than make people wonder.

When creating this document, I had (at least) 4 objectives in mind:

* Create a C# Standards document that reflects predominant mainstream opinions on best practices in syntax, style, and function.
* Choose only rules that promotes a defensive coding posture that leads to the "Pit of Success" (See Brad Abrams' posts & mine on the topic elsewhere)
* Limit the scope to topics directly related to C# Programming, and avoid .NET CLR, BCL, and FCL discussions where possible.
* Make all rules simple, clear, intuitive, and self-explanitory.

Since the beginning, it has been the last goal with which I have struggled the most.

The rule you mention is something I discovered through years of experience.

Also, If you combine it with another rule "Avoid compound conditional expressions", then you get the full picture.

Each rule has an assumption behind it, even if the assumption is as simple as "You must already know the C# Language syntax". Rules become harder to write as the prerequisite knowledge grows much further than this point. As a result, in some cases, I make the assumption that you own, will own, or (preferably) have read the books, ebooks, and articles listed in the References section of the document.

This type of assumption is often incorrect or my References are too limited, which makes it harder to determine my reasoning.

So, in the end, I must make assumptions, and then try to make sure my rules are stated as clear and self-explanatory as possible. Unfortunately, that is alot easier said than done.
# August 18, 2004 6:12 PM

Lance said:

One final word on this topic....

An implied objective has always been to keep the document small and concise.

I could actually provide detailed answers to why each standard exists, but the document would easily bloat into a 100+ page book instead of a lightweight reference.


Would you prefer a thicker tome with full analysis and explanations for each rule?

OR

Do you prefer the smaller reference document?

OR

Do you just want me to start posting such explanations to this blog?


I am open to each of the possibilities, but would hate to spend the extra time if it isnt warranted or helpful.

Thoughts?
# August 18, 2004 6:21 PM

Andy B said:

Nice document - very helpful for all .net devs.
# August 19, 2004 5:18 AM

TrackBack said:

# August 26, 2004 2:17 PM

Jason Priestas said:

Good stuff! I personally perfer the 1TBS to conserve vertical space, but that's a matter of preference per developer.
# August 26, 2004 3:55 PM

Nick Govind said:

I am currently involved in a project at uni that involves the development of software in the C#. Am I able to apply the coding standard to our project, of course, without any legal issues arising from it?
# August 28, 2004 5:09 AM

TrackBack said:

# August 29, 2004 4:36 PM

Travis said:

Lance- Thanx for the great response and of course the document itself. I hope I did not come accross as trying to flame the "coding standards" or anything. There is just alot of standards that I dont understand the "why"s. I just thought it would incredibaly educational if there are explenations for each standard. Take for instance FXCop, every rule has link to page that explains "why" the rule was broken. And even sometimes offers suggestions to fix the problem. Anyway... thanx for the great document.
# August 30, 2004 1:54 AM

Lance said:

Travis -

I definitely took your question as constructive and helpful. I hope that my verbose reply didnt come-off as too defensive.

I admittedly am not a formal author, trainer, or conference-presenter. I'm just a fellow developer who has strong opinions on best practices after years of seeing the good, the bad, and the ugly in development.

Most of these rules come from performing code-reviews and are just automatic to me these days. I'm definitely looking at better communicating the reasons, assumptions, and potential solutions to each rule. Also, I have played a bit with turning the doc into a set of FxCop rules, but havent made much progress.

Keep your feedback coming, its all good!
# August 30, 2004 11:03 AM

Lance said:

Nick -

I'm happy to hear you like the coding standards doc.

Anyone can applying the coding standards to any project they wish. It is explicitly allowed by the license contained in the document (and is highly recommended). :)

The only restrictions are in the redistribution or publication of this document. If you wish to include the whole or parts of the document in your work, please just make sure to properly cite this document, my name, and my website in your references.

For APA style electronic references, see: http://www.apastyle.org/elecsource.html

It would probably be something like this:

Hunt, R. Lance, (2004, August). C# Coding Standards v1.13, Retrieved from http://weblogs.asp.net/lhunt/archive/2004/08/17/CSharpCodingStandardsv113.aspx

Thank you!
# August 30, 2004 11:21 AM

Travis said:

The FXCop rules would be a GREAT addition!
# August 30, 2004 12:31 PM

Simon said:

Lance,

In the update from 1.12 to 1.13, you removed the Resources section so there is now no mention of FxCop.

Obviously, from reading the comments in here, FxCop is still an influential tool on your document's development but, as your document develops, will it remain consistent with FxCop's default rule set or are you planning to deviate?
# August 31, 2004 8:20 AM

Avoid using foreach with string arrays ??? said:

I don't know of any reason why we wouldn't want to use foreach on string arrays specifically.

Can you give some explanation on this topic?
# August 31, 2004 9:54 AM

Vishnu said:

I was just looking for some good guidelines for c#, Lance document is really wonderful.
Great work. This document has been written with great dedication.
If people have experience in coding, this is one of the cool way to share their knowledge.

I will be really happy if Lance can write the 100 page document that he was talking about and give reasons for each guideline.

I was really thrilled to see the resons given by Lance for some of the guidelines

Cheers to Lance !!

# September 1, 2004 8:24 AM

Jose Luis Manners said:

Lance, I'd like to suggest expanding item #21 of section 3.2. Being a bilingual programmer, I can tell you that not all programmers in the world speak English, nor they necessarily write their comments in English. That's why Microsoft have versions of Visual Studio in other languages. I suggest word it like: "All comments should be written in English or the official language of the region".
# September 8, 2004 2:26 PM

Lance said:

Sorry, I'm falling behind on responding to your comments...here goes:

Simon,

The resources section was a bit thin, and wasnt referenced elsewhere in the document, so it needed to be removed. However, you are right to question my rules compared to FxCop. My best answer, is "Yes" I plan to keep inline with FxCop in the future, but that is based on the premise that FxCop will be changing in the future. Time will tell the whole story.


"Avoid using foreach with string arrays ???",

The reason is since strings are immutable, each iteration that references a string in the array creates a new string instance. See Jeffrey Richter's Applied .NET Framework book for more/better coverage on this topic.

Vishnu,

Thanks for the praise, it is much appreciated. I have decided to start discussing the reasons and assumptions behind each rule....keep checking the blog as I plan to start this next month.

Jose Luis Manners,

Excellent point! I appologize if this rule seemed too nationalistic or prejudiced towards english speaking countries. However, sculpting such a rules is often much more art than science.

My original intent was to write the document as-if I were managing a team project. However, I havent had much experience with multinational or multilingual teams, and never with teams whose primary language wasnt English, since I am "unilingual" (is that a word?). Therefore, the scope of my rules was limited only to developers in the U.S. who speak english.

However, with the explosion of talented programmers around the world, and even the past influx of foreign workers, I do see the flaws in this approach. I obviously need to expand the scope of this document to take a more global rather than regional outlook.

I'll definitely address your suggestion and example in the next version!

Thanks everyone!!
# September 8, 2004 6:22 PM

TrackBack said:

c# coding standards
# September 14, 2004 5:54 AM

TrackBack said:

It's really too bad there wasn't a nice coding standard like this written up when we started on C# at work. Looks pretty good from what I checked out, I think I'll start following these for my own projects. Lance...
# September 14, 2004 11:50 AM

TrackBack said:

# October 4, 2004 9:21 PM

TrackBack said:

# January 26, 2005 4:33 PM

TrackBack said:

# March 3, 2005 9:12 PM

TrackBack said:

# March 3, 2005 9:14 PM