Welcome

You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

Programming Standards, Naming Conventions

Posted by Keith Elder | Posted in .Net, Programming | Posted on 30-11-2007

5

It never ceases to amaze me how different naming conventions are from language to language.  It seems each language has their own coding convention or style that gets adopted over time.  More times than not these naming conventions are established by authors in books, magazines, and Internet articles.  Developers that read those publications follow suite the majority of the time.  For example, I can remember years ago developers who wrote PHP named files they included in their programs with the extension of “.inc” yet other files ended in “.php”.  The huge downside to this was the .inc files would be passed directly through from an Apache server as plain text file instead of getting parsed as code.  This would allow want to be hackers to see the code to a web site.  The worse part is a lot of the time the database username and password was visible in plain text.  Why was this done?  It was done because Rasmus (the guy who wrote PHP) put it in his samples.  Once it was printed, it became a standard that took many years to correct.

After programming in a language for several years one tends to adopt a certain style and I am no exception to that.  It is funny how caught up we get in how things are named.  Our brains work on consistency though.  If I have to read code someone else wrote that doesn’t follow my naming conventions and style I am now out of my comfort zone and have to do double translation.  First translate their code into what I would have done to understand the problem better, and then read their code and translate that into what it is doing.  The worst examples of this are when you have to read code in a language written by a developer who is new to the language that brings in the previous style of the language they’ve used for years.  It is painful to read code that isn’t written in the “implied” standard the language is written in.  By implied I mean if you look at Intellisense for .Net objects, enumerations, namespaces, methods and so on you’ll quickly realize that everything starts with a capital letter.  A developer learning a programming language from scratch will pickup on this and more than likely follow this implied naming convention.  However, if a Java or PHP/Perl/Bash/Ruby programmer writes .Net code he or she will more than likely write code the same way they did in the Java world.  Example:

Typical .Net Version

        public int AddTwoNumbers(int x, int y)
        {
            return x + y;
        }

Typical Java Version

        public int addTwoNumbers(int x, int y)
        {
            return x + y;
        }

Typical Scripting Language Version

        public int add_two_numbers(int x, int y)
        {
            return x + y;
        }

Three distinct ways to name a method.  The difference in the first two is the upper / lower casing of the method but it is more obvious with the third example in how different platforms write their code.  I’ve had the pleasure, I mean pain of reading .Net code written or translated by developers who are new to .Net.  I can tell within a few lines the language the person translated the code from or the language they wrote in previously.  Assuming they don’t “change” how they write their code.  I suspect most others can as well.

When developers transition to .Net or learn .Net it amazes me how many of them deviate from the implied naming conventions.  For example, all namespaces in .Net are Pascal case with no underscores yet I see developers coming from a Java background creating namespaces like “com.something.foo” and breaking this convention instead of following what has been established before they got there.  I find the .Net framework very consistent in how it is written and coded.  If you are learning .Net the best rule you can follow is first follow the implied naming conventions.

I like standards, especially when moving developers in and out of development teams.  It amazes me when I look at a problem that isn’t formatted or named the way I prefer, how much longer it takes me to understand what the developer is doing.  This can be from how curly braces are structured, to variable naming conventions and much more.  I have had situations that before I could help the person I had to refactor their code before I could understand it.   More times than not while I am refactoring the person will find their own mistake because of how I refactored it (simplicity is genius).  Naming conventions are good because it helps others to quickly understand what is going on.  Again I go back to my point that if someone writes in a style you don’t follow you are doing double the work to understand it. 

Here’s an example of the subtlety in the naming of variables that can be confusing.  For example if I see a property of an object called “AddressCollection” I know immediately this is a generic list of Address objects.  Easy, Forrest Gump, no questions asked. Conversely, if I see “Addresses” as a property I have no idea what this is.  It could be a collection or just an object.  I’ve taught many a programming class and I’ve seen a lot of code written by complete newbie programmers.  It always amazed me at how I could write code they couldn’t understand just by changing my “style” or naming conventions.  Folks, this stuff does matter and especially in larger team environments.    If you don’t believe me, then write a program with variables named after Flintstone characters and then give it to a Senior Engineer and see how long it takes them to figure out what it does versus one that isn’t.

There are a lot of preferences when you talk to developers about how they code.  I personally like what makes sense and is as Gump as I can get it.  I also like to follow suit of how other things are named to provide consistency.  So what are my preferences?  Well, I won’t go into each and everyone but here are a few of my stronger opinions.

