News, code, articles, rants; a daily dose of programming rigmarole.

Saturday, October 6, 2007

Funny where life takes you

About 2 years ago, I was introduced to a website called 'Top Coder' by a guy I worked with. His words to me were "If you ever want to find out who the better programmer is, we can go here and compete". I was very intrigued, but we never did compete. From that point on, I regularly logged in to Top Coder's site and reviewed the available competitions. I thought to myself, "I wonder if I'm good enough to compete against people I don't know". I never did compete, only watching these competitions from a distance. One time I did download a distribution for a development competition that was in progress, but I just decided I hadn't the time to compete, so I didn't. Well, one day I get a call from some one at Top Coder, they were wondering what I was up to currently, as they liked my skillset and was wondering if I'd be interested in interviewing! I had just started a new gig somewhere else, and thought it best to wait it out a bit and see where that gig went.

For the unenlightened, Top Coder hosts the worlds best programming competitions in the world. They use this process to build great software. If you think you've got what it takes to compete, you should do so asap, because not only can you prove it, but you can make money doing it.

Anyway, I couldn't stop thinking about Top Coder, and the allure for working at Top Coder never waned. I went through the interview process, and with great avidity, I accepted an offer to join. My first day was officially October 1st, and I'm never looking back. The feeling I get from everybody so far is this is the best team I've ever joined. I've spent a few years contributing to open source software to build my skill set as a programmer, but after going through the interview process and competing for the first time recently, I now wish I had spent more time competing. That aside, here's to my joining a company I think has the best process in the industry, and a company I am super proud of being associated with.

Wednesday, August 29, 2007

Wow

It has been an extremely long time since I've posted on here, but I'm back in the saddle, and will be coming with some new posts very soon; keep checking back.

Thursday, February 22, 2007

Answer to What's Wrong With This Code

I can't believe it's Thursday already!! Yes, I forgot to post the answer to the previous problem yesterday, so here it is:

Looks like 3_4 on 7 got it right:

3_4 on 7 said...

I don't believe this would compile. I'm not sure what the output would be but, since C# does not support optional parameters, I believe you're required to supply a value for all of the parameters, including the optional parameters.

However, the VB developer in this instance should make sure that their code is never going to be in a library that is being used by another language as including a universally unsupported concept like optional parameters would be poor development practice.

C# does NOT (to my dismay and probably the dismay of many other developers) support optional parameters, therefore when referencing the code in C#, it would display the parameter list as having required parameters. See you next time!!

Monday, February 19, 2007

What's Wrong With This Code?

