Live to Code, Code to Live, Recursion?

Max + 1 = May

January 25, 2012 at 5:37 PMBobby Cannon

Max is getting a sister and her name will be May.

Yes, I named my next dog using an algorithm. Current Puppy + 1 = New Puppy Name. Simple but effective. That means Max + 1 = May.

ASCII Chart and the value of characters:

Computers use numbers to represent text. Values are stored on a table called  the ASCII table. The values for Max’s name is 77, 97, 120. This means the next puppies name would be 77, 97, 121 which ends up being May. I thought you guys might get a kick out of this.

Here is a picture of my next Boston Terrier. Isn’t she so cute.

May

Posted in: Personal

Tags:

Personal Coding Standard

January 24, 2012 at 9:19 PMBobby Cannon

I wanted to share with the world my personal coding standard. This is the coding standard I use everyday when I develop software.

Naming

How you name your members are very important. If helps you parse the code in our mind when reading the code. If I’m reading a bit of code and I run across a variable named “_userCount” I immediately know this is a class field. If I am reading code and I see a variable like “WaitingRoom.UserCount” I know it’s not a field because all fields are prefixed with an underscore character.

  1. Never abbreviate, never.
  2. Prefix private fields with the underscore character (_). This will be the ONLY time you will use the underscore character when naming.
    1. private int _userCount;
    2. private string _sqlConnectionString;
  3. Never use the underscore character for namespace, class, method, enum, enum value, event, read-only, const, interface and property names.
  4. Use Pascal casing for namespace, class, method, enum, enum value, event, read-only, const, interface and property names.
  5. Use Pascal casing for abbreviation like HTML should be Html. Ex. XML should be Xml.
    1. The only exception is two character abbreviations like “IO” and they should always be capitalized.
  6. Use camel casing for local variables and method arguments. Ex. userCount, phoneNumber
  7. Prefix component / control variables with the class name. Ex. LabelName, TextBoxAddress
  8. Name interfaces with the “I” prefix. Ex. IConfigurable, IExtendable
  9. Suffix exception classes with “Exception”. Ex. InputInvalidException, TypeNotFoundException
  10. Use descriptive naming.
    1. Avoid one character variable names, such as i or t. Use index or temp instead.
    2. Simple “for” loops are the only exception to one letter variable names.
    3. Never use Hungarian notation for public or protected members. Ex. strName, intNumUsers
    4. Do not abbreviate variables with names like num instead of number. See Naming item #1.
  11. Avoid fully qualified type names. Use the “using” statement instead.

Style