Variable Prefixes
A controversial topic no doubt but I prefix all private variables with an underscore.  I do this because it is easier to read.  It is also one character different which follows the rule of not making private variables and public variables different by case.  Example:

        private string _propertyName;
        public string PropertyName
        {
            get { return _propertyName; }
            set { _propertyName = value; }
        }

I’ve seen a lot of code written and published on the Internet that prefixes variables with “m_”.  Most of the time this is due to legacy habits.  For those that do this, please stop, you aren’t coding in VB6 anymore.   It boils down to simplicity.  I use one character, it avoids naming collisions and is easy on the eyes to read and less distracting. 

I also have seen code where developers will prefix a variable with a shortcut of a type.  For example if they are creating an array they’ll do arrMyVariable or if the variable is a string they will do strMyVariable.  Usually when I see this type of code it tells me the person came from a scripting language background whereby variables can literally be different types in the next statement.  For example this is something we used to do in Perl whereby this would help other developers to know what was in the variable or suppose to be in the variable so they wouldn’t try to change the type. 

Curly Braces
Another controversial topic is curly braces.  I line curly braces up on top of each other (each gets their own line).  Some may not agree with this but I find it extremely easy to debug sections since the braces line up and allow the eyes to see blocks of code quicker.  When you get into nested situations it is easier to see the “blocks”.  For those that don’t agree I have tested this in many programming classes I’ve taught and students who are “learning” a language from scratch will agree 100% of the time that lining them up is easier.  Here’s what I’m talking about with some random code that makes no sense and isn’t suppose to.  Two versions of it with a lot of nested blocks.

HARD TO READ

        private void MyFunction(int x) {
            if (x % 2 == 0) {
                for (int i = 0; i < x; i++) {
                    if (i % 2 == 0) {
                        // do something
                    }
                    else {
                        // do something
                        for (int i = 0; i < x*i; i++) {
                            // something else
                            if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday) {
                                Console.WriteLine("Take the day off.");
                            }
                        }
                    }
                }
            }
        }

EASIER TO READ

   private void MyFunction(int x)
        {
            if (x % 2 == 0)
            {
                for (int i = 0; i < x; i++)
                {
                    if (i % 2 == 0)
                    {
                        // do something
                    }
                    else
                    {
                        // do something
                        for (int i = 0; i < x*i; i++)
                        {
                            // something else
                            if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday)
                            {
                                Console.WriteLine("Take the day off.");
                            }
                        }
                    }
                }
            }
        }

While the second example is longer in terms of lines of code (this is why God created regions) one thing you can see easily is how nested it is and how the code breathes more.  The first approach looks like it is cramming the code together.  Like I’ve said, I have tested this in every programming class I’ve taught and the consensus is the second example is always preferred and easier to understand.  The nice thing is for those using Visual Studio this is the out of the box behavior. 

If Statements
A pet peeve of mine is when developers shortcut if blocks.  Here is what I mean.

If Block Shortcut

    public Foo(int x)
    {
        if (x % 2 == 0) Console.WriteLine(x.ToString() + " is even");
    }

If you have a single line for an If block you can shortcut it and leave off the curly braces.  It is a feature, yeah.  Some other languages support this and C# does as well.  Personally I can’t stand this because of several reasons.  One, debugging.  If I want to set a break point just when the Console.WriteLine is hit I can’t.  I have set it on the one line and check it each time.  Another reason this disturbs me is if the business logic changes where I have to print an else statement it has to be reformatted anyway.  Go ahead and add the curly braces up front instead of waiting.  The third reason is when looking at the code there may be things that occur after this and it is confusing to read to know what the intent of the person that originally wrote it was.   This also ties into the readability of the code as outlined in the curly braces section.   Bottom line, don’t shortcut just because you can.

Namespaces
I mentioned this earlier but I’ll mention it again. Namespaces should be Pascal Case.  A namespace should be something that is agreed on BEFORE you write code for a project.  The standard is to use the CompanyName[.Team][.SubTeam] + Project + [.Feature][.Design].  Example:  Microsoft.Practices.EnterpriseLibrary.Caching.  Of course you can leave off the team, subteam, feature or design if you choose depending on how global the project is.  Don’t worry if you do that.  ScottGu isn’t going to show up at your doorstep asking you to change it.  There aren’t any hard and fast rules these are just the “implied what Microsoft does” rules.  For more detailed information Microsoft has a reference page about namespaces available on MSDN.

