Posts Tagged ‘coding standards’

How to Increase Software Developer Productivity

March 2, 2013

Is your organisation:

  • Wanting to get more out of your Software Developers?
  • Wanting to increase RoI?
  • Spending too much money fixing bugs?
  • Development team not releasing business value fast enough?
  • Maybe your a software developer and you want to lift your game to the next level?

If any of these points are of concern to you… read on.

There are many things we can do to lift a software developers productivity and thus the total output of The Development Team. I’m going to address some quick and cheap wins, followed by items that may take a little longer to implement, but non the less, will in many cases provide even greater results.

What ever it takes to remove friction and empower your software developers to work with the least amount of interruptions, do it.
Allow them to create a space that they love working in. I know when I work from home my days are far more productive than when working for a company that insists on cramming as many workers around you into a small space as possible. Chitter chatter from behind, both sides and in front of you will not help one get their mind into a state of deep thought easily.

I have included thoughts from Nicholas C. Zakas post to re-iterate the common fallacies uttered by non-engineers.

  • I don’t understand why this is such a big deal. Isn’t it just a few lines of code? (Technically, everything is a few lines of code. That doesn’t make it easy or simple.)
  • {insert name here} says it can be done in a couple of days. (That’s because {insert name here} already has perfect knowledge of the solution. I don’t, I need to learn it first.)
  • What can we do to make this go faster? Do you need more engineers? (Throwing more engineers at a problem frequently makes it worse. The only way to get something built faster is to build a smaller thing.)

Screen real estate

When writing code, a software developers work requires a lot of time spent deep in thought. Holding multiple layers of complexity within immediately accessible memory.
One of the big wins I’ve found that helps with continuity, is maximising your screen real estate.
I’ve now moved up to 3 x 27″ 2560×1440 IPS flat panels. These are absolutely gorgeous to look at/work with.
Software development generally requires a large number of applications to be running at any one time.
For example in any average session for me, I generally have somewhere around 30 windows open.
The more screen real estate a developer has, the less he/she has to fossick around for what he/she needs and switch between them.
Also, the less brain cycles he/she has to spend locating that next running application, means the more cycles you have in order to do real work.
So, the less gap there is switching between say one code editor and another, the easier it is for a developer to keep the big picture in memory.
We’re looking at:

  1. physical screen size
  2. total pixel count

The greater real estate available (physical screen size and pixel count) the more information you can have instant access to, which means:

  • less waiting
  • less memory loss
  • less time spent rebuilding structures in your head
  • greater continuity

Which then gives your organisation and developers:

  • greater productivity
  • greater RoI

These screens are cheaper than many realise. I set these up 4 months ago. They continue to drop in price.

  1. FSM-270YG 27″ PC Monitor LED S-IPS WIDE 2560×1440 16:9 WQHD DVI-D $470.98 NZD
  2. [QH270-IPSMS] Achieva ShiMian HDMI DVI D-Sub 27″ LG LED 2560×1440 $565.05 NZD
  3. [QH270-IPSMS] Achieva ShiMian HDMI DVI D-Sub 27″ LG LED 2560×1440 $565.05 NZD

It’s just simply not worth not to upgrading to these types of panels.

korean monitors

In this setup, I’m running Linux Mint Maya. Besides the IPS panels, I’m using the following hardware.

  • Video card: 1 x Gigabyte GV-N650OC-2GI GTX 650 PCIE
  • PSU: 1200w Corsair AX1200 (Corsair AX means no more PSU troubles (7 yr warranty))
  • CPU: Intel Core i7 3820 3.60GHz (2011)
  • Mobo: Asus P9X79
  • HDD: 1TB Western Digital WD10EZEX Caviar Blue
  • RAM: Corsair 16GB (2x8GB) Vengeance Performance Memory Module DDR3 1600MHz

One of the ShiMian panels is using the VGA port on the video card as the FSM-270YG only supports DVI.
The other ShiMian and the FSM-270YG are hooked up to the 2 DVI-D (dual link) ports on the video card. The two panels feeding on the dual link are obviously a lot clearer than the panel feeding on the VGA. Also I can reduce the size of the text considerably giving me greater clarity while reading, while enabling me to fit a lot more information on the screens.

With this development box, I’m never left waiting for the machine to catchup with my thought process.
So don’t skimp on hardware. It just doesn’t make sense any way you look at it.

Machine Speed

The same goes for your machine speed. If you have to wait for your machine to do what you’ve commanded it to do and at the same time try and keep a complex application structure in your head, the likelihood of loosing part of that picture increases. Plus your brain has to work harder to hold the image in memory while your trying to maintain continuity of thought. Again using precious cycles for something that shouldn’t be required rather than on the essential work. When a developer looses part of this picture, they have to rebuild it again when the machine finishes executing the last command given. This is re-work that should not be necessary.

An interesting observation from Joel Spolsky:

“The longer it takes to task switch, the bigger the penalty you pay for multitasking.
OK, back to the more interesting topic of managing humans, not CPUs. The trick here is that when you manage programmers, specifically, task switches take a really, really, really long time. That’s because programming is the kind of task where you have to keep a lot of things in your head at once. The more things you remember at once, the more productive you are at programming. A programmer coding at full throttle is keeping zillions of things in their head at once: everything from names of variables, data structures, important APIs, the names of utility functions that they wrote and call a lot, even the name of the subdirectory where they store their source code. If you send that programmer to Crete for a three week vacation, they will forget it all. The human brain seems to move it out of short-term RAM and swaps it out onto a backup tape where it takes forever to retrieve.”

Many of my posts so far have been focused on productivity enhancements. Essentially increasing RoI. This list will continue to grow.

Coding Standards and Guidelines

Agreeing on a set of Coding Standards and Guidelines and policing them (generally by way of code reviews and check-in commit scripts) means software developers get to spend less time thinking about things that they don’t need to and get to throw more time at the real problems.

For example:

Better Tooling

Improving tool sets has huge gains in productivity. In most cases many of the best tools are free. Moving from the likes of non distributed source control systems to best of bread distributed.

There are many more that should be considered.

Wiki

