Monday, September 26, 2011

Convert from UTC Time to Local Time with C#

It's that time of the year again. Yes, it's time for my annual blog post. This one is just a blurb about converting from UTC to Local time on Windows. It's not straightforward so you might find this helpful.

public DateTime GetLocalTimeFromUTC(long theUTCTime = 1314163440)
{
 // Using parameter assignment I set theUTCTime to my birthday.
 // Notice: this UTC is in seconds, it's not from Windows

 // if UTC time is from Windows then you don't need this. .NET returns UTC in milliseconds.
 // If your UTC time comes from elsewhere you'll probably need to multiply by 1000 to get milliseconds theUTCTime *= 1000;

 // make a DateTime for the start of the UTC Epoch
 var aEpochStart = new DateTime(1970, 1, 1);

 // calculate a timespan utilizing windows-specific "ticks"
 var aTimeSpan = new TimeSpan(TimeSpan.TicksPerMillisecond * theUTCTime);

 // add the timespan to the start of the Epoch and you get your local time
 var aLocalTime = aEpochStart.Add(aTimeSpan);
 return aLocalTime;
}

Tuesday, September 14, 2010

Using the Tuple in C# and .NET 4

A new feature in C# for .NET 4 is the Tuple type.  A tuple, in C#, is a group of up to eight items of any type.



var aTuple = 
    new Tuple<string, DateTime>("This is a log entry", DateTime.Now);

I have found this to be a good, direct replacement for methods that take "out" parameters as arguments.  The following example shows a method that returns a list of messages and the total number of messages.

Example 1

public int GetMessages( out IList<string> Messages)
{
  Messages = new List<string>{"hello", "goodbye"};
return 2;
}

var aMessages = new List<string>();
var aCount = GetMessages(aMessages);
var aMessage = aMessages[0];

I prefer my code to be as direct as possible.  I can use a tuple to return multiple types and directly assign the results in my calling code.

Example 2
public Tuple<int, IList<string>> GetMessages()
{
  return new Tuple<int, IList<string>>(2, new List<string>{"hello", "goodbye"});}
}

var aMessages = GetMessages();
var aMessage = aMessages.Item2[0];     // Item2 is the second item in the tuple

Example 2 eliminates a degree of indirection that makes code harder to follow.  In Example 1 I have to infer how aMessages was populated by the program.  If I don't have source code for the GetMessages method in Example 1 that inference might take a little while to get.

For me, direct code is nicer because of its simplicity.  I like simple, direct code because it tends to reduce the number of defects in my projects.  The Tuple type helps me simplify my code and I will be using it from now on.



Wednesday, September 08, 2010

How I got out of spaghetti and in to a domain model

Refactor code to reveal a domain model

"Spaghetti Code" hides a domain model. In OOP a domain model refers to the conceptual model of a software system. A simple domain might be a model that represents a calculator. There will be classes that represent the buttons and their functions and a class that represents the display, etc...

Spaghetti code is often the product of rapid development. A first step to untangling your code is to begin refactoring a model from it. Try to find code that performs similar or duplicate functionality. This code is a candidate for refactoring. If it works on an object that appears to be fundamental to the character of your system then it should be reworked in to a domain model class.

Encapsulate at the module level

There is a boundary where objects that your code consumes should end and your domain objects begin. Sometimes this is called an anti-corruption layer. An anti-corruption layer is useful for minimizing your exposure to objects consumed from referenced modules. It provides a single point of failure and a convenient way to repair or extend the interface. You could merely build a "wrapper" class that provides a pass-through directly to the consumed object's properties and methods or you could be more creative.

If your model will be exposing classes to other consumers then make sure that the only classes you expose come from your domain. Exposing classes that are from a dependency of your model will give you what I call "dependency bleed-through". Not only is your model dependent on those classes but now any consumer of your model is dependent on the same module that your model is. Talk about untestable code...

Simplicity and Structure

In my opinion, a domain model should lack complexity. The interactions of the objects in the model should be direct. Using indirection, such as delegates and events, adds complexity and should be avoided unless necessary. This will help you and your team to understand your domain and will reduce the time it takes for new team members to come up to speed.

A glossary of terms used in the domain can be helpful, especially for interacting with non-technical personnel. Using the same terminology as someone that doesn't work directly with the code can increase the quality of your communication with them. There is no time wasted on trying to understand what one or the other is referring to in the system.

Unit test your model. Unit testing ought to be called unit building because Test Driven Development (TDD) leads to well defined components. Obviously you aren't doing pure TDD but writing tests for your new model gives you a good idea of the function/responsibility of each class.

At the end...

Once you've gotten your model out of your spaghetti you will have a system that is more maintainable than it ever was. You'll probably still have some spaghetti code leftover that needs to be refactored in to other parts of your architecure, maybe a Model and a View, but you're off to a good start.