Naming Preferences
This is a large topic, or can be.  So instead of re-hashing this on my own go read Peter Brown’s article on naming conventions.  It is fantastic. This is one of the few articles that I can say I agree with 96.78582762% or more of what it states.  I imagine if I read Peter’s code it would look exactly like mine in terms of naming preferences.  Beyond Peter’s article there is also naming guidelines already established on MSDN that outline how to name classes, enumerations, parameters, properties, events, and so on.  If you are wondering what I do, for the most part I follow that guideline.

To CSLA or Not CSLA – Your Thoughts?

Posted by Keith Elder | Posted in .Net | Posted on 28-11-2007

30

image Recently at work we have been having some discussions around standardizing .Net development around Rockford Lhotka’s CSLA framework.  My team has been digging into CSLA for several weeks now generating business objects using Codesmith Freeware 2.6 and working through Rockford’s book generating CSLA objects for our main product.  With only a few weeks into it and no real production time behind the framework we are having a hard time jumping on one side of the fence or the other.  There are things we like about CSLA such as the ability to restructure an application from a two tier to a three tier application just by changing the config file.   Maybe those of you that have used CSLA can chime in and provide some constructive criticism or positive feedback about your experience.

Before you jump in and start commenting here is some background on why this is being considered.  I think it is important to know why we are considering this path. 

The main reason we are looking to standardized development across various teams is we have teams moving to .Net and we have teams that make it hard to move engineers among the various projects as needed.  Today there isn’t a standard on how applications should be built and each team builds things the way they chose.  Some people may think that is good since it gives developers flexibility but it also causes problems.  For example, one team may use NHibernate and another might use something else.  If a team member needs to be reallocated to provide an additional resource to a project the problem arises they are no longer productive because they don’t know NHibernate.  Now of course this can be said for any variety of things.  Obviously having a standard each team follows would be beneficial.

In addition to reallocating resources other teams are moving into .Net from various other platforms.  Given the fact there are 15 ways to do data access alone we are trying to minimize that thought process so the engineers can focus mainly on business development not the “how”.   The CSLA framework is very attractive from this angle because it provides a wealth of documentation whereby we could hand an engineer a book and they can learn how things are done.  They also don’t have to know the internals of CSLA since they are going to focus on business rules, validation and security. 

That’s some of the thought process going on.  There are other things we are considering as well but I don’t want to get into all of the details.   The community in general seems to be somewhat happy with CSLA and then there are some that are not.  I have always said you really don’t know a product until you put it into production.  For those that have heard me speak, you know that I don’t normally speak on topics until I have put them in production and gone through all of the rusty washers.  So for those of you that have used CSLA for a lengthy amount of time what are the rusty washers or shiny pennies you found?    

Please keep your emotional flames to yourself, I don’t want this to get ugly and turn into a Y vs Z vs X debate, just the facts.  Ok, that’s it.  Ready?  Discuss! 

Mississippi Retreat Begins

Posted by Keith Elder | Posted in Friends | Posted on 16-11-2007

1

 

Chris on John DeereI mentioned the other day that five team members from work were coming to Mississippi for the weekend.  Chris arrived this morning about 11:00.  Soon after arriving we found out his luggage never left Detroit.  Hopefully it will arrive when we go to pickup the other guys at 8:30 tonight.

After getting in we headed to “The Front Porch” to eat a nice Southern buffet for lunch complete with fried okra (which Chris had never tried), brisket, turnip greens, purple hull peas, gumbo, cornbread, yeast rolls, mash potatoes and gravy and much more.  I think Chris ate his own weight in brisket and couldn’t stop laughing when the guy that served him was so nice.  Or maybe it was his accent. 

After that we went to the house and I gave him the tour of the Elder Estate.  He took a ride on the John Deere in the back yard and was disappointed at its speed.  As I pointed out the JD is made for hauling and is geared low.  So far so good and no one is in jail yet.

For those that want to follow along I’ll be uploading all the pictures to Flickr to the Mississippi Retreat 2007 set.

The Ultimate Team Building Experience

Posted by Keith Elder | Posted in Friends | Posted on 14-11-2007

1

Team building is an important part of work.  A lot of companies, ours included, promotes team building exercises.  This helps to build moral among the team and if other teams are included it helps to break down silos.  Currently I live in Hattiesburg, MS but I work remotely for a company in Michigan called Quicken Loans.  Being a remote team leader has its challenges, one of which is team building.  How do you do team building when you are 1,000 miles away?  This weekend we are doing what I think is going to be the ultimate team building exercise. 

