How do you hide bad code smells?

Ever come across some code that just wreaks?

I’m talking the kind of smells like 500 line method implementations or methods that are located in the wrong class.

It’s amusing to see how developers go out of their way to hide their problems rather than fix them.

There are two code-smell hiding techniques I often see utilized in the C# Visual Studio space.

  1. Wrap the offending code in a #region (and hope that others don’t have region expansion on by default)
  2. Move the distracting/inappropriately placed members into a partial class

Most often though I find that developers seem proud of the smells as they don’t even bother to hide the fact that they’ve just left a big stinky guff for the next person to walk right into.

What code-smell hiding techniques have you been witness to? Or more importantly how do you hide your own smells?

Posted in .Net, C#, Development at November 26th, 2008. 1 Comment.

How do you convert your bool to a bit (1 or 0) value?

I’ve often seen code that tries to get a numeric bit (1, 0) value for a boolean.

I know of three ways you can do it:

  1. Manual condition checking
  2. Use the GetHashCode() method
  3. Use the built in .Net Convert class

All three approaches do the job however I find that using the Convert.ToByte(boolValue) makes the most sense from a readability stance.

The following examples mix it up a bit and accommodate a Nullable<bool>.

Let’s start with the scenario where true is 1 and false and null are 0.


   bool? tVal = true;
    bool? fVal = false;
    bool? nVal = null;

    // true = 1, false = 0, null = 0

    Assert.AreEqual(1, tVal.HasValue && tVal.Value ? 1 : 0);
    Assert.AreEqual(0, fVal.HasValue && fVal.Value ? 1 : 0);
    Assert.AreEqual(0, nVal.HasValue && nVal.Value ? 1 : 0);

    Assert.AreEqual(1, tVal.GetHashCode());
    Assert.AreEqual(0, fVal.GetHashCode());
    Assert.AreEqual(0, nVal.GetHashCode());

    Assert.AreEqual(1, Convert.ToByte(tVal));
    Assert.AreEqual(0, Convert.ToByte(fVal));
    Assert.AreEqual(0, Convert.ToByte(nVal));

Now let’s mix it up a bit and say that a null value should represent a TRUE or 1 value by default.
i.e. true = 1, null = 1, false = 0,



    bool? tVal = true;
    bool? fVal = false;
    bool? nVal = null;

    Assert.AreEqual(1, !tVal.HasValue || tVal.Value ? 1 : 0);
    Assert.AreEqual(0, !fVal.HasValue || fVal.Value ? 1 : 0);
    Assert.AreEqual(1, !nVal.HasValue || nVal.Value ? 1 : 0);

    Assert.AreEqual(1, (tVal ?? true).GetHashCode());
    Assert.AreEqual(0, (fVal ?? true).GetHashCode());
    Assert.AreEqual(1, (nVal ?? true).GetHashCode());

    Assert.AreEqual(1, Convert.ToByte(tVal ?? true));
    Assert.AreEqual(0, Convert.ToByte(fVal ?? true));
    Assert.AreEqual(1, Convert.ToByte(nVal ?? true));

Is there an easier, better or another alternate way to do this?

I’d love to hear your thoughts?

Posted in .Net, C#, Development at November 24th, 2008. 5 Comments.

Excellent arguments to counter resistance to ORMs

This article collates some good answers to resistive arguments for using Object Relational Mappers.

Posted in Development at November 24th, 2008. No Comments.

Writing clean, usuable CSS

This article demonstrates 21 techniques you can employ to write usable CSS.

Posted in css, Development at November 13th, 2008. 2 Comments.

Creating Custom Exception Types

One of the things that pops up over and over in project development is the issue of when to create Custom Exceptions.

To come to any form of conclusion it’s necessary to understand the reason why you might create your own Exception class.

1. To allow typesafe error detection and act appropriately.
2. To add context specific data.
3. There’s no existing framework exception that signifies the error.

1. To allow typesafe error detection.