Implementing an excellent Wiki that is easy to use. I’ve put a few wiki’s in place now and have used even more. My current pick of the bunch would have to be Atlassians Confluence. I’ve installed this on a local server and also migrated the instance to their cloud. There are varying plans and all very reasonably priced with excellent support. If the wiki you’re planning on using is not as intuitive as it could be, developers just wont use it. So don’t settle for anything less.

Improving Processes

Code Reviews

Also a very important step in all successful development teams and often a discipline that must be satisfied as part of Scrums Definition of Done (DoD). What this gives us is high quality designs and code, conforming to the coding standards. This reduces defects, duplicate code (DRY) and enforces easily readable code as the reviewer has to understand it. Saves a lot of money in re-work.

Cost of Change

Scott Amblers Cost of change curve

Definition of Done (DoD)

Get The Team together and decide on what it means to have each Product Backlog Item that’s pulled into the Sprint Done.
Here’s an example of a DoD that one of my previous Development Teams compiled:

Definition of Done

What does Done actually mean?

Come Sprint Review on the last day of the Sprint, everyone knows what it means to be done. There is no “well I thought it was Done because I’ve written the code for it, but it’s not tested yet”.

Continuous Integration (CI)

There are many tools and ways to implement CI. What does CI give you? Visibility of code quality, adherence to standards, reports on cyclomatic complexity, predictability and quite a number of other positive side effects. You’ll know as soon as the code fails to build and/or your fast running tests (unit tests) fail. This means The Development Team don’t keep writing code on top of faulty code, thus reducing technical debt by not having to undo changes on changes later down the track.
I’ve used a number of these tools and have carried out extensive research and evaluation spikes on a number of the most popular offerings. In order of preference, the following are my candidates.

  1. Jenkins (free and open source, with a great community)
  2. TeamCity
  3. Atlassian Bamboo

Release Plans

Make sure you have these. This will reduce confusion and provide a clear definition of the steps involved to get your software out the door. This will reduce the likelihood of screwing up a release and re-work being required. You’ll definitely need one of these for the next item.

Here’s an example of a release notes guideline I wrote for one of the previous companies I worked for.

release notes

Continuous Deployment

If using Scrum, The Scrum Team will be forecasting a potentially releasable Increment (the sum of all the Product Backlog items completed during a Sprint and all previous Sprints).
You may decide to actually release this. When you do, you can look at the possibility of automating this deployment. Thus reducing the workload of the release manager or who ever usually deploys (often The Development Team in a Scrum environment). This has the added benefit of consistency, predictability, reliability and of course happy customers. I’ve also been through this process of research and evaluation on the tools available and the techniques to implement.

Here’s a good podcast that got me started. I’ve got a collection of other resources if you need them and can offer you my experience in this process. Just leave a comment.

Implement Scrum (and not the Flaccid flavour)

I hope this goes without saying?
Implementing Scrum to provide ultimate visibility

Get maximum quality out of the least money spent

How to get the most out of your limited QA budget

Driving your designs with tests, thus creating maintainable code, thus reducing technical debt.

Hold Retrospectives

Scrum is big on continual inspection and adaption, self-organisation and fostering innovation. The military have another term for inspection and adaption. It’s called the OODA Loop.
The Retrospective is just one of the Scrum Events that enable The Scrum Team to continually inspect the way they are doing things and improve the way they develop and deliver business value.

Invest a little into your servant leaders

Empowering the servant leaders.

Context Switching

Don’t do it. This is a real killer.
This is hard. What you need to do is be aware of how much productivity is killed with each switch. Then do everything in your power to make sure your Development Team is sheltered from as much as possible. There are many ways to do this. For starters, you’re going to need as much visibility as possible into how much this is currently happening. track add-hock requests and any other types of interruptions that steel the developers concentration. In the last Scrum Team that I was Scrum Master of, The Development Team decided to include another metric to the burn down chart that was on the middle of the wall, clearly visible to all. Every time one of the developers was interrupted during a Sprint, they would record this time, the reason and who interrupted them, on the burn down chart. The Scrum Team would then address this during the Retrospective and empirically address why this happened and work out how to stop it happening every Sprint. Jeff Atwood has an informative post on why and how context-switching/multitasking kills productivity. Be sure to check it out.

As always, if anything I’ve mentioned isn’t completely clear, or you have any questions, please leave a comment 🙂

Advertisements

Generic Coding Standards and Guidelines

January 5, 2013

Merging Conventions to Aid Readability thus Reducing Development Time

When programming in a mixed-language environment,
the naming conventions, formatting conventions, documentation conventions, and other conventions,
can be optimised for overall consistency and readability.
This may mean going against convention for one or more of the languages that’s part of the mix.

For Example…

in many classical Object Oriented and procedural languages,
routine names have an initial capital letter (PascalCase).
The convention in JavaScript is for routine names to have an initial lower case letter (camelCase),
unless the routine is a constructor (intended to be used with the new prefix).
When a constructor is invoked without the new prefix,
the constructors this will be bound to the global object,
rather than where it should be…
The functions execution context.
When invoked with the new prefix as it should be,
the function object will be created with a hidden link to the value of the functions prototype,
and the functions this value will be bound to the function object (where it should be).
Because this convention has a very important reason,
your team may decide to carry that convention across the other languages you use.

Refactor or Document Short, Hard to Read Names

I don’t know how many times I see code that uses very short names which make readability difficult.
What’s worse, is that so often there are many different names that mean the same thing sprinkled across the project/s.
Short, hard to read, pronounce, or understand names are rarely needed with the programming languages of today.
Use easily and quickly readable names where ever possible.
If you have to use short names or abbreviations, keep them consistent.
Translation tables are good for this.
You can have a commented translation table at the beginning of a file,
or at the project level if the names are wider spread.
Names should be specific to the domain your working in, rather than to the programming language.

Meaningful Loop Index Names

If your loop is more than a couple of lines long or you have nested loops,
make your loop index name something meaningful,
rather than i, j, k etc.

