Singletons by delegate

February 2nd, 2008 by Warren Falk

Singletons are a common programming model, wherein a program ever only uses a single instance of a certain class, and that instance is shared program-wide.

The typical implementation of this is an if-null/lock/if-null setup that looks something like this:

class OnlyOne
{
  private OnlyOne _instance;
  public OnlyOne Instance
  {
    get
    {
      if (_instance == null)
      {
        lock (typeof(OnlyOne))
        {
          if (_instance == null)
          {
            _instance = new OnlyOne();
          }
        }
      }
      return _instance;
    }
  }
}

The reason for the if-null/lock/if-null is one for a different discussion, but it is basically the fastest portable way to allow thread-safe access to the single instance. However, it requires that the first if-null be executed every time a request for the instance is made. If your instance never changes, this is needless overhead.

I developed a quick and dirty solution using delegates. The basic idea is that when you create the first instance and you know it can no longer be null, you change the “GetInstance” routine to point to a routine that does not check for null. I created a generic for this. Here’s the result:

public class Singleton<T> where T: new()
{
  public delegate T InstanceGetter();

  private static T _instance;
  public static InstanceGetter GetInstance = new InstanceGetter(_GetNewInstance);
  private static T _GetNewInstance()
  {
    if (_instance == null)
    {
      lock (typeof(T))
      {
        if (_instance == null)
        {
          _instance = new T();
          GetInstance = new InstanceGetter(_GetInstance);
        }
      }
    }
    return _instance;
  }
  private static T _GetInstance() { return _instance; }
}

And then reusing it is quite easy:

class OnlyOne : Singleton<OnlyOne>
{
}

Now only the first call to OnlyOne.GetInstance() will actually check for null in a single threaded environment. And in the worst-case multithreaded environment, only the first simultaneous calls will check, the rest will just return the instance immediately.

My tests showed about a 25% performance gain. This is actually of questionable usefulness because you should not be calling the GetInstance method in a tight loop, you should call it once and assign it to a local. But I thought I’d share the basic idea because using delegates in this fashion might be useful in other scenarios.

Monodevelop

December 11th, 2007 by Warren Falk

I’m still relatively new to Mono, which is a cross platform, open-source implementation of .Net. The implementation has proved surprisingly gap free for the most part.

But, what Mono suffers from is its lack of Visual Studio. Much of what makes .Net development so effortless is what is a really good implementation of an IDE (refactoring, a really good debugger, smart tags, and several other nice things). An IDE is beyond the scope of the Mono project, and another project, “Monodevelop” is filling in that gap.

Unfortunately, there are still gaping holes which makes it frustrating to anyone who has been spoiled by Visual Studio. I miss the refactoring, the smart tags which prompt you to effortlessly add a “Using” if necessary, but most of all, a debugger.

It is not hard to write complex code, it isn’t hard to write code quickly, but if you need to do both, you really need a debugger to get it right. And this is where Monodevelop (and also Mono) are way short. It’s relatively young still and free open source; and most importantly the developers are planning to implement all these things. I may see about getting in on that myself. But for now, Monodevelop is slightly refreshing but mostly frustrating.

Latest mono on Ubuntu

December 5th, 2007 by Warren Falk

The current version of mono on Ubuntu 7.10 is 1.2.4.2. There are fixes in 1.2.5.2 which I need. Getting 1.2.5.2 built is no problem, but getting it installed without causing all kinds of problems appears to be. This is something I miss about Gentoo.

I’ve tried building my own package, but the official packages for mono are split up into many smaller packages which made that impossible.

I think what I’ll have to do in order to upgrade is to get the source package using apt-get source, unpack it all, and see if I can just replace the 1.4.2.2 code with the 1.2.5.2 code.

I have already pulled the source package down successfully and unpacked it. It looks like the Ubuntu guys applied many patches to it. I don’t know if those patches will work with the new version of code, or if the new version of code contains those patches. It’s probably some combination of the two. This will take some time. I’ll post a follow up if I ever get this working.

Back to Linux

December 4th, 2007 by Warren Falk