Creating a customized exception allows the receiver to act upon a specific error. Using this approach the receiver is forced to detect that specific error to perform any useful action.
Examples where creating a custom exception for this scenario to make sense include;

- situations where you may need to prompt a user to correct a problem (e.g. disk full exception)
or
- where you need to log specific exceptions.

2. To add context specific data.

By adding more context to an exception, the receiver of the exception can use this information to help track down and recover from the error.

An example; say the validation rules for an object instance fail, by attaching the validation rules to the exception the receiver may use them to display appropriate error messages on screen to help recover from the error.

E.g.


public class ValidationException : Exception {

  public ValidationException(ValidationResults results) : base(results.ToString())
  {
Results = results;
  }

  public ValidationResults Results {get;set;}
} 

public class ValidationResults : IEnumerable<KeyValuePair<string,string>> {

  public IEnumerator<KeyValuePair<string, string>> GetEnumerator() {
    ...
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
  }
}

Usage:

try {
  ...
  ...
} catch (ValidationException ve) {
  foreach (var result in ve.Results) {
    Console.WriteLine("Error:" + result.Key + " : " + result.Value);
  }
}

Alternately, the System.Exception class contains a Data Dictionary property that can be used to attach context without having to create your own customized exception class:

E.g.


var exception = new InvalidOperationException("ValidationException"); 

var validationResults = new Dictionary<string, string>();
validationResults["Name"] = "The Name value is too long.";
validationResults["Postcode"] = "The Postcode is invalid.";
exception.Data.Add("ValidationResults", validationResults);

throw exception;

The lack of type safety in the Data dictionary may be off-putting but using extension methods you can add some type safety.


public static IDictionary<string, string> GetValidationResults(this InvalidOperationException ioe)
{
  if (ioe.Data.Contains("ValidationResults"))
  {
    return ioe.Data["ValidationResults"] as Dictionary<string,string>;
  }
  return new Dictionary<string, string>();
}

public static string GetValidationMessage(this InvalidOperationException ioe, string key)
{
  if (ioe.Data.Contains("ValidationResults"))
  {
    return ((IDictionary<string, string>) ioe.Data["ValidationResults"])[key];
  }
  return null;
}

I find that using the Data dictionary approach may save you the benefit of creating a Custom Exception but at the expense of more verbose and un-intuitive code.

3. There’s no existing framework exception that signifies the error.

The detail level to which you can specify an exception type is infinite. When it comes down to it there are few framework exception types that are valid for most scenarios:

Input value causes exception; throw one of

System.ArgumentException
System.ArgumentNullException
System.ArgumentOutOfRangeException

For all other errors a good default option is to use the System.InvalidOperationException.

Conclusion:

To sum up, think carefully about the specific scenario that is being addressed when writing exception logic, follow this checklist to help in your decision making.

Is there a need to act upon the specific exception and find a way to recover from it?

Yes -> Consider creating a generic custom exception.
For example create an exception named DuplicateEntityException rather than JobRateAlreadyExistsException.

No -> throw an existing exception type.

Do you need to log a specific error scenario?

Yes -> Consider creating a generic custom exception.
No -> throw an existing exception type.

Do you need extra information in the exception to respond effectively?

Yes -> Determine whether creating a custom exception with typesafe data members is more intuitive than using the Data dictionary on the System.Exception class.
No -> throw an existing exception type.

For all other scenarios default to throwing an existing exception type.

What are your thoughts and experiences on this issue?

Posted in .Net, Development at November 10th, 2008. No Comments.

Enterprise Library Walkthrough

What is Enterprise Library?

Ent.Lib 4.1 – http://msdn.microsoft.com/en-us/library/dd203099.aspx

The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development cross-cutting concerns (such as logging, validation, data access, exception handling, and many others).

The application blocks aim to encapsulate proven best-practice for enterprise .net development.

