Archives for : September2008

Assert Yourself!

Java folks, please don’t get scared off by the C# examples, the contents of the post apply regardless if it is java or C#.

None of us use Asserts enough. It’s that simple, we don’t. Asserts are essentially a way to ensure we don’t get a value we shouldn’t have. The great thing about using asserts is that they aren’t included in final code (compiled in “Release”), only code complied with “Debug”. They make testing easier by verifying that when code is being tested in Debug that it doesn’t go beyond some condition. They can also be used to ensure when troubleshooting that you have the values you should.

Take a look at the code below:

private void pass_Click(object sender, RoutedEventArgs e)
{
    int temp = 1;
    Debug.Assert(temp > 0);
    MessageBox.Show(“Pass”);
}

private void fail_Click(object sender, RoutedEventArgs e)
{
    int temp = -1;
    Debug.Assert(temp > 0);
    MessageBox.Show(“Fail”);
} 

This is a sample of using an assert. I know the example is trivial but I wanted to show a simple use of it. These are simply a Click event on a “Pass” button and a Click event on a “Fail” button. I would recommend you create your own solution and put these on a pass and fail button so you can see and understand what happens when Debug.Assert is called.

Now lately I’ve been coming across a lot of code like (anonymous-ized for your protection):

else
{
    MessageBox.Show(“ERROR: YOU SHOULD NEVER SEE THIS MESSAGE.  Invalid TransformString!”, “SERIOUS ERROR occurred in MyClass:MyMethod”, MessageBoxButton.OK, MessageBoxImage.Error);
}

I’m sorry but this is simply wrong.

Code Complete 2nd edition has a great chapter on Assertions. The above example is exactly where asserts should be used.

Per the guidelines for “Using Assertions” (McConnnel, Code Complete 2, 2004) the following guidelines should apply for using assertions:

“Use error-handling code for conditions you expect to occur; use assertions for conditions that should never occur.

Avoid putting executable code into assertions.

Use assertions to document and verify preconditions and post conditions.

For highly robust code, assert and then handle the error anyway.”

That’s right. The very first usage guideline says to use asserts for conditions that should never occur.

Take a look at a sample from Code Complete (originally VB but I ported it to C#):

private double Velocity(double Latitude, double Longitude, double Elevation)
{
    //Verify preconditions
    Debug.Assert(Latitude >= -90 && Latitude <= 90, “Invalid Latitude”);
    
Debug.Assert(Longitude >= 0 && Longitude <= 360, “Invalid Longitude”);
    
Debug.Assert(Elevation >= -500 && Elevation <= 75000, “Invalid Elevation”);
    
    double velocity = 0;
    
/* DO THE WORK */    //Verify postconditions
    Debug.Assert(velocity >= 0 && velocity <= 600, 
                 
“Invalid Velocity”
                 
“Can’t seem to properly work the velocity formula”);
    
return velocity;
}

On this McConnell has to say:
“If the variables Latitude, Longitude, and Elevation were coming from an external source, invalid values should be checked and handled by error-handling code rather then by assertions. If the variables are coming from a trusted, internal source, however, and the routine’s design is based on the assumption that these values will be withn their valid ranges, then assertions are appropriate.” (McConnell, 2004)

Now assertions aren’t the end-all, be-all of validating values. Chances are that in most cases you are still going to want to validate and do error checking. But they’re a good start.

And just for the java folks that hung around, an assert in java:

//Check to make sure we’re not going to do a divide by zero
assert denominator != 0: “denominator is 0”;

Refs:

Code Complete (Second Edition), Microsoft Press, Steve McConnell, 2004

C# Online.NET – Assert

Debug.Assert Method

And just for the java folks:
Programming With Assertions

First in a series of many

I ‘ve been trying to come up with things that lead to a series of follows up stuff.  This way I don’t have to think too hard about coming up with subjects 🙂 and it makes writing them easier since I don’t have to spend so much time in general on them.  And now from:

http://www.ayende.com/Blog/archive/2008/08/27/What-I-am-working-on.aspx

Oren is his name and he is one of the bloggers I follow pretty close.  He’s been doing some pretty incredible stuff with a product he helped write called “Rhino Mocks” that allows you to create mock objects for testing and to set test conditions on those objects (ok, there’s a lot more but that scratches the surface) and in general he’s a pretty incredible coder.

Well, recently he posted some code that seems essentially how not to develop software with so many bad coding standards it would keep me busy for awhile.  Take a look at the below code:

public class TaxCalculator
{
private string conStr;
private DataSet rates;

public TaxCalculator(string conStr)
{
this.conStr = conStr;
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(“SELECT * FROM tblTxRtes“, con))
{
rates = new DataSet();
new SqlDataAdapter(cmd).Fill(rates);
Log.Write(“Read ” + rates.Tables[0].Rows.Count +
rates from database“);
if (rates.Tables[0].Rows.Count == 0)
{
MailMessage msg = new MailMessage(“important@legacy.org“, “joe@legacy.com“);
msg.Subject = “NO RATES IN DATABASE!!!!!“;
msg.Priority = MailPriority.High;
new SmtpClient(“mail.legacy.com“, 9089).Send(msg);
Log.Write(“No rates for taxes found in ” + conStr);
throw new ApplicationException(“No rates, Joe forgot to load the rates AGAIN!“);
}
}
}
}

