Stupid C# Tricks – Sealed Classes

So as platform-driven languages go, C# isn’t a bad one.  We’ve had some good times together, and I’m rather fond of the bloated, lumbering behemoth.  But there are a few things about it which drive me absolutely insane.  One of these is sealed classes.

Now the conventional wisdom is that sealing classes improves performance and security.  First of all, if a sealed class increases performance (which it doesn’t in all cases), then those gains are absolutely negligible.  Relying on sealed classes to get your app to meet benchmark requirements is a little like entering a horse in the Kentucky Derby, and then relying on giving him a good shave to make him win.  Even if the minor weight loss DOES make him a bit faster, it’s not going to be enough to win.  Plus now you have an angry, naked horse on your hands.

Okay, so that analogy went kind of a weird place.  But I hope my point is clear: sealed classes don’t provide good enough performance boosts to really make a difference.  If the kind of operation-shaving that sealed classes sometimes result in is really your last resort for optimization, then you may have a bigger problem on your hands than you think.

As for the security argument, well, I just don’t buy it.  It seems that people think that a lack of inheritance is somehow a security feature, but I just don’t see how.  If not allowing your C# code to be overridden or reused by other people is really key to your “security” methodology, then you better hope that none of your customers are smart enough to use Reflector.  I mean, this security argument is really so stupid that I can’t help but think that I must be constructing a straw man.  Alas, a quick Google search seems to indicate that sealing classes is widely understood to be “good security.”

Of course, none of this would be that bad if it was just a smattering of C# developers who went around sealing their classes.  The problem is that a lot of very useful classes in the platform itself are sealed.  I recently found another such class when I tried to override the Console class.  Apparently the C# team at Microsoft has decided that no one will ever need, want, or get to override Console.  Which would be fine, except that I both needed and wanted to override Console.

Why, you ask?  Well, to be fair, it was for a gonzo code joke that probably would have amused only me.  But the fact of the matter is, I won’t get a chance to find out if it’s as funny as I thought it would be, because .NET won’t let me override the Console class.

So that’s the rant.  Sealing classes is both useless and annoying, doubly so when it’s done to basic platform classes.  What’s more, I’ve not seen a single good argument in defense of the practice.

Though just watch, a few weeks from now, we’ll see someone flogging sealed classes on the grounds that it protects the world from dubiously funny jokes by bored twenty-somethings.

Truth

Click for bigger. Source unknown; if anyone knows, please leave a comment.

Dear SOA Coders

Please version your services. Seriously, I cannot express the irrational irritation I feel whenever I encounter an unversioned web service. And while I would like say that it makes me go all Bruce Banner and go on campaigns of violence against service authors, really I just say mean things about them and question their intelligence, heritage, grooming habits. Truly, you wouldn’t like me when I’m angry; I can be pretty damned annoying.

Where was I? Right, web service versioning. Probably the best way to handle it is to add another web method to all your services that returns version of the executing assembly. In C# and other .NET languages, this is pretty simple:

1
2
3
4
5
6
7
8
9
10
11
12
[WebMethod]
public string GetVersion()
{
    Version versionObj = 
        System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
 
    string versionString = 
        versionObj.Major + "." + versionObj.Minor + "." + 
        versionObj.Build + "." + versionObj.Revision;
 
    return versionString;
}

Another option for web service versioning is simply to include the version as an output parameter on every method. In most cases this is overkill, but in instances where the web service changes often and/or without notice, it might not be such a bad idea.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        public static string Message { get; set; }
        [WebMethod]
        public string GetMessage(out string currentServiceVersion)
        {
            currentServiceVersion = GetVersion();
            return Message;
        }
 
        [WebMethod]
        public void SetMessage(string newMessage, out string currentServiceVersion)
        {
            currentServiceVersion = GetVersion();
            Message = newMessage;
            return;
        }

Of course this method has the disadvantage that, even though you probably only need to check the version rarely (e.g. when issues arise or when deploying new versions of consumer apps), the web service does the work of retrieving the version every time. It also incurs a slight network traffic cost, since you’re passing the version back with every response message.

I would have thought that attaching some kind of client-accessible version to your web services would be common sense or, at the very least, common best practice. But we’ve been fighting this battle in the context of my day job, trying to get a client to version the services we rely on for integration. This after several cases in which QA saw issues in testing which, after investigation, turned out to be due to web services that hadn’t been updated as promised or, worse yet, had been “updated” without our knowledge.