Some would call this formatting but it’s essential that you develop a style (format) of coding. This will greatly assist in the reading / parsing of code. There are many of the items below that are personal preferences and are not “the” way of coding. However once you have develop your style be very consistent in using it when you code.

  1. Maintain strict indentation. Always use “TAB” for indentation and never use spaces.
  2. All comments should pass spell checking. Misspelled comments indicate sloppy development.
  3. All comments need to be grammatically correct. Use punctuation to help with readability.
  4. All methods and properties should be separated by only one blank line.
  5. Always use curly brace scope for “if”, “for”, etc… statements, even if it’s a single statement.
  6. Always place an open curly brace “{“ on a new line.
  7. Always have one new line after an if, for, foreach, etc block statement.
  8. Always have one new line after the break statement in a switch block.
  9. Always have one new line before and after the beginning and ending region statements.
  10. Avoid multiple classes in one file. Always put classes, structures, enumerations in their own file.
  11. Always instantiate fields inside the constructor. Never directly initialize fields unless it is required like read-only / constant fields.
  12. Always use the C# auto property if possible.

Design

Following the following will prevent you from falling into problems that can be easily avoided. Issues like having to convert a field into a property then having to recompile code that used the field. This may not seem like a big deal unless you are releasing an assembly but you should always be conscience of your design even if it’s only use by yourself.

  1. Always use properties instead of accessible data members. Chapter 1 Item 1 of Effective C#.
  2. Always use readonly instead of const unless absolutely required or it just makes since.
    1. public const int DaysOfTheYear = 365; Using a constant makes since being that the days of the year will never change.
    2. public readonly int ReadTimeout = 10; Readonly is required because it’s possible that you may want to change the read timeout in the future.

File Structure

All files should contain the following regions. Each region may contain child regions but these should be the only root regions.

  • References (using statements)
  • Fields
  • Constructors (and de-constructors)
  • Properties
  • Methods
  • Events
  • Delegates

Tools

  • ReSharper – A must have for any C# developer.
  • Visual Studio 2010 Extensions
    • Spell Checker – spell checks comments.
    • Visual SVN

Posted in: Coding

Tags:

VAR and why it rocks!

January 24, 2012 at 9:17 PMBobby Cannon

Here are a few reasons why I use var and why I think it rocks.

You may still disagree after reading this but below are my opinions which I’ve marked the blog post in the category “Flame Wars”.

I had a hard time expressing why I like VAR so much so I did some research to try and help me express my thoughts and ideas. My references are below.

Let’s take a look at some code.

Explicit

// Have to use the full namespace because System.ServiceModel.Channels.Binding conflicts
// with System.Windows.Forms.Binding. See “It doesn't require using directive” below.
System.ServiceModel.Channels.Binding binding =   Bindings.GetBinding(address, false, false);
EndpointAddress endpoint = new EndpointAddress(new Uri(address));
using (ServiceStatusClient client = new ServiceStatusClient(binding, endpoint))
{
       client.Open();
       statusUpdates[address] = client.GetStatus();
       Console.WriteLine("ServiceHealth: {0}", statusUpdates[address].Health);
       client.Close();
}

VAR

var binding = Bindings.GetBinding(address, false, false);
var endpoint = new EndpointAddress(new Uri(address));
using (var client = new ServiceStatusClient(binding, endpoint))
{
       client.Open();
       statusUpdates[address] = client.GetStatus();
       Console.WriteLine("ServiceHealth: {0}", statusUpdates[address].Health);
       client.Close();
}

Readability

My first observation with these two versions of code is the fact that the explicit version isn’t any easier to read than the VAR version. I would argue that the explicit version is harder to read because my mind has to process more unnecessary data when trying to parse the code snippet. My goal is to ensure the code I’m reading is performing it task as expected.

EndpointAddress endpoint = new EndpointAddress(new Uri(address));

I read the previous line of code like this. I have a type EndPointAddress variable named “endpoint” with a value of a new EndPointAddress using the new URI of the provided address. Rather than I have a variable named “endpoint” with a value of a new EndPointAddress using the new URI of the provided address. Minor difference but a major one.

Basically I don’t need to identify the type in my head until I assign it. Once assigned then I know what the datatype in and can move on. Minor performance gain in not having to process the data until I need to.

See ReSharper’s point below about “removing code noise”.

Logic First

I would also like to state that using var allows you to get to the logic where most problems exist. As programmers all we do is manipulate memory. All we have to do is be sure we are doing it properly at the right times. I want to be able to see what the code is doing and if it’s doing what it should be. How many of your code defects are because of type issues? How many of your code defects are logic problems? Exactly. Here are some other people opinions.

Eglasius, a commenter on a StackOverflow states:

I will add a controversial view on it. Unless I am reading code from a book, I don't usually care what's the specific type for understanding some lines of code I am reading. Consider the .GetTableRectangle(e.Index), for which you are not showing the code that operates on it:

var itemRect = tabCaseNotes.GetTableRectangle(e.Index);
// do some operations on itemRect 

While reading that specific code I will get more to understand it from the operations on itemRect than from its type. It can be IRectangle, Rectangle, CustomRectangle, and still won't say much on what the code is doing with it. Instead I care more for the itemRect.Height, itemRect.Width or itemRect.GetArea() along with the logic involved.

Dustyburwell, another commenter on StackOverflow also makes a good point:

This question is a really good way to start a flame war. However, you should do whatever you and whoever you're working with think is most readable. There are good arguments for both sides of the debate about var.

Matt Hamilton, another commenter on StackOverflow say it this way:

var orders = cust.Orders;

I don't care if Customer.Orders is IEnumerable, ObservableCollection or BindingList - all I want is to keep that list in memory to iterate over it or get its count or something later on.

Contrast the above declaration with:

ObservableCollection orders = cust.Orders;

To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection to IList) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.

