Pascal casing or Camel Casing for C# code? - c#

I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower CamelCasing. They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties:
string firstName;
public string FirstName {
...
}
But they are used to this:
string _firstname;
public string firstName {
...
}
I try to keep up with their "standard" so the code looks the same but I just don't like it.
I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.:
System.Console.WriteLine("string")
What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything.
Update:
I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.)

A link to the official design guidelines might help. Specifically, read the section on Capitalization styles.
In the grand scheme of things, Pascal vs Camel doesn't matter that much and you're not likely to convince anyone to go back over an existing code base just to change the case of names. What's really important is that you want to be consistent within a given code base.
I'm just happy as long as you're not using Hungarian.

I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is consistently using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all.

You should have a look at Microsoft's new tool, StyleCop for checking C# source code.
Also keep an eye on FxCop for checking compiled .Net assemblies. FxCop focuses more on the details of what the code does, not the layout, but it does have some naming rules related to publicly visible names.
StyleCop defines a coding standard, which is now being promoted by Microsoft as an industry standard. It checks C# source code against the standard.
StyleCop adheres to your PascalCase style.
Getting people onto StyleCop (or any other standard for that matter) can be hard, it's quite a hurdle, and StyleCop is quite exhaustive. But code should be to a uniform standard - and a personal standard is better than none, company standard is better than a personal one, and an industry standard is best of all.
It's a lot easier to convince people when a a project starts - team is being formed and there is no existing code to convert. And you can put tools (FxCop, StyleCop) in place to break the build if the code does not meet standards.
You should use the standard for the language and framework - SQL code should use SQL standards, and C# code should use C# standards.

For public interfaces you should stick with the MS .NET framework design
guidelines: "Capitalization Conventions".
For non-exposed members then whatever you and your colleagues can agree on.

I (and my team) prefer to reserve initial capitals for class names.
Why? Java standards propagating, I think.

I just found Coding Standards for .Net.

From
.NET Framework Developer's Guide
Capitalization Conventions, Case-Sensitivity:
The capitalization guidelines exist
solely to make identifiers easier to
read and recognize. Casing cannot be
used as a means of avoiding name
collisions between library elements.
Do not assume that all programming
languages are case-sensitive. They are
not. Names cannot differ by case
alone.

Pascal casing should be used for Properties. As far as varible names go, some people use _ and some poeple use m_ and some people just use plain old camel casing. I think that as long as you ae consistant here, it shouldn't matter.

I guess you have to put up with what the coding standard says for your place of work, however much you personally dislike it. Maybe one day in the future you will be able to dictate your own coding standards.
Personally I like databases to use names of the form "fish_name", "tank_id", etc for tables and fields, whereas the code equivalent of the database model would be "fishName" and "tankID". I also dislike "_fooname" naming when "fooName" is available. But I must repeat that this is subjective, and different people will have different ideas about what is good and bad due to their prior experience and education.

Actually, there's no "standard" convention on this. There's a Microsoft edited guideline somewhere, and as with with any other naming convention guideline, surely there's another one refuting it, but here's what I've come to understand as "standard C# casing convention".
PerWordCaps in type names (classes, enums), constants and properties.
camelCase for really long local variables and protected/private variables
No ALL_CAPS ever (well, only in compiler defines, but not in your code)
It seems some of the system classes use underscored names (_name) for private variables, but I guess that comes from the original writer's background as most of them came straight from C++. Also, notice that VB.NET isn't case sensitive, so you wouldn't be able to access the protected variables if you extended the class.
Actually, FxCop will enforce a few of those rules, but (AFAIK) it ignores whatever spelling you use for local variables.

I like the coding conventions laid out in the Aardvark'd project spec

That example of .NET you posted was a function. The adopted "standard" for methods/functions is A capped camel-case (or Pascal, if you want to call it that).
I stick to camel case where I can. It lets you easily know the difference between a variable and a method.
Additionally, I'm a fan of sticking an underscore in front of local class variables. E.g.: _localVar.

Whichever you prefer is what matters, obviously adhering to the team's standard primarily.
In private you code however you want, it doesn't affect the finished product whether you named your variable someVariable or SomeVariable.

The day when i quit programming - its when Microsoft will make CamelCase in C# as standard. Because my grown logic has many reasons for PascalCase, unlike kid's logic, who cares only shorter names or easier to write.
And BTW: CamelCasing comes primarily from C++ STD library style, the native old language inherited from C. So Java inherited from C++. But C# - is entirely new language - clean and beauty, with new rules. Oldfags must programm on Java or C++, new generation people must programm on C# - and they should never interact.
Consider this example:
1) PascalCase: list.Capacity.ToString();
2) CamelCase: list.capacity.toString();
In (1) we have CAMEL CASE in long TERM!!! means listCapacityToString.
In (2) we have bullshit: listcapacitytoString.
Thats how i read. And why CamelCase is illogical for itselt. I could kill for PascalCase, never touch it, kids of any age.
Microsoft - forever or until they use PascalCase.

Related

StyleCop and/or a general style guide?

Similar questions: Styleguide for C# and StyleCop: a complete document
Ok, so I'm looking into some sort of style control at my workplace for the applications we develop in C#. I was initially just planning on producing a style guide (by collecting a number of existing style guides and picking the suitable parts from), however it seems like StyleCop might be a good addition or alternative to a style guide.
So, my question(s) are:
What are the potential problems with a style guide and/or StyleCop
that I am likely to run into?
If I use StyleCop how similar do I want the style guide to be? Do I want to attempt to prevent/limit any variation between the 2 methods? I ask because
if StyleCop doesn't enforce it then it could potentially be ignored (or is that not really too much of an issue?).
If I'm using StyleCop, is it even worth the time and effort of creating a style guide?
Are there any alternatives to StyleCop that a worthwhile looking into? (e.g. An alternative that has very good
usability/customization and "could" be considered sufficient on it's
own).
EDIT: Just a little bit of background, my workplace has a "software department" that is only really just forming now. There is 3 full time c# developers, 3 developers who may touch/use/alter the c# code, a number of BA's and no official testers.
After having been on a team that used/maintained/enforced a style guide and then on a team that used StyleCop, my advice is to use StyleCop exclusively. This is for several reasons:
It is compile-time enforceable. This is a huge advantage when it comes to something as persnickety as style. With a style manual there's always gray area, but there isn't any with a compiler error. This reduces style arguments from "This is wrong"/"No it isn't" to "Which should we prefer", which is (usually) a more civil argument.
If you create your own style, someone (or all of you) will need to be the human "style cop", which is a pretty miserable job. Developers (in my experience) tend to not like people making "style adjustments" to their committed code, and dislike even more when told to make their code conform to the style. This is also time consuming as it's another thing to review during code reviews (you are doing those, right?).
StyleCop comes with a pretty decent set of default rules, and using just these rules will let you match most other C# codebases out there. When I was using our own in-house style manual, all open-source code looked foreign because we used comment headers, capitalized parameters, some Hungarian notation, etc. But when I moved to StyleCop-enforced style with the default rule set, everything looked familiar!
Creating your style means you're going to spend a lot of time re-inventing the wheel, and then maintaining that wheel when edge cases and arguments appear. That's a non-zero amount of work and can chew up a lot of time; from my experience developers will always debate code style.
It has a decent editor to configure your rule set if you don't like some of the defaults or need to add abbreviations that StyleCop should ignore.
You can write your own rules or use those that others have published. For instance, some on our team hate trailing whitespace, so I include these rules to enforce that.
As far as alternatives, I don't know of any that are as seamless as StyleCop is. I should note that I've only ever used it in conjunction with Resharper/Visual Studio, so if you have a different environment then your mileage may vary.
FYI, the new StyleCop Analyzers NuGet Package is a major improvement on things. You can now hand-pick your StyleCop rules (or just use the default selections) by editing the project's rule set (Properties -> Code Analysis).
I just discovered they've even included three "alternative" rules for teams that follow the dark side... :-)
SX1101 - Do not prefix local calls with 'this.'
SX1309 - Field names must begin with underscore
SX1309S - Static field names must begin with underscore
The best thing you can do in your workplace is teach the value of:
Recognize existing style patterns in a body of code.
Follow the existing style patterns which you make changes to that body of code.
Regardless of the project you are working on, this practice leads to the overall lowest rate of submissions getting returned for style issues. It also requires the least amount of explanation in your style guide.
With that out of the way, you can focus on topics which are less easily inferred from looking at a single file, such as naming conventions used across the code base, threading models in effect, and the interaction between modules at a high level.

