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.
Related
If it is possible to auto-format code before and after a source control commit, checkout, diff, etc. does a company really need a standard code style?
It feels like standard coding style debates that have been raging since programming began like "put the bracket on the following line" or "properly indent your (" are no longer essential.
I realize in languages where white space matters the diff will have to consider it but for languages where the style is a personal preference is there really a need to worry about it anymore?
Auto-format can really only address whitespace.
It wont address developers giving variables bizarre nonsensical names.
It won't address some developers having functions return null on an error vs throwing an exception.
I'm sure others can think of more examples.
This is what we do at my work:
We all use Eclipse. We don't have a policy for using Eclipse but somehow none of us is an IDEA/IntelliJ guy. We also think our code should be written with legacy in mind. This means our code has to be readable in a certain way even years after (#1) no matter who wrote it and if that person even is in the company anymore.
Eclipse has couple handy features, automatic format on save and a specific Formatter tool. As you can see from the linked screenshot, it can be configured with XML. Thus there's a bunch of premade XML:s available for every worker in our company so that when a new guy comes in, we walk him through of the whole process and configure their Eclipse for them (yes, it's slightly evil thing to do) so that it actually uses those formatting XML:s we have provided. We do not enforce automatic format on save, we don't want to be completely intrusive, we just want to push all our developers into the right directions. For even increased compatability, we mostly use rules defined in JCC.
Next comes the important part, the actual builds. We are those who embrace automatic builds and for that we use Hudson Continuous Integration Server. There's two important parts in our configurations beyond this:
We use CVS loginfo to trigger builds whenever something is committed.
We utilize several plugins available for Hudson, including Continuous Integration Game in conjuction with the most important one, Checkstyle.
The Checkstyle Plugin is the magician in our code style enforcement guide line:
After commiting code to CVS, Hudson build is triggered
After build has been completed succesfully (all unit tests pass etc.), Checkstyle inspects the actual source files
Checkstyle ranks the code based rules we have defined for it
Continuous Integration Game sees the result of Checkstyle and awards/takes away points for the person who has the ownership for the relevant part of the code
Leaderboard shows total points for every commiter in system
Basically this means that when anyone commits ugly code into our CVS, our build server automatically reduces that person's points.
This means that eventually any one of us can be ranked on the Leaderboard based on the general code quality in both look and OO principles such as Law of Demeter, Cyclomatic complexity etc. etc. Naturally this isn't a completely serious statistic, but it's a good indication you're doing something wrong when causing a build to be initiated in our CI won't reduce your points - most of our commits are worth between 1 and 5 points.
And is it working? Sort of, I don't think anyone of us at my work writes ugly or unmaintainable code and personally I love to hunt all kinds of scores so it's definitely motivating me to make code that looks nice and follows all the OO paradigms I know of.
And do we as a company really need it? I think we do as you should see from reading this entire answer, it can be considered a good practice for the advancements it brings.
#1: in a related note, I refactored legacy code from 2002 today which used those standards, didn't look "bad" at all even in its original form and certainly not worse in its new form
No, not really.
If you can actually get it to work consistently and not make it flag code has changed due to a different style of laying the code out.
However, this is just a small part of coding standards. It won't cover multiple return statements, the use or not of ternary operators, etc.
It is always nice if the coding style that the shop uses is the same one that is also followed by the development tools.
Otherwise, if there is a large body of code that already follows a shop standard which is NOT the same as that of the tools you have two choices:
Modify all of the code to follow the tool standard, or
Maintain the existing shop standard.
Many shops do the latter. Regardless, there does need to be some kind of standard, and it does need to be followed.
Some development tools allow you to tweak their standard. In some cases you may be able to bring the tools in alignment with the shop standard.
It probably doesn't matter that much anymore if you can ensure that everybody in the team sees the source code "correctly" formatted, whatever they think it is. However I've not seen a system that can do that - you can do parts of it (say, reformat before and after checkin/checkout) but these days you also have to consider web interfaces into the version control, external code review systems that interact directly with the version control system etc.
The main purpose of a standard code style is (IMHO) to ensure that you can read other team members' code easily without having to start reverse engineering it because all the code is written using the same sort of guiding principles. Indenting and parentheses placement seem to be a major hangup on this but they are only a very small and in my opinion, somewhat overblown and not very important part of the need to make code consistent.
Unfortunately I'm not aware of any tools that can automatically apply consistent coding principles to source code...
Yes, coding styles are needed if there is a desire to have a homogeneous code base. Such a code base can be useful in preventing individual ownership of parts of the code base, which can cause problems when people leave the team. If you can't imagine having wildly different styles and problems understanding all of it, just look at all the different ways English text can be organized in various communications, all written but quite different such as tweets, e-mail, text messages, IM, message board posts, etc. and changes in fonts, capitalization, decorations, etc.
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 ;)
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.
Since yesterday, I am analyzing one of our project with Ndepend (free for most of its features) and more I am using it, and more I have doubt about the real value of this type of software (code-analysis software).
Let me explain, The system build a report about the health of the system and class by Rank every metric. I thought it would be a good starting point to do modifications but most of the top result are here because they have over 100 lines inside the class (we have big headers and we do use VS comments styles) so it's not a big deal... than the number of Afferent Coupling level (CA) is always too high and this is almost very true for Interface that we used a lot... so at this moment I do not see something wrong but NDepend seem to do not like it (if you have suggestion to improve that tell me because I do not see the need for). It's the samething for the metric called "NOC" for Number of children that most of my Interface are too high...
For the moment, the only very useful metric is the Cyclomatic Complexity...
My question is : Do you find is worth it to analyse code with Automatic Code Analyser like NDepend? If yes, how do you filter all information that I have mentionned that doesn't really show the real health of the system?
Actually metrics are just one feature of NDepend, did you try to use VisualNDepend that lets you analyze your project much more in depth than the report? By reading your comment, I am almost sure you didn't play with NDepend UI (standalone or integrated in Visual Studio) which is the best way to filter data about your code base.
I am one of the developers of NDepend and we use it a lot to analyze our own code. Basically we write our own quality rules with Code Rules over LINQ Queries (CQLinq). These rules automatically make sure that we don't have regression on our design. Here you'll find the list of around 200 default code rules.
Here are some unique features of NDepend and not related to code metrics:
Write CQLinq rules to make sure we don't have architectural flaws, such as dependency cycles between our components, UI using directly the DB or DB entangled with the business objects.
Make sure we don't have problem with code coverage by tests (like we make sure with a CQLinq rule that if a class is supposed to be 100% covered, it will remain 100% covered in the future)
Enforce side-effects-free code (immutable class/pure methods)
Use the ability to compare 2 analysis to code review changes since the last release, before doing a new release. More specifically, I enjoy using NDepend to know which method has been added and refactored since the last release, and is not 100% covered by tests.
Having an optimal encapsulation for all our members and types (like knowing which internal methods can be declared as private). This is also related to dead-code detection that NDepend also supports.
For a complete list of features if NDepend, see here.
I don't necessarily see NDepend results as "good" or "bad" in software engineering, there's always a good reason why an application is designed the way it is. I see it as a report that can probably help me point out issues with my design, but I have the final word when it comes to deciding if a method needs to be refactored or if it's good the way I designed it. In general, don't get too caught up trying to answer if it's worth it or not. It definitely is, instead I would suggest you carefully review the results. This will help you view your design from another perspective and there may be occasions where you decide the way you designed it is the best to achieve your applications goals.
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