Less Typing

Why should I have to explicitly declare my variables? The compiler can do this for me and I can again focus on logic. The same reason we have IntelliSense and other features in our development environments. To help us become more productive and write more code. Not that I agree with this but Scott Hanselman states we only have so many keystrokes so don’t waste them on typing Explicit datatypes.

JetBrains ReSharper Team Blog

Here is what the ReSharper team had to say. I agree with everything and it really helps me state how I feel because I just couldn’t express it myself.

With the ReSharper 4 nightly builds available, some people are complaining about numerious suggestions to convert explicit type to "var" keyword. Of course, you can hide this suggestion by using Options / Code Inspection / Inspection Severity, or by using Alt-Enter and selecting "Change severity" option. But what's the deal with implicitly typed locals, anyway? Using var keyword can significantly improve your code, not just save you some typing. However, it may require discipline to apply good practices when using implicitly typed variables. Here is my list:

Anonymous Types

This is pretty obvious - you cannot declare local variable of anonymous type without using var.

It induces better naming for local variables

When you read local variable declaration with explicit type, you have more information at that moment and something like "IUnitTestElement current" makes sense. However, when this local variable is used later, you read "current" which takes some time to figure out the meaning. Using "var currentElement" makes it easier to read at any place.

It induces better API

When you let compiler deduce type from method return type or property type, you have to have good types in the first place. When you don't have explicit type in the initialization expression, you have to have best names for members.

It induces variable initialization

It is generally a good practice to initialize variable in the declaration, and compiler needs initializer to infer type for local variable declared with "var" keyword.

It removes code noise

There are a lot of cases, when implicitly typed local will reduce amount of text developer needs to read, or rather skip. Declaring local variable from new object expression or cast expression requires specifying type twice, if we don't use "var". With generics it can lead to a lot of otherwise redundant code. Another example would be iteration variable in foreach over Dictionary.</TKEY,TVALUE>

It doesn't require using directive

With var, you don't have explicit reference to type, as compiler infers type for you, so you don't need to import namespace when you need a temporary variable.

References

http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html
http://stackoverflow.com/questions/737835/resharper-and-var
http://stackoverflow.com/questions/1873873/why-does-resharper-want-to-use-var-for-everything
http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c

Posted in: Coding

Tags:

Scott Hanselman is so funny!

January 24, 2012 at 9:05 PMBobby Cannon

While scanning my blog list I found this interesting post. These Venn diagrams are hilarious but so true!

I so agree with the first diagram. I am currently working at my dream job. Your dream job should allow you to wake up and be so excited to go to work. Your day should fly by because your are so happy at what you do. Ever heard the phrase “time flies when you’re having fun”. The only issue I have with this is that I’m so happy that it seems like time is moving so fast but I guess everything comes with a cost.

Venn - Dream Job

The goal is to find a job / career that you truly enjoy. Never use money as a motivator because it will not make you happy. I would rather make significantly less money and be happy / motivated than to make a lot of money and be miserable.

This diagram is just funny…

Venn - Happy vs Pants

Posted in: Coding

Tags:

ASP.NET Custom 404 page not returning 404 code

January 24, 2012 at 9:03 PMBobby Cannon

After trying to setup my site for Google Webmaster Tools I found that my custom ASP.NET 404 page was not returning the 404 status code. The problem lies in the fact that my custom 404 page is a content form that uses a master page. The master page will override the content form status code. It displayed the correct custom page and told the browser that everything is OK (Code 200). This is considered a soft 404 or false 404. Google doesn't like this. I found many articles on the issue but the solution I want didn't seem to work.

The solution is to add the following two lines to the code behind Render method of the custom 404 page.

Response.Status = "404 Not Found";
Response.StatusCode = 404;

If this doesn't work then your host provider is yet overriding your status code. The only solution at this point is to add the following code to the content. I do fill as if this is such a “hack” but I haven’t found any other way around the issue.

<%
    // This code is required for host that do special 404 handling...
    Response.Status = "404 Not Found";
    Response.StatusCode = 404;
%>

Here is my post on the question at stackoverflow.

Posted in: Coding

Tags: