I have two specific C# coding conventions I've been practicing with mixed feelings. I'd be curious to hear what people think. They are:
#1. Name instances after the class it's an instance of, camelCased
#2: "Matching property names"
Here's the rationale:
#1. Name instances after the class it's an instance of, camelCased
I use this as my default setting for naming convention. Of course, there are exceptions. But used consistently it dramatically improves code clarity and maintainability. The code looks like this:
var dataConnection = new DataConnection();
//not: var dataConn, dbConn, sqlConn, myDbPickOfTheDay etc.
FileInfo fileInfo = new FileInfo();
Timer timer = new Timer();
//etc.
I'm at the point where code like this causes me physical pain:
DataConnection dbConn = new DataConnection();
I can't stress enough how this convention has taken away the pain and anger of the variable name game.
This convention is in sharp contrast to attempting to name things in ways that try to indicate what the instance is doing, which amounts to trying to creatively embed the business case in code. Code has a way of getting refactored to the point where those original names are misleading at best.
To me this convention is gold. It also prevents the horrible practice of slightly tweaked variable names for the same thing.
An example of this convention in practice is:
class Person { ...
public string FirstName { get; set; }
//and then
var person = new Person();
person.FirstName = firstName; //where firstName comes from somewhere else.
Very easy to read. Very boring. Boring is good when it comes to maintaining code.
However, this convention leads me to #2:
#2 "Matching property names" ( for lack of a better title )
Here's an example:
public class ShoppingCart { ..
private Item item;
public Item Item { //<---- ?
get { return this.item; } ...
The compiler is perfectly happy with this. And, in fact, it exposes a very nice interface:
//notice how tempting it is to just say "ShoppingCart cart ... "
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.Item = item;
Now, the alternative is to be creative -- You actually need to drum up two good variable names for Item: the public property name and the private member variable name.
How many times have you seen this and just want to retire immediately?
public class ShoppingCart { ..
private Item cartItem;
public Item ShoppingCartItem {
get { return this.cartItem; } ..
///....
ShoppingCart userShoppingCart = new ShoppingCart();
userShoppingCart.ShoppingCartItem = userSelection;
I feel strongly enough about convention #1 that I think I can live with #2.
What do you think ?