A few months ago I was sitting around thinking what I could do as a team exercise.  The team is unique in the fact it is made up of all guys who all have similar personalities and are close to the same age.  Typically as long as there is fun and adult beverages involved they are happy.  The team members always kid me about living in South which I love.  I thought what better way to show them how the other half lives than invite them to come down for a weekend getaway fun trip and stay with The Elder?  That is what I did.  I put out the invitation and not surprisingly everyone on the team accepted.  We set a date when it worked for everyone, ordered plane tickets and made it happen.  Friday all of them are flying to Mississippi for a weekend in the South. 

What do you do with five guys from the North (4 michiganders, 1 canadian) in Hattiesburg, MS for a weekend?  Turns out there is a bunch of things depending on scheduling.  Friday night they will be landing at the local airport around 8:30 PM.  We have some great BBQ places in the area so I’m going to pickup some BBQ at a local place and we’ll have some BBQ on the deck when we get back to the house.  Of course you can’t have BBQ without a frosty adult beverage so I’ll be picking up a couple containers of some Mississippi brew from Lazy Magnolia brewing company.  After some BBQ and a tour around the home stead we’ll head to town to checkout the local scene.

Saturday we are loading up in the Aspen and heading to New Orleans, LA.  I’m not sure where we’ll eat lunch at but a local cajun place for sure.  I have to get the Michiganders and the Canadian some authentic gumbo, and other southern dishes to fill their bellies.  After that we’ll hit downtown New Orleans, Pat O’s, Hard Rock, etc.  Assuming we make it back from New Orleans in one piece on Saturday, Sunday we are going to eat at the best buffet in Mississippi and then head to the coast (about 60 miles from my house).  During downtime I’m sure we’ll fire up the XBox on the HDTV and try our hands at Guitar Hero II. 

All in all it is going to be a fun filled flavor of the South weekend with gorgeous 75-80 degree weather.  A quick note for the guys coming down, leave your LLBean jackets, shirts, and boots at home.  You won’t need ’em!

Codemash 2008 – It is all about Workflow!

Posted by Keith Elder | Posted in Uncategorized | Posted on 07-11-2007

1

Jim Holmes holding his new bookimage Codemash 2008 scheduled for January 9th-11th is only a few months away.  It seems like only a few months ago I was watching Jim Holmes walk around the Kalahari Resort in a Hawaiian shirt and flip flops with six inches of snow on the ground outside.  Good times.  Another Codemash event is just around the corner and rumor has it the sessions have been finalized. 

I have two sessions slated for Codemash, both of which will be given on Workflow Foundation.  The first session is an introduction to Workflow Foundation.  Here is the abstract:

Your boss comes up to you and gives you some business logic one day at work. You spend weeks coding it. As soon as you get done he informs you the rules have changed. You want to smack him/her in the face but you politely smile and say thank you, I’ll have that done in a few weeks. Little does your boss know you’ve used Workflow Foundation to map out all the business logic. You quickly make the change declaratively within Workflow and go back to reading your RSS feeds. While this scenario isn’t true, it can be if you use Workflow Foundation. In this talk we’ll explore what Workflow Foundation is from the ground up so you’ll have a good sense of where to get started when you head back to the office.

In this session I hope to give a really good no non-sense introduction to Workflow Foundation.  What I mean by that is I’m not going to spend 30 minutes talking about Workflow Foundation and then show a demo.  I think for developers to really get WF they have to see it, touch it, caress it, squeeze it and call it George.  I can tell you all day long about Activities and Extensibility but until one sees just how cool it is you aren’t going to really get it.  Bottom line is plan on getting your feet wet with Workflow Foundation as soon as possible and then I’ll explain what the heck is going on under-the-hood. 

The second session I’m going to speak on is “Building Custom Workflow Activities”.  Here is the abstract for this session:

Workflow Foundation is a powerful tool that allows you to declaratively design and map out application logic. While a lot of custom logic can be created using the Code activity provided out of the box, it doesn’t work very well when you move workflow out of Visual Studio and into the hands of business analyst or end users who want to re-configure workflows. The real power of WF shines through when you build custom activities that can be re-used on numerous workflows by end users and other developers. In this session we will look at Workflow Foundation from the ground floor all the way through building custom workflow activities from scratch. In the end we’ll design a reusable workflow activity that can be easily configured complete with validation.

This session is all about code.  I think there are only 4 slides in the whole deck that basically explain why you want to write custom code activities in Workflow Foundation.  From then on it is all about code.  It is called “Code”-mash no? 

 

Technorati tags: ,