Sunday, May 20, 2012

How do I get more than one thing back from a method?

Boy, this is a pain point isn't it? I've heard Eric Hexter use a Mad Max Beyond Thunderdome analogy: "Two go in, one comes out" ...and while it doesn't have to be just two things in a method's signature, you are just getting one thing back at the end of it all. This is an adjustment for all of us who learned object-oriented programming, and sometimes we try to fight it by using ref and out variables. Boo. It is probably best to try your damnedest to stick with writing readable code in which methods just give back one thing. C# 4.0 in a Nutshell, a book I am reading, mentions that Tuples are a new object type in C# 4.0 that allow you to have a grab bag of dissimilar types balled up in one type that may then be unspooled on the other side of being handed back by a method. This sort of hack already existed somewhat with KeyValuePair exploits, but a Tuple will allow one to hand back up to seven dissimilar things instead of merely two. I've never yet seen anyone's code use a Tuple so I suspect that this is coming to us too late after we have all learned our own dirty tricks for fighting with "one comes out." Test tests below pass and show off tucking stuff into a Tuple and pulling it back out again.

using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Tests
{
   [TestClass]
   public class TupleTest
   {
      [TestMethod]
      public void Test()
      {
         DateTime today = new DateTime(2012, 5, 20);
         Random random = new Random(14);
         StringBuilder book = new StringBuilder();
         book.Append("Call me Ishmael.");
         Tuple<DateTime, Random, StringBuilder> grabBag = Tuple.Create(today, random,
               book);
         Assert.AreEqual(grabBag.Item1.Year, 2012);
         Assert.IsTrue(grabBag.Item2.NextDouble() >= 0 && grabBag.Item2.NextDouble() <
               14);
         grabBag.Item3.Append(" Some years ago - never mind how long precisely - ");
         Assert.AreEqual(grabBag.Item3.ToString(), "Call me Ishmael. Some years ago -
               never mind how long precisely - ");
      }
   }
}

No comments:

Post a Comment