Cross-Language coding standards?

I'm looking for advice as to coding conventions. The primary languages I use, in order of frequency are C#, JavaScript, and ActionScript. They are all ECMA-based languages, so for the most part, the syntax is interchangeable. What I would like to do is standardize the way I write code.
I looked around for documents on coding standards and found some, by various authors including Microsoft, Adobe, Doug Crockford, and the authors of various books I own. Much of the individual standards are identical. For example, do not use capitalization to differentiate between object identifiers. Okay, sounds good.
However, they are different in some ways, most notably to me in the naming conventions. For example, using underscores in naming private properties, or camel casing vs Pascal casing for method names.
The C# advice tends to differ more between the others than ActionScript and JavaScript do with each other, which makes it more difficult for me since it is a greater number of languages vs a greater amount of code written. There is also the issue of automatic formatting in the IDE (e.g. the placement of opening braces in functions in JavaScript vs C#).
Any advice as to how you might have approached this problem? Any big pitfalls I'm not seeing? I realize I may be being pedantic, and that I'm lucky enough to work in an environment where I don't have to conform to someone else's standard. I hope to gain some increase in productivity and more readable code. Thanks.
Idioms that make sense in C# aren't necessarily going to make sense in Javascript (and vice-versa), despite the fact that both use pointy braces and semicolons.
We use different coding styles - for the most part, standard Microsoft style for C# and for the most part, standard jQuery style for Javascript. It can be a bit strange-looking (the disjoint of Pascal versus camel case means that you have some C# objects that have "improper" casing because they're pretty much just there as JSON containers), but I wouldn't try to shoehorn what are two discrete languages into a single grammar.
I would stick to the standards proposed by the communities or creators of the languages instead of trying to create one standard that crosses boundaries. Doing otherwise tends to torque off developers that are passionate about and active in the communities surrounding the language.
We tried to do that at one of my employers with Delphi and C#, and no one was happy.
I'm lucky enough to work in an environment where I don't have to conform to someone else's standard
Personally I don't follow the Microsoft standard for C#: instead, all my method names and property names use camelCase (though my types still use UpperCase). And, I decorate my member data (so that it can't be confused with local variables, properties, and/or parameters).
I don't see why it's necessary to follow Microsoft's naming conventions; IMO it's even occasionally a good thing not to: when I subclass a Microsoft type, the case (e.g. 'add') distinguishes my methods from Microsoft's methods (e.g. 'Add') in the underlying base class.
Also when I'm writing C++, I don't follow the same naming conventions as the standard library authors (who use lower_case for their types whereas I use UpperCase).
It is true however that other developers may/do not like it; for example, someone commented on some example C# code that I posted in some answer here on SO, to criticise it not for its content but for its naming convention.
This is a matter of preference really, because that's just what coding standards are: standards. There is no obvious right or wrong here, enforcing every language's community standards has a lot going for it until you are working in 5 different languages frequently which all have subtle differences. You will not be able to keep up and start following neither standard.
What I have done before is use the same standard for languages in the same ballpark (PHP, Java, Ruby), and then some specific ones if it was absolutely impractical to use that same set of standards, and the code looks different enough for your brain to also make the switch (for BASH scripts for instance).
But really it's what you (and the rest of your team) agrees upon. You don't gain productivity from a specific set of coding standards, you gain productivity by having the same standards as the people you work with. If you want to go full out hungarian camel case with an underscore on top: more power to you, just make sure the entire team does it ;)