Ubuntu IconOver two years ago I shed Windows from my desktop and built a Gentoo desktop. At the time, I was working from home only and had lots of extra time to tweak, compile and troubleshoot. When I changed jobs again, the lack of time, and compatibility issues with being back in a Microsoft environment at work forced me to abandon my Gentoo and go back to Windows.

Well, I’m still in a Microsoft environment at work, and I still don’t have any time, but now I’m trying to make a go of it again. This time, however, noting my lack of available tinker time, I’m going with the flow and have installed Ubuntu. (I love Gentoo but just don’t have the time to deal with its idiosyncrasies right now).

PHP Class Autoload

August 31st, 2006 by Warren Falk

It’s been a long time since I posted.  I just wanted to write up a quick post today to say how much I like the new __autoload() function in PHP.  For those not familiar with it, the function gets called when a class is used in PHP that has not been defined.  This gives the developer a chance to allow the script to find the include file it needs and include it to define the class.

The function’s not all that new, but I’m just getting around to using it and it’s changing the way I design my sites.

So now I don’t use ever need to manually include a file anymore.  I don’t use any global functions.  I make all my otherwise-global functions static functions of some class and call them that way.  I never have to remember to include the file at the top of the page, I never have to worry about including it twice because of the quirks of include_once(), and I don’t have a bunch of orphaned include()s at the top of the script anymore from removing a function but leaving it’s include.

I’m sure there’s someone out there that thinks this isn’t a good idea for whatever reason.  I’m all ears, but for now, this has made my PHP development much easier.

Margin of Error

July 12th, 2006 by Warren Falk

Here, provided for your enjoyment, are the results of a poll displayed, today, on Headline Prime with Erica Hill:

Is It OK To Lie?

52% lying is never justified

65% lying OK to avoid hurting feelings.

source: AP/IPSOS Poll

I just simply could not resist blogging this. What does this mean about at least 17% of survey respondents?

To me, this means that in addition to the margin of error on polls, we need to be aware that the margin of too-frickin-stupid is at least 17%.

Stupid Standards

June 1st, 2006 by Warren Falk

I’m all for standards in web browsers. But it really bugs me when the standards-compliant behavior is worse than the non-compliant browsers’ behavior. So here we have made a standard protocol, and to follow the protocol means making your browser behave poorly. This isn’t always the case. Quite often the standard is better, and for the most part a standard is almost always better than no standard.

It’s almost strange how little agreement there is between browser makers on the best way to implement what’s known as the box model. The box model refers to the dimensions and spacing given to html tags. For instance, a box in html has the main body where the text goes, surrounded by the padding which is filled with the object’s background color but is otherwise empty of text. That is surrounded by the border, which is surrounded by the margin, which is more empty space which is transparent and collapses against (is allowed to overlap) margins of other elements. The confusion comes when it’s time to set the width of the element. To which part of the box model does/should the width refer?

The standard apparently says that the width refers to the body part, not the padding. Internet Explorer, on the other hand, says that the width refers to the body plus the padding plus the border. Oddly, in standards compliant mode, IE still says that the width refers to the body plus the padding. IE’s “quirks” way makes the most sense to me. The standard way does not. Why? Because the standard way makes certain things impossible, whereas, IE’s way does not.

Take for instance a table of data. In one column of the table, you have an input field in each row so that the user can edit information. You want the input field to expand horizontally in size to fill the cell it’s in. So you set its width to 100% and that works perfectly, except you notice that the text seems to butt up against the left edge too closely, so you add padding to the left (about five pixels (5px) or so). Ah, that seems to work fine in IE, but in Firefox, now, the right edge of your input field has encroached five pixels into the neighboring cell on the right. Why? Because the 100% width you set doesn’t apply to the padding. So how do you take the padding into account? You can’t, because you can’t do math in CSS. Otherwise 100% - 5px would be nice. Or it might be nice to be able to actually specify which part of the box model you want width to affect.

Now IE gets a lot of flack when it doesn’t adhere to the standard, and for the most part it should. And I like that IE can be switched into “compliance” mode with a DOCTYPE declaration (even though it is only a little more compliant). However, I often find that it is the standard which is most annoying.

