In-place or operator methods?
Written by Ian Elliot   
Article Index
In-place or operator methods?
Solution

This particular C# puzzle is one of those that involves an error that no self respecting programmer would make... but are you so sure. If you use the DateTime class regularly then sure, you not only won't make the mistake you will spot the nature of the problem in no time at all.

On the other hand if you browse the .NET framework and only venture into DateTime when needed then it really is the sort of problem that occurs often and even repeatedly if you leave it long enough!

Background

Object-oriented programming is wonderful because objects can encapsulate the data and provide the methods to work with it. The methods are the verbs that do things to the objects and this is fine. There are some minor difficulties when more than one object is involved in an operation - then which object does the "verb" belong to? Even worse is when an operation is between objects of different types.

Now consider the DateTime object. It has an Add method which takes a TimeSpan object and adds the interval it represents to the current date and time stored in the DateTime object. It is a bit messy but it works and you very quickly get used to it.  For example:

DateTime t1 = DateTime.Now;
Console.WriteLine(
t1.Add(new TimeSpan(12, 0, 0)));

This creates a DateTime object with the current date time and then adds 12 hours to it as you can confirm if you examine the date printed. 

Yes it really is this simple.

Puzzle

As always with a puzzle the actual details of the code that caused the real problem have been reduced down to the very minimum necessary. This should allow you to see the problem more quickly and without any diversions to waste your time.

The program that caused the problem had a date stored in t1 and a date stored in EndDate and only if the end of the task was less than 12 hours away was it worth doing some thing. So the code came down to:

if(t1.Add(new TimeSpan(12,0,0))>EndDate){
Do something as the task nearly over
}

This code worked perfectly. Then a bright enthusiastic programmer decided to take the Add operation out of the if statement in an effort to "improve" the code. The result was:

t1.Add(new TimeSpan(12, 0, 0));
if(t1>EndDate){
Do something as the task nearly over
}

No error messages or warnings were produced but now the code didn't work. Even if t1 plus 12 hours was beyond the EndDate nothing ever got done!

Why?

And is there a fix?

Turn to the next page when you are ready to find out.

Banner

<ASIN:1449380344>

<ASIN:1430225378>
<ASIN:0470447613>

<ASIN:1933988924>

 



 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.