public bool Process(XmlDocument transaction)
{
try
{
Hashtable tx2tot = new Hashtable();
foreach (XmlNode o in transaction.FirstChild.ChildNodes)
{
restart:
if (o.Attributes[“type“].Value == “2“)
{
Log.Write(“Type two transaction processing“);
decimal total = decimal.Parse(o.Attributes[“tot“].Value);
XmlAttribute attribute = transaction.CreateAttribute(“tax“);
decimal r = -1;
foreach (DataRow dataRow in rates.Tables[0].Rows)
{
if ((string)dataRow[2] == o.SelectSingleNode(“//cust-details/state“).Value)
{
r = decimal.Parse(dataRow[2].ToString());
}
}
Log.Write(“Rate calculated and is: ” + r);
o.Attributes.Append(attribute);
if (r == -1)
{
MailMessage msg = new MailMessage(“important@legacy.org“, “joe@legacy.com“);
msg.Subject = “NO RATES FOR ” + o.SelectSingleNode(“//cust-details/state“).Value + “ TRANSACTION !!!!ABORTED!!!!“;
msg.Priority = MailPriority.High;
new SmtpClient(“mail.legacy.com“, 9089).Send(msg);
Log.Write(“No rate for transaction in tranasction state“);
throw new ApplicationException(“No rates, Joe forgot to load the rates AGAIN!“);
}
tx2tot.Add(o.Attributes[“id“], total * r);
attribute.Value = (total * r).ToString();
}
else if (o.Attributes[“type“].Value == “1“)
{
//2006-05-02 just need to do the calc
decimal total = 0;
foreach (XmlNode i in o.ChildNodes)
{
total += ProductPriceByNode(i);
}
try
{
// 2007-02-19 not so simple, TX has different rule
if (o.SelectSingleNode(“//cust-details/state“).Value == “TX“)
{
total *= (decimal)1.02;
}
}
catch (NullReferenceException)
{
XmlElement element = transaction.CreateElement(“state“);
element.Value = “NJ“;
o.SelectSingleNode(“//cust-details“).AppendChild(element);
}
XmlAttribute attribute = transaction.CreateAttribute(“tax“);
decimal r = -1;
foreach (DataRow dataRow in rates.Tables[0].Rows)
{
if ((string)dataRow[2] == o.SelectSingleNode(“//cust-details/state“).Value)
{
r = decimal.Parse(dataRow[2].ToString());
}
}
if (r == -1)
{
MailMessage msg = new MailMessage(“important@legacy.org“, “joe@legacy.com“);
msg.Subject = “NO RATES FOR ” + o.SelectSingleNode(“//cust-details/state“).Value + “ TRANSACTION !!!!ABORTED!!!!“;
msg.Priority = MailPriority.High;
new SmtpClient(“mail.legacy.com“, 9089).Send(msg);
throw new ApplicationException(“No rates, Joe forgot to load the rates AGAIN!“);
}
attribute.Value = (total * r).ToString();
tx2tot.Add(o.Attributes[“id“], total * r);
o.Attributes.Append(attribute);
}
else if (o.Attributes[“type“].Value == “@“)
{
o.Attributes[“type“].Value = “2“;
goto restart;
// 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to
// fix this because they won’t until sep-07
}
else
{
throw new Exception(“UNKNOWN TX TYPE“);
}
}
SqlConnection con2 = new SqlConnection(conStr);
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con2;
con2.Open();
foreach (DictionaryEntry d in tx2tot)
{
cmd2.CommandText = “usp_TrackTxNew“;
cmd2.Parameters.Add(“cid“, transaction.SelectSingleNode(“//cust-details/@id“).Value);
cmd2.Parameters.Add(“tx“, d.Key);
cmd2.Parameters.Add(“tot“, d.Value);
cmd2.ExecuteNonQuery();
}
con2.Close();
}
catch (Exception e)
{
if (e.Message == “UNKNOWN TX TYPE“)
{
return false;
}
throw e;
}
return true;
}

private decimal ProductPriceByNode(XmlNode item)
{
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(“SELECT * FROM tblProducts WHERE pid=” + item.Attributes[“id“], con))
{
DataSet set = new DataSet();
new SqlDataAdapter(cmd).Fill(set);
return (decimal)set.Tables[0].Rows[0][4];

}
}
}
}

If this code doesn’t make you shudder I worry about you and suspect you shouldn’t be working as a computer programmer.
Over the course of the next few weeks, along with my posts on LINQ I want to spend some time analyzing what is wrong with this and help to try to define some of the established coding standards with .Net as well as coding in general.

Let’s start with the obvious.  We all know I am anti-goto, with good reason.  There is really no place in any modern high-level language for gotos.  Look at this:

else if (o.Attributes[“type“].Value == “@“)
{
        o.Attributes[“type“].Value = “2“;
        goto
restart;
        // 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to
        // fix this because they won’t until sep-07

}

Okay, if you look at the flow of the foreach this is in this else/if and breaks the flow of the code sending the execution back up to the top in mid-loop restarting everything over again. 

But Brian, this had to be done, don’t you see the comments?

No my young padawan, it doesn’t.  I’m not saying the fix for this shouldn’t be in place, what I’m saying is that the goto shouldn’t be there.  If the original programmer thought about this a bit more he would have seen that if he simply put the statement at the beginning of the foreach as an if statement like:

if (o.Attributes[“type“].Value == “@“)
{
        o.Attributes[“type“].Value = “2“;
        // 2007-04-30 some bastard from northwind made a mistake and they have 3 months release cycle, so we have to
        // fix this because they won’t until sep-07

}

 it would have had the same effect without needing the goto.

But Brian, by putting it later in the code then most of the time you will be able to try and capture the ifs earlier and then you won’t have to do a compare on every row for “@”. 

So what?  How do you know that every row won’t have the “@” for the value?  In that case you actually hurt your code execution by not putting the if at the beginning of the foreach loop.  Plain and simple gotos hurt code (see my earlier post on gotos with references on such).  The studies have been done and there are no reason for them in a modern language.

On to the next point of the code:

MailMessage msg = new MailMessage(“important@legacy.org“, “joe@legacy.com“);

Well, what’s wrong with this? 

What if Joe quits the company?  What if Important quits the company?  These values should not be embedded in the code. 

But Brian, Important is a not person you silly guy! It’s a mailing group.

Wow, sarcasm is not lost on you.

In modern .Net applications you have the Settings.  This allows you to store values in an easy to use xml file.  To get the values back out you don’t have to even do any special parsing, you just do (assuming you named your settings “MySettings”):

MailMessage msg = new MailMessage(MySettings.WhoToSendEmailTo);

That’s right.  When you add settings to your application you can then simply refer to the values in them directly as a property of the static Settings object in your project.  Then, in the future if Joe or Important should no longer get the emails then you simply modify the xml file in the application directory (or use the Visual Studio settings editor) and change who it should go to.  No need to recompile.  It’s that simple.  To add a settings, right click on the project name, select “Add New” and click on Settings file.  Name it as you like and Visual Studio will open a settings editor where you can add these properties and values.

Brian, you’re a dumb ass.  I tried this.  My application spans multiple projects and the settings file is only scoped at the project level.

Fine, if you want to be that way be that way.  Don’t use the settings features built in to the framework.  But whatever you do don’t embed this stuff into the application code.  If your smart and have been using a data access layer (DAL) like nhibernate or netTiers then getting and storing these values in the database should be trivial.  While up front it’s a bit more of a pain, on the back end it is easier because then for each instance of your application running you don’t have to modify the settings file and deploy to each application.  You just get the values out of the database.

Well, that’s it for now.  Hopefully you all might be interested in this and if you aren’t you’ll still be getting the code.  Doing a series like this is easy for me and allows me more time to do real work so there 🙂

Next time we’ll look at DALs and refactoring.

Later ‘yall,
Brian

The labmda says, “baaaaa”

 LINQ allows you do define simple functions/methods in-line with the query you are doing.  These are called lambda expressions.

They have a special format to allow for in-line expressions.  

Take a look at:

c => c + 1

Basically this is:
for each value c give me c + 1

Rather then complicating things with full-blown LINQ queries lets cheat and just use simple arrays.  For example:

int[] myInts = { 1, 9, 2, 8, 3, 7, 4, 6, 5 };
var largeInts = myInts.Where(x => x > 5);

The where clause requires a lambda expression that returns a boolean.  Here we’re saying:

for each value x give me values where x > 5

Um, Brian, I have graduated college, this is kindergarten stuff.

Fine, lets go a bit more complicated:

string[] digits = { “zero”, “one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine” };
var shortDigits = digits.Where((digit, index) => digit.Length < index);

That’s two, yes, two variables here. If you haven’t realized by now LINQ is really syntactic sugar.  When using arrays with LINQ, since all it is really going to do is just iterate over the values for you, you have access to an index variable that represents the index of where the query is.

Here it is saying
for each digit and its corresponding index give me the values where the length of the digit string is less then the index

meaning shortDigits ends up having the values:

{ “five”, “six”, “seven”, “eight”, “nine” }

Now, before we go too far I need to take a step back and clarify something from the last post.  Remember I gave a basic LINQ statement as:

var sortedFiles = from file in files orderby file.LastWriteTime descending select file;

and then went on to say:

from file in files

basically for each file in our files list

orderby file.LastWriteTime

LastWriteTime is a property on FileInfo.  files is a list of FileInfo, therefore each file is a FileInfo object.  Intelli-sense is fully supported here so when you type in file and put the dot is shows you all the properties on file as if it were a standardly declared FileInfo.

descending

Like a standard DESC to an orderby clause.  Like sql it implicitly orders by ASC so if you want descending you have to add it.

select file

return the file that applies to the orderby clause.  This may seem a bit redundant and I would agree but it is still needed.

Okay, now that you have read this for a second time I really want to address that last section.  It is only redundant when you want the full object available in the list.  If all I wanted was a list of file names I would do:

var sortedFiles = from file in files orderby file.LastWriteTime descending select file.Name;

Yes, you can return a single property from the object.

BUT WAIT, THERE’S MORE!

Yes, Ron Popeil here with the amazing Create-The-Object-On-The-Fly ability of LINQ and the 3.5 framework.

That’s right, Set It and Forget it! and it will generate types ON THE FLY!!!

Say I not only want the file name but also want the time when the file was created (CreationTime).  Well, just add that to your LINQ and now you have an IEnumerable with two properties:

var sortedFiles = from file in files orderby file.LastWriteTime descending select new { file.Name, file.CreationTime };

Yes, here you can see the real power of the var.  sortedFiles is now a list consisting of some object (really a System.Linq.Enumerable.SelectIterator<System.IO.FileInfo,<string,System.DateTime>> object) that has the properties Name and CreationTime.  This ability is called Anonymous Types.

Taking this idea one step further, remember that a LINQ query is really just SQL you can put in your code to enumerate over lists.

That’s it Brian, your f-in with me!

Yes, yes I am.

Wow, deja vu.

As you have seen the ability to create anonymous types on the fly as well as using lambda expressions aren’t really just simply enumerating over a list.  But back to the sql idea.  Let’s do a join in a LINQ query.

Say we have a Product class that looks like:

public class Product
{
    public int ProductId;
    public string Name;
}

and an Inventory class that looks like:

public class Inventory
{
    public int InventoryId;
    public int ProductId;
    public int NumberOnHand;
}

now take a look at this:

List<Inventory> InventoryList = new List<Inventory>();
InventoryList.Add(new Inventory { ProductId = 1, NumberOnHand = 3 });
InventoryList.Add(new Inventory { ProductId = 2, NumberOnHand = 0 });

List<Product> ProductList = new List<Product>();
ProductList.Add(new Product { ProductId = 1, Name = “Apple” });
ProductList.Add(new Product { ProductId = 2, Name = “Orange” });
  
var ProductsInInventory = from InventoryItem in InventoryList
                 join ProductItem in ProductList
                                   on InventoryItem.ProductId equals ProductItem.ProductId
                 where InventoryItem.NumberOnHand > 0
                 select new { ProductItem.Name, InventoryItem.NumberOnHand };

But Brian, that’s not how it’s done in SQL.  

Well, really inner voice?  Like I’ve never done SQL before.

Wasn’t the medication supposed to stop you from hearing me?  ‘Cause it doesn’t seem to be doing a great job.

Oh that?  Stopped takin’ it.  Figured without my inner voice I was just talking to myself.

But yes, Inner Voice is correct, that is not how it’s done.  But I did say that LINQ was like sql, not exactly sql.

The way a join is done is a bit different then in SQL when doing an implicit inner join but it is still pretty simple and actually very similar to doing an explicit inner join.  We just get so used to doing implicit joins we forget about explicit joins.  Once again, things are done in LINQ to facilitate the compiler optimizations and Intelli-sense.

Well, now your foot is wet and I’ve taken you a bit further into the world of LINQ.  Next on the topic is more on lambda expressions and other types of joins.

Later ‘yall,
Brian (and his inner voice)

Hug a coder

Funny stuff, 🙂

Tiptoe Through the Tulips … LINQeses…es

As most can attest when launching into the world of WPF you have to jump in and hope you can figure out how to swim before you drown.  It has a huge learning curve but the end results are usually pretty amazing.

LINQ, on the other hand, you can slowly dip a toe in, see how tepid the water is, and then slowly immerse your whole body sliding into the warm 98 degree water.  Over the course of 7 months now I have been slowing dipping into the water called LINQ and wanted to give you a few examples where I found it particularly useful.  Unlike a cruel father I will not throw you into the water and hope you can swim but want to slowly lead you into the fold.

So what the hell is LINQ?  Well, it stands for Language INtegrated Query.  It is a way to query lists in code.  Really that’s it.  You’re f-in me Brian, aren’t you?  Yes, yes I am.  That is the fundamental idea behind LINQ but it can do so much more.

I suppose I should start with the var keyword.  You VB fans will cheer at this.  var is a variable declaration where the type of the variable is implicit in the constructor of the item being created.  This is similar to the Dim except that we are still statically typed here.  In .Net 3.5 the var keyword can be used anywhere you are defining a variable that the type can be implied.

Good Examples:

var myInt = 3;
var myDouble = 2.2;
var files = new List<FileInfo>();

Bad Examples:

var myDouble = 3;//not a double and myDouble will actually be an int
var myString = null;//type cannot be implied, will result in compile error

The easiest use for LINQ is in sorting.  No more needing to define an IComparable, just define your sort in an orderby clause.  LINQ has some similarities to writing SQL except that in order to facilitate compilation and intelli-sense the order of the query is a bit different.

Take this code for example:

//START CODE
var files = new List<FileInfo>();
var ArchiveDirectory = "C:Archive";
var archivedFiles = Directory.GetFiles(ArchiveDirectory);//will be of type string []
foreach (var filePath in archivedFiles)
{
    var fi = new FileInfo(filePath);
    files.Add(fi);
}
//now sort the file list based on last write time
var sortedFiles = from file in files orderby file.LastWriteTime descending select file;
//END CODE

Now, up until that last line it is standard C#.  The last line appears to be some sort of odd jacked-up sql.  If we break it down, however, you will see the power.

from file in files

basically for each file in our files list

orderby file.LastWriteTime

LastWriteTime is a property on FileInfo.  files is a list of FileInfo, therefore each file is a FileInfo object.  Intelli-sense is fully supported here so when you type in file and put the dot it shows you all the properties on file as if it were a standardly declared FileInfo.

descending

Like a standard DESC to an orderby clause.  Like sql it implicitly orders by ASC so if you want descending you have to add it.

select file

return the file that applies to the orderby clause.  The may seem a bit redundant and I would agree but it is still needed.

See?  Pretty simple.  No need to write an IComparable just order the list by the LastWriteTime.

So let’s take this a step further.

I have an example where I have three different tables all of which have the property “Name”.  I need to populate three different combo boxes with the values from each of the different tables.  Now I could write a whole bunch of code to do each table values and combo boxes separately but, well, nah!

Here we’re going to go a bit extreme.  Use a bit of LINQ, throw in some Generics and finally whip it all together with some Reflection.

Start with getting each list and ordering it by name

//START CODE
var sortedTypes = from type in new TypeService().GetAll() orderby type.Name select type;
var sortedFreqs = from freq in new FrequencyService().GetAll() orderby freq.Name select freq;
var sortedEvents = from event in new EventService().GetAll() orderby event.Name select event;
//END CODE

Well, that should be pretty straight forward now.  We can see the GetAll method of each service returns all the values from a table in the form of a list.  The we use the orderby clause in LINQ to sort it for us by the name.

Now let’s populate the combo boxes in the form:

//START CODE
PopulateComboBox<Type>(sortedTypes, cboType);
PopulateComboBox<Frequency>(sortedFreqs, cboFrequency);
PopulateComboBox<Event>(sortedEvents, cboEvent);
//END CODE

And thats all there is.  Pretty simple, huh?
Oh, you want to see what the hell PopulateComboBox does.  Fine, be that way.

//START CODE
private void PopulateComboBox<T>(System.Linq.IOrderedEnumerable<T> List, ComboBox Box)
{
    foreach (T val in List)
    {
        ComboBoxItem cbi = new ComboBoxItem
            {
                Content = FindReflectedProperty(val, "Name"),
                Tag = val
            };
        Box.Items.Add(cbi);
    }
}
//END CODE

As you can see we can’t take a var on the first value of the parameter since it’s type cannot be inferred.  As it would happen using the orderby clause in a LINQ query returns a list with the interface System.Linq.IOrderedEnumerable.  We use the good ole’ generics typeparam when calling the method so at runtime the code knows the type of T.  Additionally you can see that when creating the ComboBoxItem we use the new feature in 3.5 of setting properties on the objects when creating the object (really this happens right after the constructor is called).  The final bit to this is FindReflectedProperty.

//START CODE
public static object FindReflectedProperty(object Instance, string PropName)
{
    if (Instance == null)
        return null;
    foreach (PropertyInfo pi in Instance.GetType().GetProperties())
    {
        if (pi.Name == PropName)
            return pi.GetValue(Instance, null);
    }
    return null;
}
//END CODE

Getting the PropertyInfo on the instance passed in we are able to get the value of the property based on the property name.  Of course we can turn this method into more LINQ but I’ll leave that to the next in the series where we’ll dip our whole foot in, which should excite all you foot appreciators (or fetishes or whatever).  If you want to read ahead google LINQ Lambda.

And now your toe is wet, assuming you got this far.

Later ‘yall,
Brian

GoTo: goto GoTo;

Recently while looking over the shoulder’s of some fellow devs I was witness to something disturbing.  If you haven’t guessed by now it was a goto statement.  An intern we used to have had used gotos in a switch(case) statement since in C# switch(case) doesn’t allow fall-through.

You have to do:

int shippingOption = getShippingOption();
switch(shippingOption)       
      {         
         case 1:   
            cost += 25;
            goto case 2;                 
         case 2:            
            cost += 25;
            goto case 3;           
         case 3:            
            cost += 50;
            break;       
         default:            
            Console.WriteLine("Please select 1, 2, or 3.");            
            break;      
       }

I have to admit that this is the only situation where I feel gotos should be allowed.  The problem with the code that they were looking at looked more like:

switch (n)
    {
    case StaticVar1:
        if (statusVariable == 0)
        goto StaticVar3;
        statusVariable = 9;
        DoSomething();
        if (statusVariable == 3)
        goto StaticVar2;
    case StaticVar2:
        if (statusVariable == 0)
        goto StaticVar3;
        statusVariable = DoSomething2();
        goto StaticVar1;
    case StaticVar3:
        if (statusVariable == 0)
        break;
        statusVariable = DoSomething3();
        if (statusVariable == 2)
        goto StaticVar2;
...insert a whole bunch more...
    default:
        break;
    }

    
which really had more like 10 different cases.  The problem is that he wasn’t using the gotos to do fall-through.  He was using them like your classic old VB days of gotos.  

Hopefully we all know who Dijkstra is.  Dijkstra is well-known for two things in his career as a computer scientist.  The first thing, of course, is Dijkstra’s algorithm for best pathing.  If you have ever had to implement a best path algorithm Dijkstra’s is simple to do, pretty straight forward and it works.  Of course since he created it back in the 60’s others have come out that improve on his best path algorithm but still at the core of the improved algorithms are Dijkstra’s algorithm.  I mean, come on, he has an algorithm named after him, wouldn’t that be cool?  Anyways, the second thing he is known for is his article “Go To Statement Considered Harmful” in the March 1968 Communications of the ACM.

“Dijkstra observed that the quality of code was inversely proportional to the number of gotos the programmer used.” (McConnell, 2004)  

So what?  The code works.  

Well, not really.  As McConnell says above, speaking on Dijkstra’s article, the quality of the code was inversely proportional to the number of gotos.  That’s right, more bugs, harder to troubleshoot, harder to maintain.

Additionally gotos break the fundamental concept of software development that code within a method (procedure, function) flows from top to bottom.

Fine Brian, I still don’t believe you and you suck.  I mean how are we supposed to handle OnError in VB.Net?

Um, by following the preferred methods of handling exceptions as outlined in:
http://msdn.microsoft.com/en-us/library/aa289194.aspx
which is an article entitled “Life Without On Error Goto Statements”

Well, fine but goto statements allow for faster and cleaner code.

Um, no it doesn’t.

“Goto statements break the flow of code tending to thwart compiler optimization actually leading to slower executing code” (McConnell, 2004)

Now, a follow up letter to the ACM was published in March of 1987 (yeah, 20 years later) entitled “‘GOTO Considered Harmful’ Considered Harmful” by Frank Rubin, in which the he gave what he considered the seminal example for goto statements, when gotos should be used and the advantage they gave.  The letter was followed by over 50 responses, some of which supported Frank but quite a few gave samples where his goto example would be better served as a method call or some other preferred way other then a goto.

I have looked at millions upon millions of lines of code, most of which is other people’s code.  It truly is a great learning experience.  The example at the top for fall-through are the only time I’ve seen that gotos might be used.  Even in the example at the top the goto’s really aren’t needed and be worked another way.

I could spend sometime analyzing all the arguments for gotos but unfortunately I don’t have that time.  Studies show goto statements hurt code.  That’s all there is.  Want to get out of deeply nested loops?  Use status variables instead of gotos.  Want to move within a switch(case)?  Don’t.  It’s bad programming and can be done with a small bit of code duplication that will end up saving cycles in compiler optimization and code maintenance.  Sure you save a few seconds coding but in reality you’re costing yourself and/or your organization a lot more in maintenance.

If you’re used to using gotos help out your fellow man (or maintenance programmer) and spend a few more minutes working without gotos.

We all will thank you.

Every time you forward this to someone a kitten won’t get kicked.  Think of the kittens.

Brian

Refs (Additional Reading):
Code Complete (Second Edition), Microsoft Press, Steve McConnell, 2004

Life Without On Error Goto Statements, Deborah Kurata, July 11, 2003
http://msdn.microsoft.com/en-us/library/aa289194.aspx

I’d Consider That Harmful, Too, Jeff Atwood, October 25, 2007
http://www.codinghorror.com/blog/archives/000982.html

goto (C# Reference), November 2007
http://msdn.microsoft.com/en-us/library/13940fs2.aspx

Go To Statement Considered Harmful (see also A Case against the GO TO Statement), E.W. Dijkstra
Association for Computing Machinery (ACM), Communications of the ACM, March 1968

WPF – ContentProperty, it’s that simple

So there I am, creating a custom control called “RequiredLabel” that
interestingly enough is a label that has a cool icon in it to show that
whatever it is being used for is required. The control has two
properties, Text that is the text of the label and Style that is the
style of the label. Both are registered as dependency properties so
that they can be set in the xaml. I suppose it would have been fine to
simply leave good enough as good enough but I wanted it so that in the
xaml you can put the text for the label between the start and end tag
for required label. It is simply expected behavior the the content of
your control can be put in that way.

After much soul searching (i.e. Googling) I still couldn’t find the
answer. How do I make one of my dependency properties the content that
is between the tags? Well, thankfully I had an epiphany and remembered
that somewhere deep in one of my WPF books the answer was held. It is
as simple as putting the attribute above the class declaration with the
dependency property name.

[ContentProperty("Text")]
public partial class RequiredLabel : UserControl
{
    //see full code below
}

This makes it so that when I use my custom control it will look like:

<customControls:RequiredLabel x:Name="lblType" Style="{StaticResource LabelGradient}">
    Defendant's Name:
</customControls:RequiredLabel>

It also makes it so that if I decide to extend the content to support
user controls instead of just text really easy since I can switch out
the TextBlock that makes up the user control to a panel.

Also if you want to get a glimmer of using dependency properties see
attached code.

RequiredLabel.zip

Brian

WPF and Silverlight

 Check out the link below.  It is a bunch of tutorials on everything you could want to know about Silverlight plus a whole bunch of cool WPF stuff.

http://channel9.msdn.com/posts/Dan/Mike-Taulty-44-Silverlight-20-Screencasts/

WPF and MousePosition

The way I thought it should be done (but it’s wrong):

Point mousePoint = Mouse.GetPosition(this);
MyWindow win = new MyWindow();
win.Left = mousePoint.X;
win.Top = mousePoint.Y;
win.ShowDialog();

“Mama Freeda! Dang window won’t go where I put it!”

Okay, maybe I didn’t say “Mama Freeda” nor “Dang” but none the less it
seems like when getting a mouse position in WPF and trying to open a new
window relative to the mouse click is a pain.

Ah Luigi, but I have the solution 🙂

When setting the left and top properties in a wpf window they relate to
the desktop coordinates. The new window could careless that it’s being
popped up from a control underneath it.

The problem is that Mouse.GetPosition(this) returns the position
relative to the “this” which is most likely the control that is trying
to open the new window. Now if the control is the only control in the
window, there is only one screen, the application is running on the
primary screen and the application is maximized then your golden.

But screw that.

Well, how about using Mouse.GetPosition(Window.GetWindow(this))?

That returns the point relative to the window of the control (this).
That should work won’t it? That only eliminates a single concern of
ours, if the control is the only control in the window. There is still
that the application must be only one screen, the application is running
on the primary screen and the application must be maximized.

Brian, cut the Brother Stuart and just give us the simple answer!

Um, who’s Brother Stuart?

And why am I talking to myself like this?

The great thing about wpf controls is that they have the ability given a
point to convert that point to screen (i.e. desktop) coordinates.

So here is easy answer (The way it should be done):

Point mousePoint = this.PointToScreen(Mouse.GetPosition(this));
MyWindow win = new MyWindow();
win.Left = mousePoint.X;
win.Top = mousePoint.Y;
win.ShowDialog();

Basically get the mouse position relative to this control and then
convert it out to the desktop coordinates so I can then use it when
setting the left and top properties of a new window. This is great for
pop-up windows that need to be close to a mouse click. The great thing
about this is that since the mouse click position is now relative to the
desktop this works on multi-screen monitors regardless of which monitor
you have the application running on.

Later ‘yall,
Brian

ref:
Visual.PointToScreen
http://msdn.microsoft.com/en-us/library/system.windows.media.visual.pointtoscreen.aspx
Mouse.GetPosition
http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.getposition.aspx
Window.Top
http://msdn.microsoft.com/en-us/library/system.windows.window.top.aspx

Curious about your GAC?

Sometimes when adding references via XAML you need the full public key
token for a reference.

If you navigate to:

C:WINDOWS/assembly

windows explorer will show you a special view of what is in your GAC as
well as the version, culture info and public key token.

Happy Viewing,

Brian