In this (hopefully) multi-part series, I will be presenting challenging (maybe to over-glorified web developers or egocentric re-implementers like previous developers I've worked with, you know who you are! =^) programming problems that readers can solve via comments, and I will respond either with the winning comment or just the answer because nobody responded, in which case I will cry.


What's Wrong With This Code?

Say you have the following VB code:

Public Class Adder
Public Shared Function Add( ByVal a As Integer, ByVal b As Integer, Optional ByVal c As Integer = 0) As Integer
Return a + b + c
End Function
End Class

Then you have the following C# code referencing the previous VB code:

public class AdderClient{
public static void CallAdder(){
Console.WriteLine(Adder.Add( 1, 2 ));
}
}

Will this compile? Why/why not? What would the output be?

The answer will come Wednesday!

Friday, February 16, 2007

Favorite UML Tool

I didn't post yesterday in this (psuedo) daily blog; I'm a baaaaad man!!

Anyway, I wanted to share what has become my official favorite UML/Design tool - Enterprise Architect.

As you know, I'm leaving my current post and moving on to new ventures, and it's been quite some time since I updated my UML diagrams with the code I've been working with. Well, I figured up Enterprise Architect, created a new project for each programming project I had been working on, and imported them into EA. This is where EA is absolutely awesome: it reverse-engineered all of my code and generated class diagrams! This feature alone must have saved me hours of work.

Also, a few months ago when I had started one of the projects I was working on, I fired up EA, and did a lot of visual design using UML models. EA also generated the code for me in my desired language (it currently supports enough language to be useable in almost any shop like Java, C#, Python, PHP, and more), and it allowed me to specify namespaces and other rules when code was generated (I used it for C#).

Check out Enterprise Architect, along with its sweet Visual Studio integration at http://www.sparxsystems.com/ea.htm.

Wednesday, February 14, 2007

Anonymous Methods - Perfect Stranger Or Close Relative?

Since most of the world (minus those currently under rocks or archaic cave dwellers) knows what anonymous methods are, I won't spend too much time analyzing them here. I did however come across something interesting when analyzing the IL of an assembly with a class that uses an anonymous method for sorting a collection. First we'll take a look at code and it's IL after compilation without an anonymous method, and then we'll try to put a face on the anonymity of anonymous methods.

Here's the code without anonymous methods:

using System;
using System.Collections.Generic;

public class SortMan{
public static void Main( string[] args ){
SortMan s = new SortMan();
s.Test_Sort();
}

public void Test_Sort(){
List dates = new List();

dates.Add( DateTime.Now );
dates.Add( DateTime.Now.AddDays( -30 ) );
dates.Add( DateTime.Now.AddDays( -120 ) );
dates.Add( DateTime.Now.AddDays( -5 ) );


/*delegate( DateTime d1, DateTime d2 ){

return d1.CompareTo( d2 );
}*/
dates.Sort( this.Sort );
}

private int Sort( DateTime d1, DateTime d2 ){
return d1.CompareTo( d2 );
}
}

And here's its IL (ildasm.exe):










Obviously our 'Sort' method is a member of our 'SortMan' class, just like any other method we would write in any other normal class. What about using an anonymous method?


Here's the code for our 'SortMan' class with an anonymous method:

using System;
using System.Collections.Generic;

public class SortMan{
public static void Main( string[] args ){
SortMan s = new SortMan();
s.Test_Sort();
}

public void Test_Sort(){
List dates = new List();

dates.Add( DateTime.Now );
dates.Add( DateTime.Now.AddDays( -30 ) );
dates.Add( DateTime.Now.AddDays( -120 ) );
dates.Add( DateTime.Now.AddDays( -5 ) );


dates.Sort( delegate( DateTime d1, DateTime d2 ){ return d1.CompareTo( d2 ); });
}
}

And finally here's the IL for this compiled assembly:








It's quite interesting to note that our "anonymous" method actually compiles as a static field in our SortMan class, with a local static method as its target! This "anonymity" appears to be nothing more than syntactical sugar to make it appear is if you don't really need a delegate instance, when in fact the compiler is creating a static delegate field variable for you, with a local static method as its target.

Anonymous methods make for clean syntax, but they are far from anonymous, and actually become a relative of the class they live inside.

Tuesday, February 13, 2007

Great Book

In this series of Great Book posts, I'll try to provide enough information that will hopefully deem a book worthy of reading or worthy of your campfire, including three rating systems: General Rating (*-***** - 1-5 stars), Preponderance (*-***** - 1-5 stars relative to other books that should be in your collection), and Skill Level (or target for what type of skill level you should have when reading this book; this rating will be taken directly from the book if it has one).


A great book I recently picked up was Applied Micorosft .NET Framework Programming, by Jeffrey Richter. This book dives deep into the .NET Framework (v. 1.0) and succinctly covers topics such as header information written into .NET Assemblies (which really drives a point made in Effective C# about small assemblies), type fundamentals like the difference between a primitive, value and reference type and the differences between an instance and type constructor, and many more low-level .NET Framework topics. Even though this book is based on a more archaic version of the .NET Framework, much of the information is applicable to .NET Framework programming today. It's definitely a must read for novice and expert alike.

General Rating: ****
Preponderance: ****
Skill Level: Novice->Expert

Monday, February 12, 2007

Demistifying Recursion

One of those "how deep does the rabbit hole go" issues you encounter along your programming journey can be recursion. At first it makes sense, then it's confusing, then it makes sense, then it ....

Moving on! I'll try to provide some of the basic things you'll need to be aware of when you think recursion is the way to go, as well as some pointers and caveats implementing recursion within the .NET Framework. We'll use C# as the language for this article.

Recursion Defined

Let's describe function recursion as simple as possible: say you have an arbitrary function (SimpleMindedAndDumbNonCoolNonRecursiveFunction(), or FunctionA()), and it has some complex calculation that it hands off to another arbitrary (this time recursive) function that performs this calculation recursively (WayCoolAndRockinRecursiveFunction(), or FunctionB()). FunctionB() performs this calculation by "recursing", or calling itself multiple times. Let's analyze a better example.

Recursion Analyzed
Say FunctionA() contains a binary tree that you would like to traverse in pre-order fashion. The only way to achieve pre-order tree traversal is to do so recursively. Let's look at the definition of our binary tree:

public class Node{
private Node left;
private Node right;
private int val;

public Node(){}

public Node( Node Left, Node Right, int Val ){
this.left = Left;
this.right = Right;
this.val = Val;
}

public Node Left{
get{
return this.left;
}
set{
this.left = value;
}
}

public Node Right{
get{
return this.right;
}
set{
this.right = value;
}
}

public int Value{
get{
return this.val;
}
set{
this.val = value;
}
}
}

And here's the code for FunctionA():

public void FunctionA(){
Node parentNode = new Node();
parentNode.Value = 1;

parentNode.Left = new Node();
parentNode.Left.Value = 2;

parentNode.Left.Left = new Node();
parentNode.Left.Left.Value = 3;

parentNode.Right = new Node();
parentNode.Right.Value = 4;
parentNode.Right.Right = new Node();
parentNode.Right.Right.Value = 5;
//you get the point ...

FunctionB( parentNode, 1 );
}

We can simply write code to traverse this binary tree that spans all levels of nodes without recursion. But that can only be done reliably (and IMHO very ugly) if all the levels of the tree are known. But what if we add more nodes? Or remove nodes? Writing code based on this assumption would be a great failure on our part. There is a better way. Enter Recursion:

private void FunctionB( Node parentNode, int counter ){
//This function walks a binary tree in pre-order fashion

Console.WriteLine( parentNode.Value );
Console.WriteLine( string.Concat( "Recursive calls so far: ", counter++ ) );

if ( parentNode.Left != null )
FunctionB( parentNode.Left, counter );
if ( parentNode.Right != null )
FunctionB( parentNode.Right, counter );
}

10 lines of elegant simplicity. Here's how this function works:

It gets called (originally by FunctionA, with a value of 0 for 'counter'), and the value of parentNode is written to the Console. Then FunctionB determines if the left and right nodes are null. If Left is not null, FunctionB calls FunctionB (itself), passing parentNode.Left as the argument. If Right is not null, FunctionB then calls FunctionB (itself) with parentNode.Right as the argument. The entire process starts all over, and the same code is excuted, as if parentNode were the first node in the tree, even though FunctionB at this point is processing parentNode.Left and parentNode.Right.

FunctionB basically does not "care" what node it is currently working on; only that it is a Node, and that the Node contains a Value, and optionally Left and Right nodes. This is happening 'recursively', because FunctionB is calling FunctionB is calling FunctionB (...) until the bottom-most node in the tree is reached, at which point the "bottom-most" call to FunctionB returns control to the previous FunctionB, all the way back up to the top.

Note: If too many recursive calls occur, an ugly 'System.StackOverflowException' will be thrown, because there will be too many function calls on the stack, so use recursion wisely.

Let's look at the output from the recursive call, perhaps this will shed some more light on what exactly is happening when the function calls are made.

1
Recursive calls so far: 1
2
Recursive calls so far: 2
3
Recursive calls so far: 3
4
Recursive calls so far: 2
5
Recursive calls so far: 3
Finished!

FunctionA calls FunctionB, with parentNode, and a value of 1 for counter (which gets printed first as the value for parentNode), then the current counter value is printed, to keep track of how many recursive calls we've made. You may notice that the amount of recursive calls follows the pattern 1->2->3->2->3. This is because 'counter', being incremented, is passed to the next call FunctionB along with parentNode.Left, then 'counter' is incremented again, and FunctionB is called with parentNode.Right. Since 'Right' is the last node on this path, control is returned, and 'counter's previous value (2) is back in place.

This is where recursion can be difficult to understand. Remember this rule of thumb: variables that have one value within a method body may have a different value at the same point in the same method body, when that variable's scope is within a recursive method. This is because when FunctionB is called again, this is a NEW method call, and when that method call is complete, the previous method call picks back up where it left off. FunctionB may as well have called FunctionC or even FunctionD.

As you can see though, the output of the current nodes value follows the pattern we set when we originally set up our tree, in FunctionA (parent=1, parentNode.Left=2, parentNode.Left.Left=3 etc.).

Another benefit of the recursive FunctionB is we can add or remove nodes on a whim, and FunctionB can handle this automatically without any code change whatsoever.

I hope this post has helped you obtain a better understanding of function recursion. Recursion is simple to implement, and can empower a developer to perform complex calculations with great ease, while maintaining a clean codebase, and minimalist class sizes.

Friday, February 9, 2007

How To Be A Great Programmer

When first starting out as a programmer, it can be quite difficult to discern what steps to take to grow your skills and flourish. This difficutly is compounded when working around others who have radical, pernicious ideas of how to write software. How does one overcome this? How can you continue to grow as a developer, even while working around others who can perpetuate bad habits? How can one identify when the ideas of those around them are actually "bad"?

Well, as it turns out, there's a method to the madness. In this multipart series, I plan on covering many steps to unravel the mystery behind becoming great, especially since it's really always a work in progress, and never a desitination (did I just say that greatness can never be achieved?). But in this particular post, we'll start with some of the more basic steps I took to help my skills flourish.

How To Choose A Language

The language you finally settle on dictates what path you should follow, but your choice of languages should start with a solid, low level language. I started with C (via K&R/CC classes). Learning C first laid an excellent foundation for what has so far become a great journey in the world of writing software. There is lot's of great software originally written (and still maintained) in C. If you're gonna learn C, make sure to have the K&R book handy (it was co-authored by the creator of the C language, Dennis Ritche, who is one of the greatest contributors to computing in general). Even if you've been a programmer for a number of years, and even if you have no use for C, learn it anyway.

Note: Whatever you do in software, it all comes down to one thing: hard work. If you're unwilling to put in the hard work necessary to be good at writing software, then you will waste the time and money of many people (including yourself). The hard work never really ends, and you must be able to persevere.

This is the path I chose when I decided I wanted to write software:
  • Learned C: I attended a class at my local CC, read K&R, and wrote as much code as I could.
  • Learned C++: I mostly read C++ Primer Plus (great book on C++), and wrote more code.
  • Learned VB6: I again attended a class at my local CC, and wrote more code still.
  • Learned C#: I started learning C# around the time I was attending classes for VB6, shortly before the .NETFX 1.0 was released (pre-beta+).
  • Learned Java: Because of my familiarity with C based languages, I figured I would have an easy time with this, and I did. Syntactically, Java is very similar to C# (some would say C# was derived from Java), and so for me Java was like learning European English while already knowing American (U.S.) English (in other words, a rather easy transition).
  • Learning(ed) Python: This is a work in progress, though I have written a calculator with some minor scientific calculations.
Currently, I work mostly in C# and .NET 2.0 professionally, with most free time spent in Python. A great book, Pragmatic Programmer, says you should learn one language every year; I tend to think this is great advice.

My next step was to join and actively participate in the Open Source community. I feel this was one of the best steps I ever made. My skills grew tremendously, as I was reading code written by others (two of the best I found in C# were the Jabber library for C# - jabber-net, and the MySQL .NET Connector), and I was writing code to be viewed by others (now the world is really watching!). I also participated in as many C# and Java forums as I could register for and still get work done throughout the day.


In my next post, I plan on discussing more about learning programming languages, as well as beginning discussion on more advanced topics, like design patterns, methodologies, and so on.