So yes: version your services. It’s not that hard, and can save everyone a lot of angst. Especially those who would otherwise have to listen to me bitch.

Throw-Away Apps FTW!

So one of the greatest things about being a hacker is that one has a ready answer to idle thoughts of “I wish my computer did X…” You simply code up a way for it to do what you want. It’s especially nice when what you want it to do is actually rather simple, but just something that no one’s thought to implement yet. (This is all, of course, assuming that Google failed to turn up a good existing solution. Reinventing the wheel makes baby Edsger Dijkstra cry.)

Case in point: on a couple of recent occasions, I’ve thought it’d be nice if I had a way to quickly dump a timestamp to my windows clipboard so that I could drop it into documents. Well, after ten minutes of hacking and a little bit of thrashing at OS integration, I have exactly that.

Basically I wrote a lightweight C# console app that optionally takes a DateTime format string as an argument and does nothing but push a current timestamp to the clipboard. (It applies the format string if provided, otherwise it just uses default formatting.) I put the executable in an easy-to-remember path (C:\TimeToClipboard\). I then added keys to some of the shell registry entries to add the application (called with my preferred timestamp format) to filesystem context menus.

The application code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Windows.Forms;
 
namespace TimeToClipboard
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Clipboard.SetText(DateTime.Now.ToString(args[0]));
            }
            else
            {
                Clipboard.SetText(DateTime.Now.ToString());
            }
        }
    }
}

The registry entries:

