Wednesday, May 28, 2008

LINQing the Fibonacci Sequence

I've never been one for algorithms and/or academic type of questions/examples. However, while interviewing for my latest job I was asked to write code to generate the Fibonacci sequence... I struggled through it as much as my poor interviewing skills allowed. It was only my second job interview ever (for my second job ever) so I guess that means I'm batting a 1.000, even if I suck at interviewing ;)

Thinking of something to blog about tonight I figured I could make a FibonacciSequence generator that implemented IEnumerable just for shits and giggles (and I'll send the link to Johnny Mac for possible redemption).

There are a dozen ways to generate the sequence (albeit in the interview I could barely find one - lol), but I chose this way because it easily allowed for the "yield" keyword.

Also, then we can use LINQ over it... Our final code can do this:

//an enumerator over every Fibonacci
//number divisible by 3
var qry = (from ulong i
in new FibonacciSequence()
where i % 3 == 0
select i);


What's even better, is now I'm prepared for that next interview question, which could be "create an enumeration over a distinct ascending ordered list of every Fibonacci number divisible by 3 times every Fibonacci number divisible by 5 whose product is divisible by 17:

var qry = (from ulong i
in new FibonacciSequence()
from ulong j
in new FibonacciSequence()
where j % 5 == 0
&& i % 3 == 0
let res = (double)i*j
where res % 17 == 0
orderby res
select res).Distinct();


Amazingly, the above code will print out all elements of the enumeration in under 1 second.

And finally, here's the FibonacciSequence class.

public class FibonacciSequence : IEnumerable<ulong>
{

public IEnumerator<ulong> GetEnumerator()
{
yield return 0;
yield return 1;
ulong a = 0;
ulong b = 0;
ulong c = 1;
checked
{
while (true)
{
a = b;
b = c;
try
{
c = a + b;
}
catch (OverflowException)
{
yield break;
}
yield return c;
}
}
}

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


As a final disclaimer - yes, the ulong to double conversion in the first example does result in a loss of precision, so please don't comment on that.

Cheers!

Wednesday, May 21, 2008

Extension Methods

I've been having a good time with extension methods in C# 3.0 lately. You know, kids to bed, having a beer, reading digg.com and thinking, "What am I doing?!?! I wanna write some extension methods! Hell Yes!!!" </sarcasm>

If you don't know about, or understand extension methods - google it. This post is NOT for the beginning developer. I'm not providing complete examples that you can just pop in your code. You need to understand where to put these extension methods (in some static class in a special namespace that isn't ALWAYS included). I'm not catering to the script kiddies here (script kiddies: go back to the IRC #hak5 chat room please).

The first thing everyone seems to want to do is take all of the static methods from the static "Convert" class and apply them to the appropriate objects. Certainly a reasonable approach. However, instead of writing it all out, we can just codegen all of the methods. The Jedi is lazy - most of you know that already.
This code will popup a messagebox that you can copy the code for all 100+ (I'm not counting) conversion methods. The end result is that all primitives have a "ToWhatever()" method that makes it easy to do conversions.

static void Main()
{
StringBuilder code = new StringBuilder();
foreach (var m in typeof(Convert).GetMethods(
BindingFlags.Public |
BindingFlags.Static))
{
ParameterInfo[] parameters =
m.GetParameters();
code.AppendFormat("public static {0} {1}(",
m.ReturnParameter.ParameterType.Name,
m.Name);
bool first = true;
foreach (var p in parameters)
{
if (first)
{
code.Append("this ");
first = false;
}
code.AppendFormat("{0} {1}, ",
p.ParameterType.Name,
p.Name);
}
code.Remove(code.Length - 2, 2);
code.AppendFormat(") {{ return Convert.{0}(",
m.Name);
foreach (var p in m.GetParameters())
{
code.AppendFormat("{0}, ", p.Name);
}
code.Remove(code.Length - 2, 2);
code.Append("); }");
code.AppendLine();
}
MessageBox.Show(code.ToString());
}

Sweet... But, that code will throw on exceptions... What if we wanted a "TryParse" type of equivalent for every single one? Time for another approach.
All of these objects are IConvertible.... Hmmmm... how about this approach!

public static T To<T>(this IConvertible obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}

Sweet! Now we can do

int i = myString.To<int>();

So adding a couple helper methods is easy as pie.

public static T ToOrDefault<T>
(this IConvertible obj)
{
try
{
return To<T>(obj);
}
catch
{
return default(T);
}
}

public static bool ToOrDefault<T>
(this IConvertible obj,
out T newObj)
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = default(T);
return false;
}
}

public static T ToOrOther<T>
(this IConvertible obj,
T other)
{
try
{
return To<T>obj);
}
catch
{
return other;
}
}

public static bool ToOrOther<T>
(this IConvertible obj,
out T newObj,
T other)
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = other;
return false;
}
}

public static T ToOrNull<T>
(this IConvertible obj)
where T : class
{
try
{
return To<T>(obj);
}
catch
{
return null;
}
}

public static bool ToOrNull<T>
(this IConvertible obj,
out T newObj)
where T : class
{
try
{
newObj = To<T>(obj);
return true;
}
catch
{
newObj = null;
return false;
}
}