Additional Thoughts

  • Code is read many more times than it is written.
    Make sure the names you choose favour read-time over write-time convenience.
  • If you have names that are general or vague enough to be used for multiple purposes,
    refactor your code, maybe create additional entities that have more specific names.
  • Don’t leave the meaning of the name to guess work.
    This taxes the programmers mind unnecessarily.
    There are better uses of our cycles.
  • Agree on and adopt a set of coding standards and guidelines.
    It’s more important to have standards than to not have them because you can’t agree on the “right” way.
    They will save wasted time and arguments during coding, and code reviewing.

JavaScript Coding Standards and Guidelines

December 19, 2012

This is the current set of coding standards and guidelines I use when I’m coding in the JavaScript language.
I thought it would be good to share so others could get use out of them also, and maybe start a discussion as to amendments / changes they see that could be useful?

Naming Conventions

Names should be formed from the 26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9), and _ (underbar).
Avoid use of international characters because they may not read well or be understood everywhere.
Do not use $ (dollar sign) or \ (backslash) in names.

I think jQuery would have to be an exception to this

Do not use _ (underbar) as the first character of a name.
It is sometimes used to indicate privacy, but it does not actually provide privacy.
If privacy is important, use the forms that provide private members.

Most variables and functions should start with a lower case letter.

Constructor functions which must be used with the new prefix should start with a capital letter.
JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted.
Bad things can happen if new is not used, so the capitalization convention is the only defence we have.

Global variables should be in all caps.
JavaScript does not have macros or constants, so there isn’t much point in using all caps to signify features that JavaScript doesn’t have.
Same with Enum names. There is no native ability to create constant variables. Although… you can create read-only properties.
With the advent of ES5 we now have a couple of well known techniques to enforce that our property values can not be altered once initialised.

When you define a property using one of the ES5 techniques, (1) when you set the writable property attribute to false the value of the value attribute can no longer be altered. (2) Using an accessor property with only a get function

var objWithMultipleProperties;
var objWithMultiplePropertiesDescriptor;

objWithMultipleProperties = Object.defineProperties({}, {
   x: { value: 1, writable: true, enumerable:true, configurable:true }, // Change writable to false enables read-only semantics.
   y: { value: 1, writable: true, enumerable:true, configurable:true }, // Change writable to false enables read-only semantics.
   r: {
      get: function() {
         return Math.sqrt(this.x*this.x + this.y*this.y)
      },
      enumerable:true,
      configurable:true
   }
});

objWithMultiplePropertiesDescriptor = Object.getOwnPropertyDescriptor(objWithMultipleProperties, 'r');
// objWithMultiplePropertiesDescriptor {
//    configurable: true,
//    enumerable: true,
//    get: function () {
//       // other members in here
//    },
//    set: undefined,
//   // ...
// }

See here for complete coverage of property attributes.

Coding Style

Commenting

Use comments where needed.

If the script needs commenting due to complexity, consider revising before commenting.
Comments easily rot (can be left behind after future code changes).
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
In this case they cause more damage than they originally gave benefit.
Comments should be well-written and clear, just like the code they are annotating.

Make comments meaningful. Focus on what is not immediately visible. Don’t waste the reader’s time with stuff like

i = 0; // Set i to zero.

Comment Style

Block comments are not safe for
commenting out blocks of code. For example:

/*
var rm_a = /a*/.match(s);
*/

causes a syntax error. So, it is recommended that /* */ comments be avoided and //
comments be used instead.

Don’t use HTML comments in script blocks. In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn’t have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn’t show it as text in the page. The ‘hack’ was to use HTML comments within the script block to hide the code.

<script language="javascript">
<!--
   // code here
   //-->
</script>

No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. Thanks Matt Kruse for re-iterating this.

File Organization

JavaScript programs should be stored in and delivered as .js files.

  • JavaScript should not be in HTML
  • JavaScript should not be in CSS
  • CSS should not be in JavaScript
  • HTML should not be in JavaScript

Code in HTML adds significantly to page weight with no opportunity for mitigation by caching and compression. There are many other reasons to keep the UI layers separate.

<script src=filename.js>; tags should be placed as late in the body as possible.
This reduces the effects of delays imposed by script loading on other page components.

There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.

Formatting

Bracing

Use same line opening brace.
Brace positioning is more or less a holy war without any right answer — except in JavaScript, where same-line braces are right and you should always use them. Here’s why:

return
{
  ok: false;
};

return {
  ok: true;
};

What’s the difference between these two snippets? Well, in the first one, you silently get something completely different than what you wanted.
The lone return gets mangled by the semicolon insertion process and becomes return; and returns nothing.
The rest of the code becomes a plain old block statement, with ok: becoming a label (of all things)! Having a label there might make sense in C, where you can goto, but in JavaScript, it makes no sense in this context.
And what happens to false? it gets evaluated and completely ignored.
Finally, the trailing semicolon — what about that?
Do we at least get a syntax error there? Nope: empty statement, like in C.

Spacing

Blank lines improve readability by setting off sections of code that are logically related.