Keys: HKey_Classes_Root/*/shell/Get Timestamp/command
HKey_Classes_Root/Drive/shell/Get Timestamp/command
HKey_Classes_Root/Folder/shell/Get Timestamp/command

Value: c:\TimeToClipboard\TimeToClipboard.exe “yyyy.M.d H:mm:ss”

This worked pretty well, but I couldn’t figure out a way to add the Get Timestamp context menu item to the desktop context menu. I was hoping that * really meant “add to all context menus”, but it in Microsoft world, it apparently means “add it to an unspecified subset of context menus.” Not very helpful.

So my next idea for easy access was a keyboard shortcut. I added a shortcut to the TimeToClipboard application to my desktop and bound it to the Ctrl+Alt+T keyboard combination. This works well, and works no matter what application has keyboard focus. So no matter what I’m doing, I’m never more than three keystrokes away from having a timestamp.

World changing? Hardly. But convenient. Plus the whole thing took me less than an hour to bash together and get setup, and most of that time was googling around for the names of registry keys.

CSS Hackery

Getting some CSS help from my friend Chris. This is just a test. Please ignore.

1
2
3
4
5
6
7
8
if(thisWorks)
{
    return "I'm impressed";
}
else
{
    return "OH SHIT GUYS, DIDN'T WORK!";
}

(Also, sorry for the weirdness of the code samples the past few days. I think we have the problems ironed out now. Just beating a new WP plugin into submission. Nothing to see here.)

Stupid C# Tricks – Closures

So in my current quest to poke around in some of the more esoteric corners of C#, I’ve gotten interested in C#’s implementation of closures. Like most .NET languages, C# is trying really hard to be everything to everyone, and so as of language version 3.0 it has native support for closures. Now, many of you functional folks in the audience are probably either saying “woo-hoo closures! Yeah! ROCK!” or possibly “wait, people use C#? I thought everyone was on Ruby these days.”

The .NET folks are probably searching in vain for the MSDN article on this mythical “closure” thing.

So a closure (for those unfamiliar) is a chunk of code that can be passed around like a first-class object and which can reference variables in the namespace in which it was created. It’s essentially a method that’s treated like and object and can reference variables it could see at the time of its creation. These things are all the rage in Lisp- and Smalltalk-like languages. They’re one of the things that makes Lisp so powerful and they cause most Rubyists to get all wet in the trousers.

So what can closures do for you? Go go gadget example!

In this example, we’ll be creating a light-weight console app which determines the length of the Collatz Chain resulting from a given starting point. The Collatz Conjecture (unproven) states that the following function, if iterated, will eventually converge to 1, regardless of starting point:

f(x) = x/2 (X is even)
f(x) = 3x+1 (X is odd)

A Collatz Chain, then, is the sequence of results created by iteratively applying the above function starting from a particular number.

Now a recursive solution to this is pretty easy to bash out. There’s not much to the problem as stated here. But it serves as a pretty handy way to demonstrate closures. (The real mindfuck comes when you start examining the problem’s properties and the various interesting attempts at proving the conjecture. Also, the function makes for a really kickass graph and fractal.)

So, in the code below, I’m going to encapsulate the Collatz function in code block and pass it in to a wrapper class which will do that actual execution of the code.  First, the wrapper:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CollatzByClosures
{
    public static class CollatzWrapper
    {
        public static Func method;
        public static int Execute()
        {
            return method();
        }
    }
}

As you can see, there’s not a whole lot to this. The static CollatzWrapper class has a Function object that returns an integer, and it’s got a public Execute method that just returns the result of that method’s execution. Note that the method takes no arguments and that the wrapper is both static and contains no other member variables besides the function. “There’s nothing up my sleeve and nothing under my hat”, said the magician.

Next, the program that uses this wrapper:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace CollatzByClosures
{
    class Program
    {
        private static int CollatzArgument = 0;
        private static int CollatzLength = 0;
 
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                CollatzArgument = int.Parse(args[0]);
            }
            else
            {
                CollatzArgument = 42;
            }
 
            CollatzWrapper.method = (
                () => {
                    if(CollatzArgument%2 == 0)
                    {
                        CollatzLength++;
                        return CollatzArgument/2;
                    }
                    else
                    {
                        CollatzLength++;
                        return (CollatzArgument*3+1);
                    }
                });
 
            while (CollatzArgument > 1)
                CollatzArgument = CollatzWrapper.Execute();
 
            if (args.Length > 0)
            {
                Console.WriteLine(args[0] + " results in a Collatz chain of " + CollatzLength.ToString());
            }
            else
            {
                Console.WriteLine("No argument detected. Using 42 which results in a Collatz chain of length " + CollatzLength.ToString());
            }
        }
    }
}

So the above code’s fairly simple. The Program class has a pair of private static variables used to track the length of the chain and the current number that we’re evaluating using the Collatz Function. If the user passes in an argument, we’ll calculate the chain from that. Otherwise, we’ll calculate the chain from 42. Next, we assign a block encapsulating the Collatz Function to the CollatzWrapper’s “method” variable. Notice that the block that I’m constructing here references private members of the Program class, and I’m assigning this block to a variable in the CollatzWrapper class. The intuition of most OOP folks will tell them that these private members shouldn’t be accessible from another class.

Thanks to the magic of closures, however, the block that I assigned to the CollatzWrapper’s “method” variable can still reference anything to which it had access when that block was created. This means that it can still access those private members, even from another class.

The results of running the above app with no arguments:

No argument detected. Using 42 which results in a Collatz chain of length 8    
Press any key to continue . . .

Results when I pass in argument 17298 (randomly generated using the “ask a friend to pick a large number” method):

17298 results in a Collatz chain of 53

So the closure passed into the wrapper uses private variables from the class in which it was created (rather than the one in which it was executed) to track the length of the Collatz chain and to store the result of its computations.

One other nice thing about closures (not really demonstrated in this code), is that since closures are first-class objects, they can be passed around in exactly the same way as any other object. Moreover, they can be changed, assigned, and moved all through a system, all while maintaining access to the variables that were available to them on creation. These are all properties which make closures full of awesome.

Now, is there anything you can do with closures that you can’t do some other way in C#? Well, no. But I imagine there are a lot of things that closures make easier, more intuitive, and quicker to implement. Besides, even if one never uses closures, it’s nice to be able to say that we know what our tools can do.

The Problem with Computers


From the inimitable SMBC

Static Constructors Ruined My Party

So static constructors are weird.  This should be an unconstroversial statement, but in case anyone was in doubt and needed more evidence, here’s a peculiar little situation.  I normally use static constants in any project where I need immutable references to strings, numerical constants, or other objects.

So I’ve set up a static ‘Constants’ class, which has some static readonly strings and some dictionaries which references those strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace StaticStringsWeirdness
{
    static class Constants
    {
        public static readonly string PlanKey = "Plan";
        public static readonly Dictionary FridayNightPlans = 
            new Dictionary {
                                            {PlanKey,Party}
                                          };
        private static readonly string Hack = "Hackety hack!";
        private static readonly string Party = "Party! Oontz oontz oontz!";
        public static readonly Dictionary SaturdayNightPlans = new Dictionary {
                                            {PlanKey,Hack}
                                          };
 
    }
}

Pretty straight forward. I’m planning to party on Friday night and buckle down and do some hacking on Saturday night. (Sounds like a damned fine weekend to me!) So I have two dictionaries, one for my plans Friday night and one for my plans Saturday night. I also have some strings that are private and used to build the dictionaries. Anyway, both of these dictionaries are initialized in exactly the same fashion. They both use private static strings that are defined in the same class and same code file to add a single entry, keyed to the string “Plan”.

Anyone want to bet that both dictionaries get initialized with the right values? Anyone? C’mon, 5 gets you 10 if those two dictionaries both get initialized properly.

If you took that bet, email me and I’ll let you know where you can send your $5.

See, I use these two dictionaries in a simple little C# console app. There’s no trickery here, nor really even anything interesting. I just grab the value associated with the “Plan” key and dump it to the console. Both dictionaries have this key, and both of them assigned to it a private static readonly string. Code for the app:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace StaticStringsWeirdness
{
    class Program
    {
        static void Main(string[] args)
        {
            //Friday night
            Console.WriteLine("Whatcha doin' Friday night?");
            Console.WriteLine(Constants.FridayNightPlans[Constants.PlanKey]);
 
            //Saturday night
            Console.WriteLine("That's cool. What about Saturday night?");
            Console.WriteLine(Constants.SaturdayNightPlans[Constants.PlanKey]);
        }
    }
}

So now you would expect this to just output a cute little story about how my plans are to party on Friday night and to hack on Saturday night. Instead, the output looks like:

Whatcha doin' Friday night?
 
That's cool. What about Saturday night?
Hackety hack!
Press any key to continue . . .

So the output from the first dictionary, which should have read “Party! Oontz oontz oontz!” was instead the empty string. It threw no exceptions, and the request for the value keyed to the “Plan” key returned a string that is initialized, but contains the empty string. The second dictionary, however, returns the expected value.

So why the difference in behavior between the two dictionaries? Well, if you look at the Constants.cs code listing, you’ll see that the FridayNight dictionary is declared above the Hack and Party strings and that the SaturdayNight dictionary is declared below them. This means that, when the constants class is loaded, the FridayNight dictionary is initialized first (using an empty string for Party), followed by the Hack and Party strings, and then the SaturdayNight dictionary (which gets the correct value for the Hack string).

Again, the value in the FridayNight dictionary is not null. The string object it references has been created, but has been initialized to the empty string. This is because the static class is created with all of its members. These members are created with the default values for their type, which for a string is the empty string. Then, during the static constructor, these get initialized in the order that they appear in the code file. You can see this clearly by looking at the static constructor that was generated by the C# compiler.

1
2
3
4
5
6
7
8
9
10
11
12
static Constants()
{
    PlanKey = "Plan";
    Dictionary g__initLocal0 = new Dictionary();
    g__initLocal0.Add(PlanKey, Party);
    FridayNightPlans = g__initLocal0;
    Hack = "Hackety hack!";
    Party = "Party! Oontz oontz oontz!";
    Dictionary g__initLocal1 = new Dictionary();
    g__initLocal1.Add(PlanKey, Hack);
    SaturdayNightPlans = g__initLocal1;
}

You’ll notice that none of the members (Hack, Party, FridayNight, SaturdayNight) are actually created in the constructor. They exist already and, at the start of the static constructor, have the default values for their types. In the case of strings like Hack and Party, that’s the empty string. The FridayNight dictionary gets built just fine, but with an empty string instead of the expected “Party! Oontz oontz oontz!”.

So where FridayNight should have been full of partying, it was instead full of fail.

The moral of the story is that, while static classes are handy, they do take some care. This is especially true when it comes to their constructors. If you need to use references to other class members in static initializers (as I did with the dictionaries above), be sure that the objects that are referenced are declared above the static initializer of the member that references them. Otherwise the referenced object will have its default value at the time that it’s used in the initializer.

Hacker Newspaper: A Case Study in Signal and Noise

The inimitable Giles Bowkett is the mad genius behind an awesome little Hacker News filter called Hacker Newspaper. It’s quickly become the only way I read Hacker News. It cuts out a lot of the bullshit and presents what’s left in a meaningful, easy-to-read fashion.  In essence it takes a channel, removes noise, and then improves the signal somewhat by reshaping the message to be easier to understand.  Noise down, signal up, SNR goes way up.

Compare this to horrid, ad-laden spam blogs that scrape other sites for original content and then wrap it ads.  These take a signal and, without modifying the signal at all, add noise.  This dilutes the signal, causing the SNR to go down.  Sometimes they even combine the signal from multiple sources, adding interference and confusing things even further.

In a recent post, Bowkett ponders what the difference is between his tool and site-scraping spam blogs.  I’m fairly sure that our conclusions on this point are isomorphic, but just framed in different terms.  In my opinion, it all comes down to signal and noise.  Hacker Newspaper remains true to the original signal, but filters out a lot of noise.  This means that it’s unequivocally a better source for that signal.  (Why listen to Hacker News when Hacker Newspaper provides the same signal, only stronger?)  Spam blogs, on the other hand, are reverse-filters that add noise and cause signals to bleed into one another.

To put it another way, Hacker Newspaper is a filter and spam blogs are anti-filters.  I think this not only explains the difference between them, but also hits to the heart of why people express moral outrage at spam blogs and (usually) don’t at things like Hacker Newspaper.  People, especially those in the hacker community, appreciate good filters.  They appreciate them so much in fact, that their willing to totally ignore any principles they may have with regards to “stealing content” if what’s done with that content makes the signal come through stronger.

On the flip side, hackers are rightfully annoyed by obfuscation and irritated when someone willfully makes our lives harder just to make a buck.  This is essentially what happens when spam blogs wrap a signal in noise that profits the owner of the spam blog.  The message gets harder to interpret just so someone who’s too lazy and useless to make their own content can make some easy money on someone else’s message.  It should go with out saying that this makes spam blogs unmitigated bullshit that are full of naught but evil and fail.

People’s reaction to this lameness often gets expressed as moral outrage.  (“How dare you steal content!”) I think it gets framed this way because, given the choice between making an argument from utility and from morals, most people prefer the moral high ground.  After all, righteous indignation is much cooler than simple annoyance.

That’s an over simplification of course, but most people’s principles, when it comes to things like “stealing of content” (scare quotes employed because the theft metaphor is a pretty inaccurate one when it comes to digital content) make a lot of allowances for adding value.  For many people, the principles are genuine, but misstated.  The objection isn’t to reusing content, it’s to diluting someone else’s hard work.  Or to plagiarism for the sake of profit.  Or simply to the loss of value that occurs with any loss of SNR.

In other words, people don’t really mind it when someone reuses content, they mind when someone ruins content.

Determining Number of Factors in PHP

I’m currently learning PHP.  It’s not the first dynamically typed language I’ve worked in (I’m pretty handy in JavaScript), but I definitely do the lion’s share of my hacking in statically typed languages.  (These days, mostly C#).  The below code is hardly revolutionary, but it works well enough.  And suggestions for improving it are most welcome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
	function DetermineNumFactors($numberToCheck)
	{
		if($numberToCheck == 1)
		{
			return 1;
		}
		$numberRoot = sqrt($numberToCheck);
		$numFactors = 2;
		for($i = 2; $i < $numberRoot; $i++)
		{
		    if($numberToCheck % $i == 0)
		    {
		    	$numFactors++;
		    }	
		}
		//we have all the factors up to, but not including the square root
		$numFactors *= 2;
		//now we have all the factors above and below the square root.
		if(floor($numberRoot) == $numberRoot)
		{
			//if root is a natural number, then it&#039;s a factor
			$numFactors++;
		}
		return $numFactors;
	}

One notable bit is the floor/ceiling comparison.  I needed to check to see if the root is a natural number.  (If the square root of the number is a natural number, then the square root of the number is also one of its factors.)  Comparing the square root’s floor and ceiling was the first solution that popped into my head.

I had considered just modding the number by one and comparing the result to zero, but the mod operator truncates floats before performing the modulus, so ($foo % 1) will always return zero.If anyone has a better solution, please let me know.

UPDATE: Two improvements to the method above from the comment section. Andy makes the excellent point that my factorization can start from two, since one and the number itself will always be factors. In order to make this work, I also have to then include an if to handle the boundary case for if the $numberToCheck argument is one.

Chris astutely pointed out that my ceil() check is superfluous and that I can get by with just if (floor($numberRoot) == $numberRoot).

Thank you both for your feedback.

Return top

Shut Up and Hack

This is a blog where I talk about hacking, code, software, and the philosophy of making things. It's basically just another craft blog. Whatever your project or passion is in life, it is more important than this. So thank you very much for reading, but please, when you're done here, go make something awesome.