Now we can ask for default (calls blank constructor or "0" for numerics) on failure, specify a "default" value (I call it "other"), or ask for null (where T : class). I've also provided both silent exception models, and a typical TryParse model that returns a bool indicating the action taken, and an out param holds the new value.
So our code can do things like this

string a = myInt.ToOrDefault<string>();
//note type inference
DateTime d = myString.ToOrOther(DateTime.MAX_VALUE);
double d;
//note type inference
bool didItGiveDefault = myString.ToOrDefault(d);
string s = myDateTime.ToOrNull<string>();

Oddly type inference doesn't pickup on expected return types. I'd think it would. Thoughts?

So - I'd think that's about the best you can get. I couldn't get Nullable types to roll into the whole thing very cleanly. I tried for about 20 minutes before I threw in the towel.

Enjoy!

Wednesday, May 14, 2008

4 nasty C# 3.5 code "changes" for your last day at work

I recently left my job of over 8 years, and it got me to thinking about the fun I could have had with the millions of lines of code that I had access to. Of course, I didn't do any of these things (though I wish I had done some of the funny ones), and I won't be doing them in the future at my new job either. Let me clearly state that this post is meant to be read as humor. However, it is meant to be informative regarding .NET 3.5 / C# 3.0.

Leaving your job? Being laid off? Here's 4 fun/annoying/destructive things to leave behind!




4. Refactor random methods into operator overloads
(rated: annoying)


Find some methods throughout the code that match operator parameter lists and replace them with operator overloads.

Example:
change this:

public void MyMethod() 
{ 
    //does something 
}
into this:
public static int operator ~ (TheClass c) 
{ 
    //do the same thing referencing "c" instead of "this" 
}
or change this:
public string MyOtherMethod(string something)  
{  
    //does something  
}
into this:
public static string operator + (TheClass c, string something)  
{  
    //do the same thing referencing "c" instead of "this"  
}
Then go through all the broken code and adjust it to use the overloads instead of the methods. This would make the code TERRIBLY confusing!

I
magine seeing:
MyClass m = new MyClass();
~m;
string answer = m + "Jedi";
Greatest part about this annoyance is that "Find References" doesn't work on overloads, so beginner programmers are left stumped; Especially with the "~" overload as many people have never even seen that before outside of destructors!



3. Create Extension methods with hilarious names on base objects
rated: funny


Find some obscure cs file deep within the code, and add this at the bottom:


namespace System
{
    public static class HaHa
    {        public static void ThatsWhatYourMotherSaid(this object o)        {
        }    }}

Now every object in the entire codebase has a useless method called "ThatsWhatYourMotherSaid". Maybe I'm a geek, but that's hilarious. Note: this is easily findable with a "Go to definition" context option.
If you'd rather be annoying instead of funny, do the same thing, but write a program to generate code creating methods for every English word in the dictionary. That would render Intellisense useless - and possibly even cause major IDE slowdown (I didn't try!).

This works well because we put the class "HaHa" in the namespace "System". This namespace is included in every C# file ("using System;"), unless it's been strangely removed. Extension methods are only revealed on objects if the namespace in which they are defined is included (yeah, that's why you have "using System.Linq;" in your code!).




2. Create seemingly useful extension methods which do nothing, or worse...
rated: annoying at the least, possibly destructive

Once again, find some obscure file to hide this in. Similar to above, create an extension method but this time make it sound useful. New people, or beginners joining the project may think, "Wow! That's great!". Here's some examples I can think of:


namespace System
{    public static class HaHa
    {        public static bool EqualsCaseInsensitive(this string s1, string s2)        {
            return true;
        }        public static void ShowOnTop(this Form f)        {            f.Close();
        }
    }
}

Now your strings have a "EqualsCaseInsensitive" method which always returns true, and your forms have a "ShowOnTop" method that closes the form (which also calls Dispose() I believe)! Evil....



1. Replace a widely used core library class with a creatively destructive decorator class
rated: Extremely destructive

Creating a decorator (aka wrapper) class for a core framework class which has the exact same name will allow existing code to compile, but you gain control over it's behavior. The issue here is that if you define a class in local code under the same namespace as a framework class, it will be used instead of the framework class. Here's an INCOMPLETE example:



namespace System.Threading
{
    public class Thread
    {
        private global::System.Threading.Thread _wrappedThread;
        public Thread(ThreadStart start)        {            _wrappedThread = new global::System.Threading.Thread(start);        }
        .
        .
        .
        public void Start()
        {
            if (new Random().Next(1, 101) >= 99)
            {
                return;
            }
            else
            {
                _wrappedThread.Start();
            }
        }        .        .        .
    }
}

To make this example complete, you'd have to decorate every method, property, and event on the Thread class. Tedious, but not too bad with a program to generate the code. Note the usage of "global::" which makes it use the REAL Thread class.
Bottom line is, with the above example (if completed), you'd end up with System.Threading.Thread.Start() only starting 98% of the time. Now THAT is a bitch!

Cheers,
The Software Jedi