Benji Smith in Why I Hate Frameworks:

So this week, we're introducing a general-purpose tool-building factory factory factory, so that all of your different tool factory factories can be produced by a single, unified factory. The factory factory factory will produce only the tool factory factories that you actually need, and each of those factory factories will produce a single factory based on your custom tool specifications. The final set of tools that emerge from this process will be the ideal tools for your particular project.

A great read that not only shows why I too hate most frameworks, but also over-engineered code in general. YAGNI FTW! (via Don Box)

During a Java debug session today, I was investigating an exception and noticed that its cause was set to itself; effectively leading to an infinite stacktrace (or so I thought).

When I added a watch on exception.getCause(), this returned null though, so I initially assumed this was a bug in my IDE (I'm using a beta release of IDEA 5.0). However, a quick check of the source-code of Throwable disproved that initial assumption. As it turns out, this problem is caused by a JVM hack implementation.

Take a look at the excerpt from Throwable below:

  /**
   * The throwable that caused this throwable to get thrown, or null if this
   * throwable was not caused by another throwable, or if the causative
   * throwable is unknown.  If this field is equal to this throwable itself,
   * it indicates that the cause of this throwable has not yet been
   * initialized.
   *
   * @serial
   * @since 1.4
   */
  private Throwable cause = this;

  public Throwable getCause() {
      return (cause==this ? null : cause);
  }

  public synchronized Throwable initCause(Throwable cause) {
      if (this.cause != this)
          throw new IllegalStateException("Can't overwrite cause");
      if (cause == this)
          throw new IllegalArgumentException("Self-causation not permitted");
      this.cause = cause;
      return this;
  }
It turns out that self-causation is the default state; indicating that the cause has not yet been initialized. In other words, it's nothing but a hack to save the developer from either adding a causeInitialized boolean to Throwable, or (if they really felt they need to save those 4 bytes), doing something like
  private static Throwable NOT_INITIALIZED =
             new Throwable("CAUSE NOT INITIALIZED", null);
    
  private Throwable cause = NOT_INITIALIZED;
Now from a runtime-perspective, this hack really doesn't matter as cause is private and the this initial value is never returned to the user. Unfortunately from a debug-perspective, this implementation is utterly confusing.

So why do I still say I love Java? Because, unlike .NET for instance, I have access to the source-code in moments like this. Language-wise, I actually prefer C# over Java. Library-wise, I also tend to favor the .NET implementations over their Java counterparts. But with .NET, if something works somewhat differently from what I would expect, I don't have the option of checking the actual implementation. To me, this is a BIG DEAL. Having the source available is not only helpful in situations like this, but it's also a tremendous aid when you truly want to grok an API.

And yes, I'm aware of the existence of Rotor and decompilers, but

  1. Rotor is an incomplete implementation, lacking all of WinForms for instance.
  2. Decompilation is not perfect and sometimes leads to awkward looking code.
  3. Checking code from either Rotor or decompiling a class tends to not be integrated in VS.NET, so I'm forced to leave the IDE for tasks like this.
  4. .NET decompilers typically show only one decompiled method at a time (the ones I've tried did this anyway) instead of the full class, leading to a more fragmented view of the code.
  5. Decompiled code lacks comments and sometimes even lacks the original variable-names.

There's been some dialog going on for over a year now about open-sourcing Java, but as far as I'm concerned, Java's already open-source enough. I just wish .NET would follow Java's example on this aspect as well. I don't need a license to allow me to change the source, but it sure would be nice if Microsoft would surprise me and include the source in .NET 2.0...

Last week, Sam Ruby posted a very interesting article on continuations for "people older than dirt" (a category which I, according to his definition, fall into). The topic became even more interesting when Don Box posted how you can use a very similar syntax in the next iteration of C#. Shortly thereafter, Cedric Beust posted that he wasn't convinced on the usefulness of this construct, and that a simple Java class without continuations pretty much does the same thing.

Despite having, like Cedric, mainly a Java background, I do think this construct will be useful, and would welcome it in the next release (that seems to be the established pattern anyway). Consider the example of trying to write a filtered Iterator. Using the C# 2.0, the code almost writes itself:

    class Program
    {
        public static IEnumerable<T> IteratorFilter<T>(IEnumerable<T> iterator,
                                                       Predicate<T> predicate)
        {
            foreach (T value in iterator)
            {
                if (predicate(value))
                {
                    yield return value;
                }
            }
        }

        static void Main()
        {
            int[] values = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
            foreach(int i in IteratorFilter(values, 
                    delegate(int v){ return v%2 == 0; }))
            {
                Console.WriteLine(i); // even numbers only
            }
        }
    }
The same can definitely not be said for Java. My initial version took quite a bit longer to create than the C# version, and ended up looking like this:
    public interface Predicate<T> {
        boolean evaluate(T value);
    }

    public class IteratorFilter<T> implements Iterator<T> {
        private Iterator<T> _iterator;
        private Predicate<T> _predicate;
        private T _currentValue;
        private boolean _hasNext = true;
    
        public IteratorFilter(Iterator<T> iterator, Predicate<T> predicate) {
            _iterator = iterator;
            _predicate = predicate;
            skipFiltered();
        }
    
        private void skipFiltered() {
            while (_iterator.hasNext()) {
                _currentValue = _iterator.next();
                if (_predicate.evaluate(_currentValue)) {
                    return;
                }
            }
            _hasNext = false;
        }
    
        public boolean hasNext() {
            return _hasNext;
        }
    
        public T next() {
            if (!_hasNext) {
                throw new NoSuchElementException();
            }
            T result = _currentValue;
            skipFiltered();
            return result;
        }
    
        public void remove() {
            throw new UnsupportedOperationException();
        }
    
        public static void main(String[] args) {
            Integer[] values = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
            Iterator<Integer> i = new IteratorFilter<Integer>(
                    Arrays.asList(values).iterator(), 
                    new Predicate<Integer>() {
                        public boolean evaluate(Integer value) {
                            return value % 2 == 0;
                        }
                    });
    
            while(i.hasNext()) {
                System.out.println(i.next());
            }
        }
    }
Ouch! Without continuations, there's no option to just iterate over the elements and filter out the unwanted values, like I did in the C# implementation. Instead, I'm forced to create a class that implements the Iterator interface, store _currentValue and _hasNext as fields, and create a skipFiltered() method to skip unwanted values.

I am aware that C#'s IEnumarable isn't exactly the same as a Java Iterator; in a way it's more like a subset of Java's Collection. However, creating a Java function that creates a new Collection (containing the filtered subset of the original) wouldn't be quite the same as it would create a second Collection and have all filtering done up-front, instead of just an iterator whose elements are fetched from the original in an on-demand fashion.

Disclaimer: I am by no means an expert on the new constructs in C# 2.0 or Java 5.0 (far from it) - if I've overlooked something, please let me know in the comment section below.

Many years ago, before I got broadband, I remember sometimes having to leave my computer turned on overnight to complete some huge (back then: anything over a few MBs) download, only to oftentimes find in the morning that my modem had hung up shortly after I went to bed.

Last night, I felt like I was back in that age again. I started downloading the Visual Studio 2005 Team Suite Beta 2 from MSDN (which weighs in at a whopping 3.75GB) and was told it would take more than eight hours to complete. Then in the middle of the night (when one of my kids woke up and got me out of bed) I checked it, only to find that the download had stopped and the File Transfer Manager was just sitting idly waiting for me to press the "Resume" button (hopefully VS.NET itself will be smarter than the download manager you need to get it). So anyway, I continued the download and when I woke up this morning I found it had still only downloaded 24% :-(

I've had it running all day today and have gotten up to 63% right now, with a time remaining that fluctuates between 3 and 10 hours. If everything works out I guess it should complete by tomorrow, after which there's no doubt a multi-hour install procedure coming up...

What the F is in this thing for it to be so freaking huge? A top-notch Java IDE can fit in 40MB; is VS.NET really 100 times better / have 100 times more features? Guess I'll find out tomorrow...

I love listening to DotNetRocks on my iPod while driving to work, but one thing has been bothering me for a long time: when you pause the show halfway and then either dock the iPod or listen to something else, you lose where you were. This means that in order to continue listening later, you need to manually fast-forward back there.

I just found out that for audio-books, iPods do keep a bookmark though, and any AAC file will be recognized as an audiobook if it has a .m4b file-extension (instead of the default .m4a). So to be able to bookmark your DotNetRocks shows, follow the following directions:

  • Download the "Windows Media" version of the show.
  • Drag 'n drop it into iTunes, which will automatically convert the .wma file to a .m4a file. (you could have also downloaded the mp3 and manually converted that to aac through iTunes, but the sound-quality of WMAs is better and iTunes will auto-convert them).
  • After the conversion is complete, right-click on the file and select "Show Song File" - an explorer window will pop-up for the directory containing the converted file.
  • Rename the file-extension to .m4b.
  • Drag 'n drop this file back into iTunes (it will now show up as a "Protected AAC Audio File").
  • Remove the original file from iTunes.
  • Et Voila! Your iPod will now automatically set a bookmark when you pause DotNetRocks, and continue playing from there when you return later.

A little while ago, I received an email from Palo Mraz offering me a free license for his Dynamic Autocomplete .NET Component, to be used in SharpReader. Having given it a spin, I have to say I'm very impressed. Usage of this component is a snap: you just drop it on your form and all your existing TextBoxes become automagically autocomplete-enabled, meaning they now show a dropdown of past entries for the user to choose from at runtime. They will also get a number of extra properties in VS.NET's property-grid to customize the autocomplete behavior - very nice indeed. To get more info, check out these tutorials.

Using this component, dynamic autocomplete will be one of the new features of the next SharpReader release. Thanks Palo!

I have to say that seeing components like this makes me realize that there are most likely a lot of other commercial components out there that may be useful for SharpReader as well. If anybody has any suggestions of useful winforms components at a reasonable pricepoint, please let me know.

Eric Gunnerson blogged last week about Nullable types in C# 2.0. This new C# feature will allow one to specify a Type like int? which will act just like a regular int, with the exception that it can now also be null. The "?" syntax comes from this Microsoft Research paper, which introduces the following Regex-inspired Type-modifiers:

Type*Zero or more of Type
Type+One or more of Type
Type?Zero or One of Type
Type!Exactly One of Type

In .NET, by definition a value type defaults to "!" (i.e. is not nullable) while a reference type defaults to "?" (i.e. is nullable).

With the introduction of "?" in C# 2.0, developers will be able to override the default value type behavior, which is interesting and useful, but the one I'd really like to see implemented would be "!" on a reference type. Being able to protect against NullReferenceExceptions at compile-time would be a very powerful construct, helping both program readability as well as robustness. Methods would no longer have to check if their parameters are non-null while callers would know whether it's ok to pass in a null in the first place. Also, when calling a method, you would be assured the returned object would always be non-null.

The assignment rules would be simple enough:

Type nullable = ...;
Type! nonNullable = ...;
nullable = nonNullable; // compiles fine
nonNullable = nullable; // fails compilation
nonNullable = (Type!)nullable; // compiles but may throw a NullReferenceException at runtime
The main problem with introducing "!" into the existing .NET framework would be that it can't really be integrated in the existing libraries. Method return-types can be changed to "!" notation without any problems (as they're assignment compatible to existing types), but changing method arguments that way would break almost all code currently using that method.

A potential solution to this problem would be allow for another modifier or keyword ("Type!?" maybe?) that would allow assignments from regular reference-typed objects at compile-type, but that compiles into code that checks for null at runtime and possibly throws a NullReferenceException. Apart from assignment, variables of this type would behave just like "Type!" as its value will be guaranteed to be non-null. In doing this, we would not gain the compile-time checking advantage (as the backwards compatibility sacrifice would simply be too large), but we'd still gain in readability and maintainability as the code would become more self-documenting.

There is of course another solution, which would be to simply leave the current framework method parameters as-is, but I think the enhanced self-documenting nature and automatic early null-checks of using a method argument modifier would be preferable. Also, even though we cannot get the compile-time checking, we certainly can have the compiler spit out warnings when regular (nullable) types are passed as arguments to these methods.

After having had it on my Amazon wish list for about a year, I finally picked up my copy of Chris Sells' "Windows Forms Programming in C#". Being a server-side Java developer by day, I've put off getting this book for quite a while, despite the excellent reviews it got everywhere. Then when a few weeks ago I got stuck on some WinForms stuff for SharpReader, I decided it was about time to get me a copy. Just browsing through it shortly, I see now that it wasn't just "about time", it was really "way overdue"! It contains well over 600 pages of very useful information on Windows Forms and should help me a lot in future SharpReader development; thanks Chris!

One of the first things I noticed was the 8 color pages in the middle with various pictures of WinForms apps and controls that are discussed in the book. Much to my surprise, the very last one (showing the use of the NotifyIcon component) contains the SharpReader icon. Way cool!

Copyright © 2003, 2004 Luke Hutteman