In total there are over 9 application blocks:

  • Caching
  • Cryptography
  • Data Access
  • Exception Handling
  • Logging
  • Policy Injection
  • Security
  • Unity – Dependency Injection (IoC) container
  • Validation

This article will address the Exception, Logging, Validation and Unity application block. The new Unity Application block encapsulates the Policy Injection block and as such will not be addressed in this article along with the Caching, Cryptography and Security blocks.

Download Ent. Library 4.1 here:
http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&displaylang=en

Important:

This article is just a rehash of information easily found in the Ent.Library documentation and online websites. To get a comprehensive understanding of how the blocks work download the Sample Code I’ve created here.

Alternately, for further demonstrations on how these blocks work, load up the included QuickStart tutorials included with the Ent. Lib download.

Note:
The solution is works with VS 2008 Team System. It utilizes the seperate Unity Application block but works with Ent. Library 3.1 for all other App. Blocks due to 3rd party software we use that has a dependency on Ent. Lib 3.1.

To migrate to Ent. Lib 4.1 just change all references for 3.1 app blocks to 4.1 app blocks.
You will also be able to remove out the the ApplicationCode/CallHandlers/*.cs files and use the 4.1 PolicyInjection CallHandlers.

NOTE: Be sure to read the rest of this article by clicking the link below.

Read More…

Posted in .Net, C# at November 7th, 2008. 1 Comment.

Cohesion and Coupling

Remember taking Software Design 101 at University and hearing the terms Cohesion and Coupling being thrown about but were too hungover to pay attention?

Well this article by Jeremy Miller is an excellent introduction (or re-introduction) to Cohesion and Coupling – two terms I believe you need a strong comprehension of to design good software.

Posted in Development at November 4th, 2008. No Comments.

Reader challenge!

It’s been a while since we’ve had a reader question, so here’s one for you all. It’s not that I can’t solve this problem; it’s more that I’m wondering if there’s a more elegant solution.

The Problem: Given two dates, what’s the easiest way of determining if they fall in the same week?

Please submit your answers as a comment!

Posted in C#, Daily Question at November 3rd, 2008. 9 Comments.

Using Flagged Enums

Have you ever written or come across code where you have a series of boolean values that determine whether or not certain actions are allowed?

Example:


public class WorkDays
{
  public bool Sunday { get; set; }
  public bool Monday { get; set; }
  public bool Tuesday { get; set; }
  public bool Wednesday { get; set; }
  public bool Thursday { get; set; }
  public bool Friday { get; set; }
  public bool Saturday { get; set; }

  public bool Weekdays { get { return Monday && Tuesday && Wednesday && Thursday && Friday; } }
  public bool Weekends { get { return Sunday && Saturday; } }

  public int NumberOfDaysWorked
        {
            get
            {
                int numberOfDaysWorked = 0;

                if (CanWorkMonday) numberOfDaysWorked++;
                if (CanWorkTuesday) numberOfDaysWorked++;
                if (CanWorkWednesday) numberOfDaysWorked++;
                if (CanWorkThursday) numberOfDaysWorked++;
                if (CanWorkFriday) numberOfDaysWorked++;
                if (CanWorkSaturday) numberOfDaysWorked++;
                if (CanWorkSunday) numberOfDaysWorked++;

                return numberOfDaysWorked;
            }
        }
}

There’s a more elegant approach that is utilized through the standard .net framework that we too can mimic.

This scenario is a perfect candidate for using a flagged enum and the power of bit operations.



    [Flags]
    public enum Days
    {
        None = 0,
        Sunday = 1,
        Monday = 2,
        Tuesday = 4,
        Wednesday = 8,
        Thursday = 16,
        Friday = 32,
        Saturday = 64,
        MondayToFriday = Monday | Tuesday | Wednesday | Thursday | Friday,
        Weekend = Saturday | Sunday,
        All = MondayToFriday | Weekend,
    }

    public class WorkDays
    {
        public Days DaysWorked { get; set; }

        /// <summary>
        /// Get the Number of Days worked.
        /// NOTE: Uses bitwise and operation.
        /// </summary>
        public int NumberOfDaysWorked
        {
            get
            {
                Days days = DaysWorked;
                int numberOfDaysWorked = 0;
                for (; days != 0; numberOfDaysWorked++)
                {
                    days &= days - 1; // clear the least significant bit set
                }
                return numberOfDaysWorked;
            }
        }
    }

By defining an enum with each successive value a power of 2 greater (i.e. binary) you can then use the bitwise or (|) and bitwise (&) operations to group and determine which values are selected.


    [TestClass]
    public class ExampleTestClass
    {
        [TestMethod]
        public void Test()
        {
            var mondayToFriday = new WorkDays { DaysWorked = Days.MondayToFriday };
            Assert.IsFalse(Days.Sunday.In(mondayToFriday.DaysWorked));
            Assert.IsFalse(Days.Saturday.In(mondayToFriday.DaysWorked));
            Assert.IsTrue(Days.Wednesday.In(mondayToFriday.DaysWorked));
            Assert.AreEqual(5, mondayToFriday.NumberOfDaysWorked);

            var monday = new WorkDays { DaysWorked = Days.Monday };
            Assert.IsFalse(Days.Sunday.In(monday.DaysWorked));
            Assert.IsTrue(Days.Monday.In(monday.DaysWorked));
            Assert.AreEqual(1, monday.NumberOfDaysWorked);

            var mondayAndWednesday = new WorkDays { DaysWorked = Days.Monday | Days.Wednesday };
            Assert.IsFalse(Days.Tuesday.In(mondayAndWednesday.DaysWorked));
            Assert.IsTrue(Days.Monday.In(mondayAndWednesday.DaysWorked));
            Assert.IsTrue(Days.Wednesday.In(mondayAndWednesday.DaysWorked));
            Assert.AreEqual(2, mondayToFriday.NumberOfDaysWorked);

            var weekend = new WorkDays { DaysWorked = Days.Weekend};
            Assert.IsTrue(Days.Saturday.In(weekend.DaysWorked));
            Assert.IsTrue(Days.Sunday.In(weekend.DaysWorked));
            Assert.IsFalse(Days.MondayToFriday.In(weekend.DaysWorked));
            Assert.AreEqual(2, weekend.NumberOfDaysWorked);
        }
    }

    public static class Extensions
    {
        /// <summary>
        /// Is the specified enumeration value within the range of Enum values?
        /// </summary>
        /// <param name="value">the enum value to look for in the range</param>
        /// <param name="range">the range of enum values (eg. bitwise OR'd values)</param>
        /// <returns></returns>
        public static bool In(this Enum value, Enum range)
        {
            var valueNumber = (int) Enum.Parse(value.GetType(), value.ToString());
            var rangeNumber = (int) Enum.Parse(range.GetType(), range.ToString());
            return (valueNumber & rangeNumber) == valueNumber;
        }
    }

For further information check out the following resources:

If you’re gotten a bit rusty on your bitwise operations:
http://en.wikipedia.org/wiki/Bitwise_operation

Flagged Enum:
http://weblogs.asp.net/wim/archive/2004/04/07/109095.aspx

Posted in .Net, C# at November 2nd, 2008. 1 Comment.

Visual Studio 2008 – Shortcut Keys for running Unit Tests

Short Cut Keys to Run Tests:

• Ctl R, T: Run Tests in Current context (namespace, class, and method – ie. Based on where your cursor is within a file it determines the tests to run)
• Ctl R, C: Run Tests in Current Test Class
• Ctl R, N: Run Tests in Current Namespace
• Ctl R, S: Run All Tests in Solution
• Ctl R, D: Run the Tests in the Last Test Run
• Ctl R, F: Run the Failed Tests of the Last Test Run

Posted in .Net, C#, Development, Unit Testing at October 30th, 2008. 2 Comments.
Quickduck logo