Moved

I’ve moved this blog to http://itsavirtuallife.wordpress.com/.  I thought the name fit better since most of my posts are software related.

Advertisements

Clean Code Tip #7 – Method Purpose

#7:  Methods should either do something or decide something, but not both.

For example, the method below has a method GetDistinctArrarCount that returns an array count and it removes empty elements.  The removal elements should be done separately since the method purpose is to get the array count.

static void Main(string[] args)
        {
            List<string>  people = new List<string>() { "Brian", "Sara", "", "Bob"};

            int count = GetDistinctArrayCount(people);

            Console.Write(count);
            Console.ReadLine();
        }

        private static int GetDistinctArrayCount(IEnumerable<string> arrayValues)
        {
            // Remove Emtpy Values
            arrayValues = arrayValues.Where(x => !String.IsNullOrEmpty(x));

            // Return Distinct Count
            return arrayValues.Distinct().Count();
        }

Here’s a better way to write this:

 static void Main(string[] args)
        {
            List<string>  people = new List<string>() { "Brian", "Sara", "", "Bob"};

            // Remove empty elements before getting the distinct count
            people = people.Where(x => !String.IsNullOrEmpty(x)).ToList();
            int count = GetDistinctArrayCount(people);

            Console.Write(count);
            Console.ReadLine();
        }

        private static int GetDistinctArrayCount(IEnumerable<string> arrayValues)
        {
            // Return Distinct Count
            return arrayValues.Distinct().Count();
        }

DynamicObject

I ran across this the other day when looking at some code from the Internet.  I hadn’t heard of DynamicObject before, so I thought I’d investigate.  The definition from MSDN states that it “Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly.”

You can think of it as something similar to the .NET Object class, except that it enables you to define which methods or properties can be performed at run time.

For other classes, you will get a compile time error when you’ve written code against a nonexistent method.  Classes that inherit from DynamicObject will not, but will be instead evaluated at run time.  If the dynamic class hasn’t implemented the method or coded for nonexistent methods, then a run time error will be thrown.

Here’s an example:

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {

    }
}

The MyDynamicClass inherits from DynamicObject and is completely empty.  However, the Main method is calling a method called MyAdder which sonds like it adds two integer arguments.  When this code is compiled, there’s no errors, but when we run we get a “RunTimeBinderException was unhandled error” which states that “‘DynamicObjectExample.MyDynamicClass’ does not contain a definition for ‘MyAdder’.”

To add logic for situations where a method is invoked which doesn’t exist, the TryInvokeMember method can be overridden.

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }
    }
}

The result of the above is

“MyAdder Method not present in this class

Result: 0”

with no exceptions.  Now let’s see what happens when we actually implement the MyAdder method on MyDynamicClass.

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }

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

The result of the above will be “Result: 3” which is what we expect :).

TryGetMember and TrySetMember are other virtual members on DynamicClass that allow you to add logic for getting and setting properties that do not exist.

How Facebook Ships Code (via FrameThink – Frameworks for Thinking People)

I’m fascinated by the way Facebook operates.  It’s a very unique environment, not easily replicated (nor would their system work for all companies, even if they tried).  These are notes gathered from talking with many friends at Facebook about how the company develops and releases software. It’s been over six months since I assembled these observations and I’m sure Facebook has continuously evolved its software development practices in the meanti … Read More

via FrameThink – Frameworks for Thinking People

Clean Code Tips #4-6: Method Arguments

#4:  Methods should have as few arguments as possible.  Ideally, they should never have more than three.  If there’s more than three, then it’s likely the arguments should be wrapped into a class of their own.

#5:  Boolean arguments should be avoided because it complicates the method name and the purpose of the method.  Passing a boolean will likely cause your method to do two different things based on the bool.  This is in contradiction to rule #2.

#6:  Methods that change input arguments should be defined so the argument is the return value.  This also prevents the usage of output arguments which can be confusing.

Clean Code Tips #1-3: Methods Should be Small, Do Only 1 Thing, and 1 Level of Abstraction

#1:  Methods should be small.  Ideally, they should hardly ever be 20 lines long.  This forces the developer to create more methods that can shared and tested more easily.  Smaller methods will also result in less unit tests for each method since there’s less logic applied.

#2:  Keeping method small also helps to enforce the concept that methods should only do one thing.  The more logic that exists in a method will likely limit it’s ability to be shared and reused.  It also ensures that changes to the method will only affect the single purpose of the method.

#3:  One level of abstraction per method is also a good rule to follow.  This helps others understand what the method is doing which prevents bugs from getting into the software.

Following the above tips will result in more methods, but it doesn’t necessarily result in more code since methods can be shared more easily.

Most Used Enumerable(T) Methods

Here’s the Enumerable methods I use the most.  All of these are available in the .NET 4.0 Framework.

Enumerable.Any() – Determines whether a sequence contains any elements.

Enumerable.Empty<T>() – Returns an empty IEnumerable<T> that has the specified type argument.

Enumerable.Distinct() – Returns distinct elements from a sequence by using the default equality comparer to compare values.

Enumerable.FirstOrDefault() – Returns the first element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Count() – Returns the number of elements in a sequence.

Enumerabel.LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Max() – Returns the maximum value in a generic sequence.

Enumerable.Min() – Returns the minimum value in a generic sequence.

Enumerable.Select() – Projects each element of a sequence into a new form.

Enumerable.ToArray() – Creates an array from a IEnumerable<T>.

Enumerable.Where() – Filters a sequence of values based on a predicate.

Here’s a link to the MSDN site that lists all the available methods