Are variable prefixes (“Hungarian notation”) really necessary anymore? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Since C# is strongly typed, do we really need to prefix variables anymore?
e.g.
iUserAge
iCounter
strUsername
I used to prefix in the past, but going forward I don't see any benefit.
Are variable prefixes ( Hungarian ) really necessary anymore?
NO!
In fact, Microsoft's own style guidelines (where the practice originated) now recommend against it. In particular, see the section on General Naming Conventions, which includes the following text (in bold type, no less):
Do not use Hungarian notation.
Of course, these guidelines are not binding or mandatory outside of Microsoft. However, this is the published recommendation of the platform vendor, and it goes beyond merely removing the positive recommendation from any prior guide, to instead a strongly-worded and emphasized negative recommendation today.
In other words, don't use them anymore.
The only places I see fit to bend the standards and prefix variables:
control names: txtWhatever - and I see I'm not the only one. The nice thing is that you can come up with stuff like lblName next to txtName, and you don't need to go into the NameLabel/NameTextBox direction.
class member variables: _whatever. I've tried both m_ and no prefix at all and ended up with simple underscore. m_ is more difficult to type and having no prefix becomes confusing sometimes (especially during maintenance, I know all of you know their code by heart while writing it)
I didn't find any consistent situation where prefixing a variable with its type would make the code more readable, though.
EDIT: I did read the Microsoft guidelines. However I consider that coding styles are allowed to evolve and/or be "bent", where appropriate. As I mentioned above, I found using underscore prefix useful by trial and error, and is certainly better than using this.whatever everywhere in the code.
Supporting the "evolving" theory - back in .NET 1.x when Microsoft released coding guidelines, they advised using Camel casing for everything, even constants. I see now they've changed and advise using Pascal case for constant or public readonly fields.
Furthermore, even .NET Framework class library is currently full of m_ and _ and s_ (try browsing the implementation with the Reflector). So after all, it's up to the developer, as long as consistency is preserved across your project.
If Hungarian means "prefix with a type abbreviation" such as uCount or pchzName, then I would say this practice is bad and thankfully seems to be fading from common use.
However, I do still think that prefixes are very useful for scope. At my studio we use this convention for prefixing variables :
i_ // input-only function parameter (most are these)
o_ // output-only function parameter (so a non-const & or * type)
io_ // bidirectional func param
_ // private member var (c#)
m_ // private member var (c++)
s_ // static member var (c++)
g_ // global (rare, typically a singleton accessor macro)
I've found this to be very useful. The func param prefixes in particular are useful. Way down inside a function you can always tell where that var came from at a glance. And typically we will copy the var to another when we want to modify it or change its meaning.
So in short: prefixes for types are unnecessary with modern tools. The IDE takes care of identifying and checking that stuff for you. But scope-based prefixes are very useful for readability and clarity.
There are also fun side benefits like with Intellisense. You can type i_ ctrl-space and get all the input params to the func to choose from. Or g_ ctrl-space to get all your singletons. It's a time-saver.
Nope. Did we ever need to?
Hungarian notation is ugly. The only exception is with interfaces, where most people think it's acceptable.
Linus sums it up well:
"Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer"
No. Hungarian Notation just adds unnecessary noise to code and is redundant with compiler type checking.
Yes, if Hungarian notation were used as it was originally meant, instead of as implemented by Microsoft. Much like the example above, which shows text boxes and corresponding labels as lblWhatever, txtWhatever. Use it to define the use of the variable, not the type. It can provide information to know that your number is moneyTotal, which tells me more than just the data type.
But, as commonly used? No.
Prefixes are a leftover from the VB (and older!) days when Hungarian Notation was king. That is no longer the case, though the C# community does mandate things like using a prefix of Capital I for interfaces (e.g. ILoadable).
The current Microsoft Guidelines are here.
Hungarian notation is no longer needed to identify data types like in your string example, but it still can be useful for identifying characteristics of variables in other ways. Here's a good article that talks about useful ways of using the Hungarian notation: http://www.joelonsoftware.com/articles/Wrong.html
Here's an excerpt
"In Simonyi’s version of Hungarian notation, every variable was prefixed with a lower case tag that indicated the kind of thing that the variable contained.
For example, if the variable name is rwCol, rw is the prefix.
I’m using the word kind on purpose, there, because Simonyi mistakenly used the word type in his paper, and generations of programmers misunderstood what he meant."
He also uses an example of identifying strings prefixed with an 's' or a 'u' to identify if they are secure to print out or not, so that a statement like print(uSomeString); can easily be identified as wrong.
Most of the arguments I see against Hungarian notation mention that modern editors and IDEs are perfectly capable of giving you all the information you need to know about every identifier. Fair enough.
But what about printed code? Don't you carry out code reviews or walkthroughs on paper? Don't you use printed code for training purposes? Don't you use code snippets for online help? Hungarian notation is extremely valuable in these occasions.
I keep using (some sort of) Hungarian notation in all my code. I find its absence ugly and lacking in information.
I personally don't anymore, however you will still people argue to prefix for scope.
I go with Microsoft and use their Capitalization Styles for all naming conventions. The entire "Design Guidelines for Class Library Developers" section, which that link is a part of, is pure gold, in my opinion.
Additionally, I love the "Framework Design Guidelines" book from Addison Wesley. It covers all of these guidelines with annotations from Microsoft team members on to why they recommend what they are proposing and how it is adopted within the organization.
Well, to counter, I'd say - it depends. I'm personally against them, but it comes down to your team. Each team should be responsible for developing their own set of guidelines. Hopefully that doesn't include so-called Hungarian Notation, but it really should be a team decision. You might find cases where you want to break with the style guidelines.
What makes me curious about this question is the fact that the languages (C then C++) where prefixing (i.e., Hungarian notation) was introduced were also strongly-typed. For all I know, it was done with Pascal's use at Microsoft as well. And it would seem that it was also used with Mesa, a strongly-typed language that the Hungarian may have had some familiarity with [;<).
That being the case, it is fair to get beneath the question and consider (1) what problem was prefixing used to help solve and (2) how has that problem gone away?
I know that's not exactly an answer, but it might be more useful than the blanket objections to use of prefixes as outmoded or wrong-headed.
Even though the compiler can quickly and easily check the type of a variable, humans are unable to do so while skimming a piece of source code.
Therefore some people (like me) prefer to make variable names a tad more verbose, making them quickly recognizable to be global or class variables, string or int, etc.
It might not help the compiler, but when reading a foreign piece of code, it surely saves you having to look up each variable manually...
Definitely not. As a general rule, I've come to believe that it's just noise. If you're an indepedent consultant or your company doesn't have a comprehensive style guide, IDesign has a great guide. Just look on the right hand side of the page and you can D/L the latest iteration of their C# Coding Standard document.
Steve
I only use it in my database (PostgreSQL)
t_ for table name
v_ for view name
i_ for index name
trig_ for trigger
sp_ for stored procedure name
p_ for parameter
v_ for variable
c_ for cursor
r_ for record
Hungarian notation was never meant to be used to show what data type the variable was. It was misunderstood to suggest that "str" or "i" be used to implicitly define the type. It was meant to only show the "kind" of variable, not the "type."
So to answer the question, it shouldn't be used now nor should it have ever been used in the past.
I know it has been linked, but scroll to the bottom of Joel's article for more info - http://www.joelonsoftware.com/articles/Wrong.html where he talks about where Hungarian
For a general overview of good conventions see here:
http://msdn.microsoft.com/en-us/library/ms229002.aspx
There is a book about that in which they explain the reasons behind each of that conventions. Pretty interesting read.
I always prefix instance member variables with m__ and static member variables with s_. I've come across variable articles from MS people who recommend/discourage the approach.
I'm also pretty sure I've come across the m_ prefix when looking through the standard .NET libraries using Reflector...
No, we don't need them. I used to follow this when back in the days, we were forced to follow that kind of a coding standard.
Also with Intellisense, Code Definition Window and Refactoring tools built into VS and other third party plugins like CodeRush express and Refactor Pro, it's easier to work with code without it.
Inside the code and when working with data types I see no reason for the use of Hungarian notation.
But when I'm working with a series of user interface control, be that they are textboxes, dropdown lists, grids or what not, I like to have my intellisense work for me. So to accomplish that, I usually make the id of the control with a prefix of "uxSomeControlName". This way, when I'm looking for that textbox to grab it's text value, all I have to do is type "ux" and all of the user interface ID's are displayed. No need to search for txt, ddl, grd, or anything else.
Now is this correct, if you read the above, no. But I don't want to sit hear and try to remember a dozen or more control names when I just have to know two letters.
Like I said, this is only when working on the front end.
I use it all the time but that could because I use VBA with Access and Excel.
For me CountAll is a name intCountAll is a name with this difference that it additionially describes the name (never intended for machines just for humans) like sintCountAll tells me its static pintCountAll private and gintCountAll global so for the purpose I use it; it is very usefull.
control names is a time safer like instead of ControlName I have lblControlName, txtControlName, cboControlName, lstControlName etc so when I use VBA I just type lst and I have all the names I need so I don't have to remember what is the exact name which saves me a lot of time but again this is mainly VBA in Access and Excel.
Regards
Emil
The only prefix I would consider for C# is a _ for member variables such as
public class Test
{
private int _id;
}
I would say that in most languages these days that have a limited set of types - in particular no concept of unsigned types - then a well-named variable shouldn't need the prefix.
In languages that have signed and unsigned types, or a slew of similar types (e.g. short, int, long or Int8, Int16, In32), then prefixes are useful, despite what anybody else has or will say (and they will, you know it).
The compiler will, at best, give a warning when you try and mix integral types of different signs in expressions, and this could easily be missed if, for example, you configure your IDE to only show errors (not warnings) in a build in the final summary (as you can do with Visual Studio). Mixing signs in arithmetic can seriously ruin your day, so save you or your successor a headache and give them a clue. Remember - you're not the only one who will ever look at the code.
A solution to a problem that doesn't exist.
While many programmers today are abandoning it, I would still use it in certain cases. Here are some of them;
If you are maintaining code that
already uses it, then I would keep
using it.
When your company style guidelines
still require or even suggest it.
When your documentation has a simple
alphanumerically sorted list of
variables, it helps group like types.
I sometimes use a kind of prefix where pName is a parameter passed into my function (notice I don't prefix the type), oName is local to my current method, mName is a member to the class I'm in and cName is a constant or static readonly member.
Personally I find it helps.
The short answer is NO. But...
I see the point of getting away from Hungarian notation, the standards in our shop forbid it, too, but I still find it useful in my one-off or little utility projects for one reason and one reason only: when I am coding to a large number of controls in a web or win form, using HN makes it easy to use Intellisense make sure I catch every single control while coding.
If I have a five checkboxes and their names all start with chk then typing chk gives me the list of every one of them and I can easily pick which one I'm working on that moment.
Also, sometimes I find myself wondering "what the heck was that checkbox named again?" And I have to break off and look in the .ASPX page again.
One way I have compromised is to begin with HN, and then once I have gotten the main code in a win or web form complete, my last step is to do global renames for the HN-named controls. This has actually worked well for me. YMMV, of course.
No, if your methods are so long that you cant read the definition at the same time as the use, or the name doesnt imply the type then you have more serious design issues than just naming.
However, i INSIST that you do prefix controls with their type, such as txtName.

What should be included in a C# Programming Standard?

I've been tasked to write our department's C# Programming Standard (including guidelines). What sort of standards/guidelines should I include? I've already taken bits from various standards around the net (and pieces from Code Complete), but I'd like hear from developers in the field.
I've already got:
Naming Conventions - General/Variables/Classes/Methods/Interfaces/Controls
General Programming Practices - Documentation (comments etc), [WIP]
OO Programming Practices - Encapsulation, [WIP]
What else would be useful? What shouldn't I include?
Have you already suggested that everyone reads the "Design Guidelines for Class Library Developers"? That covers the bulk of it. Other than that, I'd want to hammer home:
You should very rarely be creating your own structs. Don't think of them as lightweight classes.
Structs should never be mutable.
Fields should always be private, apart from readonly fields where the type of the field is immutable
Only attempt lock-free programming if you're sure that a simpler solution will be too slow - and have evidence!
Readability is king
Be aware of cultural issues - in particular, read Microsoft's String Handling Recommendations
I'll add more as I think of them...
Information on how to handle namespaces, assembly/project/solution naming conventions, nameing conventions of files.. grouping of items (for example of your have both Item and Item do they go in the same file?)
File name guidelines
Namespace naming / organising guidelines
Design & architectural guidelines such as using interfaces to create louse coupeling and to make unittesting eaiser (for such as dependency injection and mocking)
Advice on when things should be refactored (long methods and so on)
Naming and casing for parameters
Guidelines on unit testing (if you use it) and on mocking
Grouping of items (for example of your have both a generic and non-generic implementation of a class do they go in the same file or seperate files following a naming convention?)
How to handle 3rd party dependencies
Promoting the use of tools like FxCop, StyleCop and other metrics
Just a couple of things from the top of my head
Guides on maximum method length, maximum class size and maximum loc in a source file are usefull.
Furthermore you can set some guidelines on indentation and code layout and stuff but I found it easier just to do this with settings in Visual Studio and then have your developers import the same settings file for this. This way people don't have to think about this and visual studio does the work for them.
Best practices can be checked automatically too by FXCop and tools like that. So it's usefull to distribute guidelines about that by just making FXCop files available that check all the rules you care about. Dont introduce big FXCop checks in a large existing code-base though try to ramp up the checks over a period of time so people dont get hit with 1000's of FXCop errors
In short:
Try to keep the guidelines short, only include things that are really important. Make them easy to read (you can write naming conventions as an example-class for example where you highlight all the rules with some extra boxes with text) And use tools to automate checks where you can so developers get easy and early feedback.

Do you have any good advice/links to a set of coding standards or best practices to follow?

For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original author of the code you’re working on. Coding styles are often used for specific program languages and some styles in one coding language might not be considered appropriate for others. Of course some coding standards can be applied across many different program languages.
Thank you for your time.
EDIT: As we know there are many related articles on this subject, but C# Coding standard / Best practices in SO has some very useful links in there which is worth a visit. (Check out the 2 links on .NET/C# guidelines by ESV - Accepted Answer)
Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
My best advice regarding coding standards: don't let them get in the way when trying to get work done.
A big bureaucracy might actually hinder progress in projects instead of helping to achieve better team work. When people complain about not following coding standards instead of the actual quality of the code, then it is too much regulation.
Other than that, pick one from the many suggestions and try to stick with it for as long as possible to build a code base following a single standard that you are used to.
Coding standards are good, but coding standards written from scratch in which the company reinvents the wheel, or coding standards imposed by a single "prophet", can be worse than having no coding standards at all.
This means:
Coding standards should be discussed and agreed upon.
The coding standards document should include the reasons behind each rule.
Coding standards should be at least partially based on reliable sources.
The sources I know of for the languages in your tags are:
For C++: The book C++ Coding Standards by Sutter/Alexandrescu.
For C#: 4 or 5 PDF's I found googling for C# Coding Standards :)
Adam Cogan has a great set of rules on his web site. There are coding guidelines, but there is much more there also.
Adam Cogan's Rules to Better...
Coding standards are great. We've been using Lance Hunt's C# Coding Standards for .NET almost without modifications
If you are maintaining code that continue to use the same standard as the original code was developed in (there is nothing worse then trying to debug a problem when the code looks all higgildy piggeldy)
Some comment to the post suggesting looking at the Google C++ guidelines. Detailed discussion about some aspects of these guidelines are posted at comp.lang.c++.moderated.
Some weird or controversial points include:
We don't believe that the available
alternatives to exceptions, such as
error codes and assertions, introduce
a significant burden.
As if assertions were a viable alternative... Assertions are usually for programming errors and situations that should never happen, while exceptions can happen (are somewhat anticipated) in the execution flow.
Reference Arguments: All parameters
passed by reference must be labeled
const. ... In fact it is a very strong
convention that input arguments are
values or const references while
output arguments are pointers.
No comment, about weasel phrase a very strong convention.
Doing Work in Constructors: Do only
trivial initialization in a
constructor. If at all possible, use
an Init() method for non-trivial
initialization.  ... If your object
requires non-trivial initialization,
consider having an explicit Init()
method and/or adding a member flag
that indicates whether the object was
successfully initialized.
Yes... 2-phase init to make things simpler... What if I have const fields? This rule is probably the effect of attitude towards exceptions.
Use streams only for logging
Which streams? IOStreams, standard C streams, other?
On one hand they advise to use macros only in exceptional situations, while they recommend using DISALLOW_COPY_AND_ASSIGN to prohibit copy/assign. They could have advised the approach with special class (like in Boost)
Do not overload operators except in rare, special circumstances.
What about assignment, or arithmetic operators for numeric calculations, etc?
Default parameters are more difficult to maintain because copy-and-
paste from previous code may not reveal all the parameters. Copy-and-
pasting of code segments can cause major problems when the default
arguments are not appropriate for the new code.
The what? Copy/paste from previous code?
Remember that reading any of the guidelines can introduce a bias to your way of thinking. And sometimes it won't be beneficial for you or your code. I agree with some other posts advising reading good books by good authors beforehand. When you have sufficient amount of knowledge, then you are able to look at the guidelines and find good and weak points easily, without creating a mess in your brain ;)
If you plan to introduce a code-formatting standard to an existing programming team, get input from each member of the team so they'll have "buy in" and be more likely to write code to that standard.
Programming styles are as difficult to change as habits, and you'll have to accept that some people won't make their code 100% compliant 100% of the time. It would be worth your time to find (or write your own) pretty-printer program and periodically run all your code through it to enforce consistency. (I always felt uneasy when manually checking in source code changes that only consisted of formatting corrections for other peoples' code; I worried that others would label me a nitpicker.)
Sun Java Code Conventions
Python Style Guide
Zend Coding Standard for PHP
Having asked this question. I found that the accepted answer proved to be sufficient for my needs.
However, I realise that this is not a 'one-size-fits-all' scenario, so there is a large quantity of information within the thread that you may find more or less useful. Weel worth a read!
For Java and other C-family languages I recommend Sofware Monkey's coding standards (of course, since they're mine).
In general, keep them simple, and provide examples and justification for every requirement.
What's in the standard doesn't really matter all that much. What matters is that you have one, and that your developers follow it.
It doesn't quite answer the question, but it's worth a mention...
I read Steve McConnell's Code Complete. Whilst it doesn't give you a pre-baked set of coding standards it does set out a lot of good arguments for the various approaches. It'll make you think about things you'd not thought of before.
It changed my little world for the better.
Coding standards themselves are great and all, but what I think is much, much, MUCH more important is keeping with the style of whatever code you're maintaining. I've seen people add a function to some class written one way and forcing their coding standard on just that function. It's inconsistent, it sticks out, and, in my opinion, it makes it harder to enjoy the class "as a whole".
Whenever you're maintaining code, look at the code around it. See what the style is. K&R braces? Capital Camel Case methods? Hungarian? Double-line comment blocks between every function? Whatever it is, you should do it too in that specific area.
Before I leave, one thing I'd like to note that's related - naming files. I'm mainly a C++ guy, so this may not apply to whatever else, but basically it goes _.h or .cpp. So, Foo::Bar would be in Foo_Bar.h. Common things (i.e. a precompiled header) for the Foo namespace would be in Foo_common.h (note the lowercase common). Of course, that's a taste thing, but everybody who has worked with this has come out in favor of this.
i think Code Craft - The Practice of Writing Excellent Code pretty much sums it all up
Very popular are Ellemtel rules for C++.
For C# I recommend Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition) (Microsoft .NET Development Series).
Mono Coding Guidelines
The answers here a pretty complete, thus I am not pointing to another coding standard document. However, once you decided to stick to one style you should use an automated coding style enforcer throughout your team.
For Java there is checkstyle and for .NET Microsoft Style Cop.
Here is a similar discussion on Stackoverflow: C# Coding standard / Best practices
Camel and pascal casing alone solves a lot of coding standard problems

Categories

Resources