Blank spaces should be used in the following circumstances:

  • A keyword followed by ( (left parenthesis) should be separated by a space.
    while (true) {
    
  • A blank space should not be used between a function value and its ( (left parenthesis). This helps to distinguish between keywords and function invocations.
  • All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
  • No space should separate a unary operator and its operand except when the operator is a word such as typeof.
  • Each ; (semicolon) in the control part of a for statement should be followed with a space.
  • Whitespace should follow every , (comma).

Tabs and Indenting

The unit of indentation is three spaces.
Use of tabs should be avoided because (as of this writing in the 21st Century) there still is not a standard for the placement of tab stops.
The use of spaces can produce a larger file size, but the size is not significant over local networks, and the difference is eliminated by minification.

Line Length

Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it.
Place the break after an operator, ideally after a comma.
A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.
The next line should be indented six spaces.

Language Usage

Access To Members

In JavaScript we don’t have access modifiers like we do in classical languages.

In saying that, we can and should still control the accessibility of our members, and keep as much of our objects information secret to outsiders.
We can apply public, private and Privileged access.

public

Members created in the Constructor using the dot notation

function Container(param) {
    this.member = param;
}

So, if we construct a new object

var myContainer = new Container('abc');

then myContainer.member contains 'abc'.

In the prototype we can add a public method.
To add a public method to all objects made by a constructor, add a function to the constructor’s prototype:

Container.prototype.stamp = function (string) {
    return this.member + string;
}

We can then invoke the method

myContainer.stamp('def')

which produces 'abcdef'.

private

Ordinary vars and parameters of the constructor becomes the private members

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

param, secret, and that are private member variables.
They are not accessible to the outside.
They are not even accessible to the objects own public methods.

They are accessible to private methods
Private methods are inner functions of the constructor.

function Container(param) {

    this.member = param; // param is private, member is public
    var secret = 3;      // secret is private
    var that = this;     // that is private
    function dec() {     // dec is private
        var innerFunction = function () {
            that.value = someCrazyValue;  // when dec is called, value will be a member of the newly constructed Container instance.
        };

        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }
}

A method (which is a function that belongs to an object) cannot employ an inner function to help it do its work because the inner function does not
share the method’s access to the object as its this is bound to the global object. This was a mistake in the design of the language.
Had the language been designed correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function.
The work around for this is to define a variable and assign it the value of this.
By convention, the name of that variable I use is that.

  • Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
privileged

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Privileged methods are assigned with this within the constructor.

function Container(param) {

    this.member = param;
    var secret = 3;
    var that = this;

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.service = function () { // prefix with this to assign a function to be a privileged method
        if (dec()) {
            return that.member;
        } else {
            return null;
        }
    };
}

service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null. service calls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

eval is Evil

The eval function is the most misused feature of JavaScript. Avoid it.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.

Global Abatement

JavaScript makes it easy to define global variables that can hold all of the assets of your application.
Unfortunately, global variables weaken the resiliency of programs and should be avoided.

One way to minimize the use of global variables is to create a single global variable
for your application:

var KimsGlobal = {};

That variable then becomes the container for your application:

KimsGlobal.Calculate = {
    calculatorOutPutArray: [
    $('.step1i1'),
    $('.step1i2'),
    $('.step1r1'),
    ...
    ],
    jQueryObjectCounter: 0,
    jQueryDOMElementCounter: 0
    ...
};

KimsGlobal.NavigateCalculator = {
    currentStepId: stepId,
    step: 'step' + stepId,
    stepSelector: = '#' + step,
    ...
};

By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.
Your program also becomes easier to read because it is obvious that KimsGlobal.Calculate refers to a top-level structure.

Using closure for information hiding is another effective global abatement technique.

var digit_name = (function() {
  var names = ['zero', 'one', 'two', ...];
  return function (n) {
    return names[n];
  };
})();

Using the Module patterns explains this in detail.

Scoping

JavaScript scoping is different to classical languages, and can take some getting used to for programmers used to languages such as C, C++, C#, Java.
Classical languages like the before mentioned have block scope.
JavaScript has function scope. Although ES6 is bringing in block scoping with the let keyword.

In the following example “10” will be alerted.
var foo = 1; // foo is defined in global scope.
function bar() {
    if (!foo) { // The foo variable of the bar scope has been hoisted directly above this if statement, but the assignment has not. So it is unassigned (undefined).
        var foo = 10;
    }
    alert(foo);
}
bar();
In the following example “1” will be alerted.
var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);
In the following example Firebug will show 1, 2, 2.
var x = 1;
console.log(x); // 1
if (true) {
    var x = 2;
    console.log(x); // 2
}
console.log(x); // 2

In JavaScript, blocks such as if statements, do not create new scope. Only functions create new scope.

There is a workaround though 😉
JavaScript has Closure.
If you need to create a temporary scope within a function, do the following.

function foo() {
    var x = 1;
    if (x) {
        (function () {
            var x = 2;
            // some other code
        }());
    }
    // x is still 1.
}

Line 3: begins a closure
Line 6: the closure invokes itself with ()

Hoisting

Terminology

function declaration or function statement are the same thing.
function expression or variable declaration with function assignment are the same thing.

A function statement looks like the following:

function foo( ) {}

A function expression looks like the following:

var foo = function foo( ) {};

A function expression must not start with the word “function”.

//anonymous function expression
var a = function () {
    return 3;
}

//named function expression
var a = function bar() {
    return 3;
}

//self invoking named function expression. This is also a closure
(function sayHello() {
    alert('hello!');
})();

//self invoking anonymous function expression. This is also a closure
(function ( ) {
    var hidden_variable;
    // This function can have some impact on
    // the environment, but introduces no new
    // global variables.
}() );

In JavaScript, a name enters a scope in one of four basic ways:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. Variable declarations: These take the form var foo;.

Function declarations and variable declarations are always hoisted invisibly to the top of their containing scope by the JavaScript interpreter.
Function parameters and language-defined names are, obviously, already there. This means that code like this:

function foo() {
    bar();
    var x = 1;
}

Is actually interpreted like this:

function foo() {
    var x;
    bar();
    x = 1;
}

It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:

function foo() {
    if (false) {
        var x = 1;
    }
    return;
    var y = 1;
}
function foo() {
    var x, y;
    if (false) {
        x = 1;
    }
    return;
    y = 1;
}

The assignment portion of the declaration is not hoisted.
Only the identifier is hoisted.
This is not the case with function declarations, where the entire function body will be hoisted as well,
but remember that there are two normal ways to declare functions. Consider the following JavaScript:

function test() {
    foo(); // TypeError 'foo is not a function'
    bar(); // 'this will run!'
    var foo = function () { // function expression assigned to local variable 'foo'
        alert('this won't run!');
    }
    function bar() { // function declaration, given the name 'bar'
        alert('this will run!');
    }
}
test();

In this case, only the function declaration has its body hoisted to the top. The name ‘foo’ is hoisted, but the body is left behind, to be assigned during execution.

Name Resolution Order

The most important special case to keep in mind is name resolution order. Remember that there are four ways for names to enter a given scope. The order I listed them above is the order they are resolved in. In general, if a name has already been defined, it is never overridden by another property of the same name. This means that a function declaration takes priority over a variable declaration. This does not mean that an assignment to that name will not work, just that the declaration portion will be ignored. There are a few exceptions:

  • The built-in name arguments behaves oddly. It seems to be declared following the formal parameters, but before function declarations. This means that a formal parameter with the name arguments will take precedence over the built-in, even if it is undefined. This is a bad feature. Don’t use the name arguments as a formal parameter.
  • Trying to use the name this as an identifier anywhere will cause a Syntax Error. This is a good feature.
  • If multiple formal parameters have the same name, the one occurring latest in the list will take precedence, even if it is undefined.

Additional hoisting examples on my blog

Now that you understand scoping and hoisting, what does that mean for coding in JavaScript?
The most important thing is to always declare your variables with var statements.
Declare your variables at the top of the scope (as already mentioned JavaScript only has function scope). See the Variable Declarations section.
If you force yourself to do this, you will never have hoisting-related confusion.
However, doing this can make it hard to keep track of which variables have actually been declared in the current scope.
I recommend using strict mode which will inform you if you have tried to use a variable without declaring it with var. If you’ve done all of this, your code should look something like this:

function foo(a, b, c) {
    'use strict';
    var x = 1;
    var bar;
    var baz = 'something';
    // other non hoistable code here
}

Inheritance

Always prefer Prototypal inheritance to Pseudo classical.

There are quite a few reasons why we shouldn’t use Pseudo classical inheritance in JavaScript.
JavaScript The Good Parts explains why.

In a purely prototypal pattern, we dispense with classes.
We focus instead on the objects.
Prototypal inheritance is conceptually simpler than classical inheritance.

I’ll show you three examples of prototypal inheritance, and explain the flaws and why the third attempt is the better way.

Example 1
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

The object function takes an existing object as a parameter and returns an empty new object that inherits from the old one.
The problem with the object function is that it is global, and globals are clearly problematic.

Example 2
Object.prototype.begetObject = function () {
    function F() {}
    F.prototype = this;
    return new F();
};

newObject = oldObject.begetObject();

The problem with Object.prototype.begetObject is that it trips up incompetent programs, and it can produce unexpected results when begetObject is overridden.

Example 3
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

Example 3 overcomes the problems with the previous prototypical examples.
This is how Object.create works in ES5

New

Use {} instead of new Object(). Use [] instead of new Array(). There are instances where using new allows compiler optimisations to be performed. Learn what happens when you use new in different scenarios and test.

Operators

Plus Minus

Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your intention clear.

total = subtotal + +myInput.value;

is better written as

total = subtotal + (+myInput.value);

so that the + + is not misread as ++.

Equality
By default use the === operator rather than the == operator.
By default use the !== operator rather than the != operator.

JavaScript has two sets of equality operators: === and !==, and their (as Douglas Crockford puts it) evil twins == and
!=. The === and !== ones work the way you would expect. If the two operands are of the
same type and have the same value, then === produces true and !== produces false.
The other ones do the right thing when the operands are of the same type, but if they
are of different types, they attempt to coerce the values.
Make sure this is what you need rather than just blindly using the shorter form.
These are some of the interesting cases:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true
false == 'false'   // false
false == '0'       // true
false == undefined // false
false == null      // false
null == undefined  // true
' \t\r\n ' == 0    // true

Patterns

Module

Module presents an interface but hides its state and implementation.
Takes advantage of function scope and closure to create relationships that are binding and private.
Eliminate the use of global variables. It promotes information hiding and other good design practices.

Global Import

JavaScript has a feature known as implied globals.
Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name.
If none is found, that variable is assumed to be global.
If it’s used in an assignment, the global is created if it doesn’t already exist.
This means that using or creating global variables in an anonymous closure is easy.
Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative.
By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.

(function ($, YAHOO) {
    // now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));
Module Export

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value.

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

Notice that we’ve declared a global module named MODULE, with two public properties:
a method named MODULE.moduleMethodand a variable named MODULE.moduleProperty.
In addition, it maintains private internal state using the closure of the anonymous function.
Also, we can easily import needed globals, using the pattern we learned above.

Augmentation

One limitation of the module pattern so far is that the entire module must be in one file.
Anyone who has worked in a large code-base understands the value of splitting among multiple files.
Luckily, we have a nice solution to augment modules.
First, we import the module, then we add properties, then we export it.
Here’s an example, augmenting our MODULE from above:

var MODULE = (function (my) {
    my.anotherMethod = function () {
        // added method...
    };

    return my;
}(MODULE));

Use the var keyword again.
After this code has run, our module will have gained a new public method named MODULE.anotherMethod.
This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn’t always necessary.
One of the best things a JavaScript application can do for performance is to load scripts asynchronously.
We can create flexible multi-part modules that can load themselves in any order with loose augmentation.
Each file should have the following structure:

var MODULE = (function (my) {
    // add capabilities...

    return my;
}(MODULE || {}));

The import will create the module if it doesn’t already exist.
This means you can use a library like require.js and load all of your module files in parallel, without needing to block.
preferably not more than 2 to 3 at a time, else performance will degrade

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module.
Most importantly, you cannot override module properties safely.
You also cannot use module properties from other files during initialization (but you can at run-time after intialization).
Tight augmentation implies a set loading order, but allows overrides.
Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) {
    var old_moduleMethod = my.moduleMethod;

    my.moduleMethod = function () {
        // method override, has access to old through old_moduleMethod...
    };

    return my;
}(MODULE));

Here we’ve overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance
var MODULE_TWO = (function (old) {
    var my = {},
    var key;

    for (key in old) {
        if (old.hasOwnProperty(key)) {
            my[key] = old[key];
        }
    }

    var super_moduleMethod = old.moduleMethod;
    my.moduleMethod = function () {
        // override method on the clone, access to super through super_moduleMethod
    };

    return my;
}(MODULE));

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility.
As I’ve written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references.
Changing one will change the other.
This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval.

Sub-modules
MODULE.sub = (function () {
    var my = {};
    // ...

    return my;
}());

Statements

Simple Statements

Each line should contain at most one statement.
Put a ; (semicolon) at the end of every simple statement.
Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.

JavaScript allows any expression to be used as a statement.
This can mask some errors, particularly in the presence of semicolon insertion.
The only expressions that should be used as statements are assignments and invocations.

Compound Statements

Compound statements are statements that contain lists of statements enclosed in { } (curly braces).

  • The enclosed statements should be indented four more spaces.
  • The { (left curly brace) should be at the end of the line that begins the compound statement.
  • The } (right curly brace) should begin a line and be indented to align with the beginning of the line containing the matching { (left curly brace).
  • Braces should be used around all statements, even single statements, when they are part of a control structure, such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.
Labels
Say no to labelling Statement labels are optional. Only these statements should be labelled: while, do, for, switch. Or better still don’t use labelling.
return Statement

A return statement with a value should not use ( ) (parentheses) around the value.
The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion.

if Statement

The if class of statements should have the following form:

if (condition) {
    statements
}

if (condition) {
    statements
} else {
    statements
}

if (condition) {
    statements
} else if (condition) {
    statements
} else {
    statements
}

Avoid doing assignments in the condition part of if and while statements.

Is

if (a = b) {

a correct statement? Or was

if (a === b) {

intended? Avoid constructs that cannot easily be determined to be correct.

Also see the Equality section

for Statement

A for class of statements should have the following form:

for (initialisation; condition; update) {
    statements
}

for (variable in object) {
    if (filter) {
        statements
    }
}

The first form should be used with arrays and with loops of a predetermined number of iterations.

The second form should be used with objects.
Be aware that members that are added to the prototype of the object will be included in the enumeration.
It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
    if (object.hasOwnProperty(variable)) {
        statements
    }
}
while Statement

A while statement should have the following form:

while (condition) {
    statements
}
do Statement

A do statement should have the following form:

do {
    statements
} while (condition);

Unlike the other compound statements, the do statement always ends with a ; (semicolon).

switch Statement

A switch statement should have the following form:

switch (expression) {
case expression:
    statements
default:
    statements
}

Each case is aligned with the switch. This avoids over-indentation.
Each group of statements (except the default) should end with break, return, or throw. Do not fall through.

Or better, use the following form from Angus Crolls blog post

Procedural way to do the construct

var whatToBring;
switch(weather) {
    case 'Sunny':
        whatToBring = 'Sunscreen and hat';
        break;
    case 'Rain':
        whatToBring  ='Umbrella and boots';
        break;
    case 'Cold':
        whatToBring = 'Scarf and Gloves';
        break;
    default : whatToBring = 'Play it by ear';
}

OO way to do the construct

var whatToBring = {
    'Sunny' : 'Sunscreen and hat',
    'Rain' : 'Umbrella and boots',
    'Cold' : 'Scarf and Gloves',
    'Default' : 'Play it by ear'
}

var gear = whatToBring[weather] || whatToBring['Default'];
try Statement

The try class of statements should have the following form:

try {
    statements
} catch (variable) {
    statements
}

try {
    statements
} catch (variable) {
    statements
} finally {
    statements
}
continue Statement

Avoid use of the continue statement. It tends to obscure the control flow of the function.

with Statement

Why it shouldn’t be used.

Why it should be used.

with statement Both points are valid. Understand how it works before you use it. It aint going to work with strict mode anyway, for good reason IMHO.

Function Declarations

  • All functions should be declared before they are used.
  • Inner functions should follow the var statement. This helps make it clear what variables are included in its scope.
  • There should be no space between the name of a function and the ( (left parenthesis) of its parameter list.
  • There should be one space between the ) (right parenthesis) and the { (left curly brace) that begins the statement body.
    The body itself is indented four spaces.
    The } (right curly brace) is aligned with the line containing the beginning of the declaration of the function.

This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed.
It provides the best readability with inline functions and complex structures.

function getElementsByClassName(className) {
    var results = [];
    walkTheDOM(document.body, function (node) {
        var a; // array of class names
        var c = node.className; // the node's classname
        var i; // loop counter

// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.

        if (c) {
            a = c.split(' ');
            for (i = 0; i < a.length; i += 1) {
                if (ai === className) {
                    results.push(node);
                    break;
                }
            }
        }
    });
    return results;
}

If a function literal is anonymous, there should be one space between the word function and the ( (left parenthesis).
If the space is omitted, then it can appear that the function’s name is function, which is an incorrect reading.

div.onclick = function (e) {
   return false;
};

that = {
    method: function () {
         return this.datum;
    },
    datum: 0
};

When a function is to be invoked immediately,
the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

var collection = (function () {
    var keys = [], values = [];

    return {
    get: function (key) {
        var at = keys.indexOf(key);
        if (at >= 0) {
             return values[at];
        }
    },
    set: function (key, value) {
        var at = keys.indexOf(key);
        if (at < 0) {
            at = keys.length;
        }
        keysat = key;
        valuesat = value;
    },
    remove: function (key) {
        var at = keys.indexOf(key);
        if (at >= 0) {
            keys.splice(at, 1);
            values.splice(at, 1); }
        }
    };
}());

Variable Declarations

All variables should be declared before used.
JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that become implied globals.
If you get into the habit of using strict mode, you’ll get pulled up on this anyway.
Implied global variables should never be used.

The var statements should be the first statements in the function body.

It is preferred that each variable be given its own line. They should be listed in alphabetical order.

var currentSelectedTableEntry;
var indentationlevel;
var sizeOfTable;

JavaScript does not have block scope (see Scope section), so defining variables in blocks can confuse programmers who are experienced with other C family languages.

  • Define all variables at the top of the function.
  • Use of global variables should be minimized.
  • Implied global variables should never be used.

References

http://javascript.crockford.com/code.html

http://www.webreference.com/programming/javascript/prototypal_inheritance/

http://javascript.crockford.com/prototypal.html

http://www.crockford.com/javascript/inheritance.html

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

C#.NET Coding Standards and Guidelines

August 12, 2012

This is the current set of coding standards and guidelines I use when I’m coding in the C#.NET language.
I thought it would be good to share so others could get use out of them also, and maybe start a discussion as to amendments / changes they see that could be useful?

Naming Conventions

  • Do not use Hungarian notation, I.E. a boolian variable may have the name MyBool, but shouldn’t be called bMyBool.
  • Do prefix member variables with the underscore ‘_’. Do not prefix member variables with “this”. also use camelCasing for member variables. The underscore is easy to see, is one key stroke.
  • Do prefix interfaces names with “I”
  • Do not prefix enums, classes, or delegates with any letter.

Key:

c” = camelCase
P” = PascalCase
“_” = Prefix with _Underscore
“x” = Not Applicable.

Identifier Public Protected Internal Private Notes
Project File P x x x Match Assembly and Root Namespace
Project Folder P x x x Match Project File
Source File P x x x Match contained class
Test Source File P x x x Append the word Test if it contains tests
Image File c x x x
Other Files P x x x Apply where possible
Namespace P  x x x Partial Project/Assembly match.(Also see the namespace section)
Solution File P x x x CompanyNameSolutionDescription
Solution Folder P x x x CompanyNameSolutionDescription (if multiple solutions in repository). Source (if single solution)
SpecFlow Feature File P x x x USn_BriefUserStoryName where n is the user story number
oject Folder P  x x x Same as Project file
Class or Struct P P P P Add suffix of subclass.
Interface P P P P Prefix with a capital I.
Generic Class P P P P Use T (type) or K (key) as Type identifier.
Method P P P P Use a Verb or Verb-Object pair.
Test Method P x x x MemberUnderTest_StateUnderTest_ExpectedBehavior . StateUnderBehavior can be leftout if not applicable.
Property P P P P Do not prefix with Get or Set.
Field P P P _c Only use Private fields.
Constant P P P _c
Static Field P P P _c Only use Private fields.
Enum P P P P Options are also PascalCase.
Delegate P P P P See under Events, Delegates for naming Dot NET
Event P P P P See under Events, Delegates for naming Dot NET
Inline Variable x x x c Avoid single-character and enumerated names.
Parameter x x x c

Coding Style

Commenting

Comment Style

Block comments should usually be avoided

/* Line 1
* Line 2
* Line 3
*/
/* … */

Begin comment text with an upper case character. End comment text with a period.

If you have to comment your code, consider refactoring, so that it is easier to read.
Prefer not to use inline-comments to explain obvious code. Well written code is self-documenting.
Rather fix or clean up code now, than put a // Todo in.

You can access // Todo‘s in Visual Studio via

View menu -> Task List
The Tokens can be setup in Tools -> Options… -> Environment->Task List

or for ReSharper

ReSharper menu -> Tools -> To-do Items (or use the key shortcuts)

Use the following tokens:

  • Todo
  • Note
  • Bug
  • Not Implemented

XML Documentation

  • Always apply C# comment-blocks (///) to public, protected, and internal declarations.
  • Only use C# comment-blocks for documenting the API I.E the interface.
  • include <summary> comments. Include <param>, <return>, and <exception> comment
    sections where applicable.
  • Include <see cref=””/> and <seeAlso cref=””/> where possible.
  • Always add CDATA tags to comments containing code and other embedded markup in order to avoid
    encoding issues.
    Example:

    ///
    /// Add the following key to the appSettings” section of your config:
    /// <code><![CDATA[
    ///   <configuration>
    ///     <appSettings>
    ///       <add key=”mySetting” value=”myValue”/>
    ///     </appSettings>
    ///   </configuration>
    /// ]]></code>
    ///
    

File Organisation

Group internal class implementation by type in the following order:

  1. Member variables.
  2. Constructors & Finalizers.
  3. Nested Enums, Structs, and Classes.
  4. Properties
  5. Methods

Sequence declarations within type groups based upon access modifier and visibility:

  1. Public
  2. Protected
  3. Internal
  4. Private
  • Do not use #region statements
  • Always match class name and file name where ever possible. Avoid including more than one class per file.

Formatting

Bracing

  • Place first brace of the block at the end of the line preceded with a space.
    In languages like C, C++, C#, Java, it doesn’t matter where you put the first curly brace, it’s just personal preference or based on vote.
    In languages like JavaScript, it does matter. I use quite a bit of JavaScript, so just find it easier to use the same convention. Although at work, we use the “opening brace on a new line convention, simply because it won the vote”.
  • Always use curly braces ({ and }) in conditional statements. Unless there is a very simple statement, like return bla.
  • Recursively indent all code blocks contained within braces.

Spacing

Use white space (CR/LF, Tabs, etc) liberally to separate and organize code.

Only declare related attribute declarations on a single line, otherwise stack each attribute as a separate declaration.

Example:

// Bad!
[Attrbute1, Attrbute2, Attrbute3]
public class MyClass {
   …
}

// Good!
[Attrbute1, RelatedAttribute2]
[Attrbute3]
[Attrbute4]
public class MyClass {
   …
}

Tabs and Indenting

Tab characters (x09) should not be used in code. All indentation should be done with 3 space characters.

Language Usage

Access Modifiers

Do not omit access modifiers.
Explicitly declare all identifiers with the appropriate access modifier instead of allowing the default.
Example:

// Bad!
Void WriteEvent(string message) {
   …
}

// Good!
private Void WriteEvent(string message) {
   …
}
Prefer explicit to implicit Both the above definitions are private.
Prefer explicit to implicit.

Calling Routines

When calling a routine that takes a bool or a number.
Don’t pass litterals, as it’s unclair what they represent.
Instead create a variable with a meaningful name.

// calling MethodTakingExampleArgs
MethodTakingExampleArgs(true, 12);

// instead do the following

bool temperatureHasChanged = true;
int temperatureInCelcius = 12;

// calling MethodTakingExampleArgs
MethodTakingExampleArgs(temperatureHasChanged, temperatureInCelcius);

The intent becomes clearer, thus making for code that’s easier to read, thus we work faster.

If a routine call has its parameters spread over more than a single line due to being to long, place each parameter on its own line.
Also consider how many arguments are being passed, if it’s over 5, consider other ways to pass the information needed.

Class

Avoid putting multiple classes in a single file.

Events, Delegates

The delegate type should be prefixed with “Handler”.
The name of the procedure that does the work should be a verb.

public class MyDelegateExample {
   delegate void ChangeHandler();
   event ChangeHandler _change;

   private void OnChange() {
      if (_change != null)
         _change();
   }
}
Prefer explicit to implicit Rather than checking for null, you can add an empty delegate to your _change event
so that you don’t have to check the event for null before you raise it.

The traditional null check followed by the next action is not atomic, so not thread safe. Discussed in more depth here.

public class MyDelegateExample {

   delegate void ChangeHandler();
   event ChangeHandler _change = delegate{};

   public void Attach(ChangeHandler update) {
      Change += update;
   }

   public void Detach(ChangeHandler update) {
      Change -= update;
   }

   private void OnChange() {
      _change();
   }
}

Exceptions

  • Do not use try/catch blocks for flow-control. Only use for exceptional cases.
  • Only catch exceptions that you can handle.
  • Never declare an empty catch block.
  • Avoid nesting a try/catch within a catch block.
  • Always catch the most derived exception via exception filters.
  • Order exception filters from most to least derived exception type.
  • Avoid re-throwing an exception. Allow it to bubble-up instead.
  • If re-throwing an exception, preserve the original call stack by omitting the exception argument from the throw statement.Example:
    // Bad!
    catch(Exception e) {
       Log(e);
       throw e;
    }
    
    // Good!
    catch(Exception e) {
       Log(e);
       throw;
    }
    
  • Only use the finally block to release resources from a try statement.
  • Always use validation to avoid exceptions.
    Example:

    // Bad!
    try {
       conn.Close();
    }
    Catch(Exception ex) {
       // handle exception if already closed!
    }
    
    // Good!
    if(conn.State != ConnectionState.Closed) {
       conn.Close();
    }
    
  • Always set the innerException property on thrown exceptions so the exception chain & call stack are maintained.
  • Avoid defining custom exception classes if there is an existing Exception derived class available in the .NET library.
  • Always suffix exception class names with the word “Exception”.
  • Always add the SerializableAttribute to exception classes.
  • Always implement the standard “Exception Constructor Pattern”:
    public MyCustomException ();
    public MyCustomException (string message);
    public MyCustomException (string message, Exception innerException);
    
    Prefer explicit to implicit Or better… if using .NET 4.0 or greater, use optional parameters.
  • Always implement the deserialization constructor:
    protected MyCustomException(SerializationInfo info, treamingContext contxt);
    

Flow Control

Case Statements

  • Only use switch/case statements for simple operations with parallel conditional logic.
  • Prefer nested if/else over switch/case for short conditional sequences and complex conditions.
  • Prefer polymorphism over switch/case to encapsulate and delegate complex operations.
    Don’t fall into the trap of writing procedural code in an OO language.

Conditions

Avoid evaluating Boolean conditions against true or false.
Example:

// Bad!
if(isValid == true) {
   …
}

// Good!
if(isValid) {
   …
}

Use braces {} as shown above in all situations but for the most simple.
If you have more than a single line statement in a conditional, surround it with braces.

Implicit typing using the var keyword

Some background on var:

The compiler simply takes the compile time
type of the initialization expression and makes the variable have that type too.
An example:

var stringVariable = "Hello, world."
stringVariable = 0;
The above code is invalid.

The var keyword should only be used with LINQ and Anonymous types.
Unless there’s a significant gain in code simplicity, use explicit typing.

It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.
See Microsofts reference on var.

Sometimes you actually want the code to break when a type is changed.

Consider a control system. Many elements have On() and Off() methods. there are many cases where there is no relationship between the types (i.e. no common base classes or interfaces), there is only the similarity that both have methods with those signatures.

Writting code:

var thing = SomeFactory.GetThing();  // Returns something that is safe to turn off...
thing.Off();

Then later a change is made to the Factory and that method now returns something completely different, which happens to have severe consequences if it is arbitrarily turned off having such a design is debatable for many reasons.

By using var, the previous code will compile without complaint. Even though the return type may have changed from ReadingLamp to LifeSupportSystem.

I believe that there are more times when there is the possibility of an “unintended side-effect” caused by a change in the type than there are times where the change in type has no bearing on the code that consumes it. As a result, I very rarely use var. Even when the return type is obvious (such as the LHS of a new), I find it easier to be consistent.

Namespace

  • CompanyName.SolutionDescription.AssemblyDescription
  • Never declare more than 1 namespace per file.
  • Append folder-name to namespace for source files within sub-folders.
  • Also see the Naming conventions table.
  • Place namespace “using” statements together at the top of file. Group .NET namespaces above custom namespaces.
  • Followed by grouping of external namespaces.
  • Followed by grouping of organisation namespaces.
  • Order namespace “using” statements alphabetically.

Variables and Types

  • Declare and preferably initialize local variables at the same point and as close to where you first use them.
  • Always choose the simplest data type, list, or object required.
  • Always use the built-in C# data type aliases, not the .NET common type system (CTS).
    Example:
short NOT System.Int16
int NOT System.Int32
long NOT System.Int64
string NOT System.String
  • Declare one variable per line.
  • Only declare member variables as private. Use properties to provide access to them with public, protected, or internal access modifiers.
  • Prefer to use the as operator and check for null, rather than directly casting, and having to handle potential InvalidCastException.
    object dataObject = LoadData();
    DataSet ds = dataObject as DataSet;
    if(ds != null) {
       …
    }
    
  • Avoid boxing and unboxing value types.
    Especially in loops, or where performance matters.Example:

    int count = 1;
    object refCount = count; // Implicitly boxed.
    int newCount = (int)refCount; // Explicitly unboxed.
    

Strings

  • Use the “@” prefix for string literals instead of escaped strings.
  • Prefer String.Format() or StringBuilder over string concatenation.
    StringBuilder performs many times faster (thousands in fact)
  • Never concatenate strings inside a loop. Remember, string’s are immutable. Each time you concatenate, a new instance of string is created.
  • Checking whether a string is empty?
    String.Length == 0 or “” is faster than String.Empty, but… beware of null strings, if null when you perform a String.Length, you’ll get a NullReferenceException.
    The safest technique is to use the static IsNullOrEmpty function on string.
    Using “” does not create a new object. Due to string interning, it will be created either once per assembly or once per AppDomain.