Development in Variable Width (follow up)

May 30th, 2006 by Warren Falk

I am still using variable width for my development. I still have not noticed any more annoyances besides those I had already noted in my first post (space character too thin, developers that try to line stuff up too often etc.). I have corrected the space-too-thin problem by editing the font. I took the liberty of merging the monospace versions of the parentheses, angle brackets, and curly braces (I used Bitstream Vera Mono for that) into my favorite proportional font so far (Verdana - like Tahoma, but with wider spacing between letters).

I also fixed some other annoyances, such as the tiny margin on either side of single and double quotes. This made it very hard to read, and made things such as a single quote, wrapped in double quotes, a very hard thing to decipher. So I increased that margin significantly.

Then I did a couple more things. I made the parentheses (that I copied in from the monospace font) to be more concave. I like that much better. I also made their footprints wider to compensate. Then I added a dot in the middle of the zero, and even put a very thin line through the seven, just because.

I even adjusted the kerning between certain characters to make operators easier to read. I made >>, => and -> spaced closer together, but when I tested them out, I found that my development environment does not seem to take advantage of kerning. If it had, I might have also added some more operator kerning.

So for anyone who is interested, here is the font: WF-Programmer Postscript Font file

DOM Builder Shortcut Function

May 16th, 2006 by Warren Falk

I’ve created a library to aid in the creation of DOM trees from within Javascript using a json-like syntax. If you’ve ever createElemented or appendChilded your way to a DOM tree, you know why this might be handy.

Click to continue reading “DOM Builder Shortcut Function”

Development in Variable Width

May 10th, 2006 by Warren Falk

The traditional font family for use in writing computer code is monospace. Partly this is because monospace was all that was available when computer programming began and remained largely the only choice until relatively recently. Mostly, though, monospace is used because coders use spacing to line up their code to make it more readable.

I visited a website which listed some favorite programming fonts and described the properties of each font which made it suitable for programming. All the fonts were monospace as one would assume. However a commentor on the site said that he began using a variable width font a few years previously and never looked back.

So I’ve decided to give it a try, and so far, I like it. Variable width fonts are just easier on the eyes after a while. Still, you need a decent programming font. I would like one where the parentheses (and brackets) have wider than average spacing, and similar characters such as zero and the letter ‘O’ are distinguishable. Interestingly, I’ve found that when I don’t intentionally line my code up, I actually don’t want it to line up. I have found that it is actually easier to read the code when all the characters in the line below do not line up directly under characters in the line above. My left margin is always clean because the spaces and tabs are always the same size. For the most part, I don’t see spacing as a problem. In my particular font, I wish the space character was bigger, though. Another “pro” is that I can fit a whole lot more on one line without using a small font or a harder to read, narrow font.

There are some “cons” though. That narrow font means that people who wrap their comments to more than one line seem to wrap them way too soon. And using a variable width font means I will, likewise, tend to wrap mine later than would be readable for a monospace-font developer. My left margin is always clean, but every once in a great while, I find that code that was intended to line up does not. However, this hasn’t been a problem for me. Coders, I think, often over-format their code, even reducing readability to some degree.

What I would like to see is an editor that can mitigate the downsides of variable width fonts by manipulating the whitespace and recognizing the language syntax. For instance, the editor should be able to detect when a monospace-font developer adds superfluous whitespace for the purpose of lining up code and then expand the variable width whitespace as necessary to make sure the code is lined up. Though this can’t ever be perfect, it can be perfected to a reasonable degree. Also, comment blocks that are obviously wrapped intentionally could be “unwrapped” then “rewrapped.” There are email applications that do this with email text wrapped to the standard 80-or-so lines.  The editor can then automatically wrap comments back to monospace width when saving.

I am currently using KDevelop, KDE’s development environment, for my C++ development.  I might just try to find out where the editor code is and see if I can implement something like this.  In the mean time, though, I think I’ll keep experimenting with different variable width fonts anyway.


AJAXed with AWP