Posts Tagged ‘Languages’

Programming Must Be An Open System

I decided I needed an hour break from Scala hacking, and I am about halfway finished with Sean Carroll's From Eternity to Here, which goes on at great length about entropy as it relates to time's arrow. So for the fun of it I whipped up a simulation of an Ehrenfest Urn using Processing.js.

Check it out here (requires a browser supporting canvas).

Now that I'm done, there are a couple of things I find amazing about this.

  • I felt like I needed a break from being paid to write Scala. As opposed to, like, Visual Basic, Java, C++, or something like that.
  • Within an hour I was able to download processing, learn the basics, and hack this animated demo together. And put it on a web page, viewable by pretty much anybody that I care to reach. Back in the early aughts I probably spent fifty or sixty hours just trying to figure out how to step debug javascript.

From eternity to here apparently involves a massive improvement in the state of the programming art. Everything is amazing and nobody's happy.

Memetastic

At the behest of Ira Pfeifer here is every programming language I have ever learned. I have grouped these into families since I have met people that have touted the nine variants of COBOL that they know as separate languages and I have considered all of these people to be deserving of horrible, horrible deaths. The grouping makes chronological order impossible.

  1. BASICs: TRS-80 variety, GWBASIC, QBASIC, VB6, VB.NET.
  2. C
  3. Assemblies: x86. And okay, MIPS in school. I have actually written MSIL by hand for production use, although I am not sure if that really belongs here.
  4. C++, to the degree that anyone other than Stroustrup, Stepanov, and Sutter actually knows this byzantine mess.
  5. Pascal, but I quickly reconsidered.
  6. Shell scripts: cmd.exe batch, Bourne, Monad
  7. Java
  8. ML's: SML, OCaml, F#
  9. PHP
  10. Coldfusion. Feel free not to count this. I just completely forgot that this ever existed and felt like listing it.
  11. Turing complete SQL's: T-SQL, plpgsql
  12. C#
  13. Lisps: Common, Scheme, and Emacs
  14. Python
  15. Haskell
  16. Javascript
  17. Erlang
  18. Ruby
  19. Horrible ideas that some enterprisey person should be in prison for: NAnt, Ant.
  20. Things that Wikipedia lists as languages but that might be going too far with this: YACC, XSLT, Matlab.

It's hard to pick favorites between Haskell and the Lisp variants. I can get a lot of work done in Lisps but appreciate Haskell for its brainsmashing purity. If I had to point out an obvious deficiency it'd be that I have yet to play with Factor.

Rule of Thumb

So here's my method for determining whether or not a particular platform is worthwhile.

I ask myself, "how would David Letterman summarize this?" I know this doesn't seem very scientific, but it's a mask I have years of experience wearing. Trust me on this one.

When the curtain is raised to reveal a total square dancing around with a sign that says, "it's simply XML!" I ask myself, "is this anything?" Then I reflect for a second or two and decide, dismissively, that no. This is nothing.

Lakin Wecker has an alternative approach that involves thinking carefully and considering the lessons of history. I will re-evalutate my approach if our results ever differ significantly.

What is Dan Doing?

Hey, by the way, the last post is likely to be my last Windows-oriented post for the forseeable future. I have recently quit the financial sector and will be starting a fantastically cool new job here in a few weeks. I no longer have a Windows machine at home at all, so unless I take up Mono, expect a lot of posts that mention emacs from now on. I think this will be for the best, since I've been kind of bored and nonplussed with .NET stuff lately, F# notwithstanding.

Giving up on Microsoft development entirely was a little bittersweet until someone showed me XMLScript a week or two ago–clearly, a lot of people in that world are out of their god damned minds. Best of luck writing xhtml-serving web applications defined in xml markup with client script written declaratively in more xml, also exposing xml web services to rich client applications defined largely in XAML, updated automatically as defined in xml configuration files, to those of you lucky enough to get to do this.

Is XAML an Elaborate Joke?

Don Box says:

As a WPF user, I spend at least as much time reading and writing XAML as I do reading/writing C# code that does WPF-isms. I do spend a lot of time in C#, but little of it is WPF specific, which arguably is one of the strengths of WPF’s data/content facilities.

In my opinion, the sooner folks get thrown into the XAML pool the sooner they learn to swim.

(Emphasis mine.)

I thought the whole point of selling our souls to the XML devils was that development tools would deal with that slop for us.

Forget swimming. I am having trouble seeing any non-masochistic reason for me to learn this at all. I am just not getting through the Microsoft marketing on this one. I say this as somebody with deep-to-extremely-deep knowledge of most of the Microsoft tools of the last 10 years–I'm not Don Box, but I'm also no slouch.

Give me one good reason why I should spend my spare time learning an API that looks like this. (And it would be my spare time. I am still living here in the real world, where it still seems to be occasionally more practical to write Windows platform code in C++, for god's sake.)

Wikipedia reassures me–in a rather hilarious, pleonastic way–that this is "simply XML."

[A] key aspect of the technology is the reduced complexity needed for tools to process XAML, because it is simply XML. As a result, a variety of products are emerging, particularly in the WPF space, which create XAML-based applications. As XAML is simply based on XML, developers and designers are able to share and edit content freely amongst themselves without requiring compilation.

(Emphasis mine.)

Show me one XML-based API that does not, in one way or another, prove this to be an oxymoron. (See also: "Java programmer writes application which reads 243 XML files on startup then wonders why it takes 30 seconds to start." Thanks, Slava.)

Sometimes trite observations become trite because they are obviously correct. Who created the creator? Why re-invent the s-expressions that have been around since the 50's, but poorly? Et cetera. In these cases the fact that the criticism is well-worn does nothing to detract from it.

Maybe I am just being a grizzled old fogey (at the incredibly advanced age of 27.) It wouldn't be the first time that I have been described as a crotchety septugenarian in the body of a young adult. If I am way off the mark here, please enlighten me.

Update, May 20th: Jon Harrop avoids my bitching and gives solutions. See XAML or F#.

Wheels I Have Wasted Time Re-inventing

This site has been silent for quite a while. My lame excuse for this is as follows.

Sometime around the beginning of the summer I started trying to learn functional programming in earnest. I had some exposure to this in school (ML, if I remember correctly), but not nearly enough, as it turns out. C#'s anonymous methods provided the "eureka" moment that made me want to revisit the topic. I had also been asked to contribute to The Hub, but I had felt like I was lost in the world of F# and that fizzled out altogether (maybe now I might have a few things to say).

So that's my story–I have been exploring strange new(-ish) topics and I've found that I haven't had anything insightful to contribute to the world.

Recently I've been trying to complete a few large projects in Common Lisp. I'm pleasantly surprised to find myself saying that most or all of the highfalutin crap that is spouted about Lisp is true. As to why it isn't the most-used language in the world right now, I am too much of a novice to speculate. But purely from a language standpoint it is certainly making all of the others feel, well, tedious.

Lisp seems to supersede every single neat trick I have ever come up with programming professionally. It either contains them outright, or it makes them trivial through macros or completely unnecessary for some other reason. Let me give you one simple example.

Writing applications in C#, I've occasionally had a singleton or some kind of global object that I wanted to be redefined within a certain call stack. Let's say I have this API:

class Foo
{
    public static Foo Default { get; }
}

And I want this to be redefined for a little while while I call some method called Bar(). Impersonation of users is one concrete example of where this is useful.

My neat-trick solution to this problem is to make the implementation of Default use thread local storage (and maybe fall back on a static instance too), then create a "scope" class that allows me to write code that looks like this:

// Original value of SomeOtherFoo out here
using(FooScope s = new FooScope(someOtherFoo))
{
    // In here, Foo.Default gives someOtherFoo
    Bar();
}
// Original value of SomeOtherFoo out here

(I am skipping over a lot of irritating details here and let me be clear, I don't claim to have invented this. I just mean that I burned a lot of hours arriving at it basically independently of the ten million other programmers who probably recognized the same need and did the same thing. It is purely my own ignorance and stupidity that made "re-discovering" it necessary.)

Anyway, I thought that was clever at the time. But with dynamic scope (as opposed to global scope, which is what static fields have in C#) Lisp has this as part of the language. Writing this:

(let ((*default-foo* some-other-foo))
  (bar))

Is basically the same thing with no effort. The Lisp syntax has the added advantage of working with objects other than the ones I author myself.

This reminds me of the first time I was exposed to .NET events. I realized that I had implemented the same god-damned thing in other languages a handful of times (albeit as a less-seasoned programmer) and it never worked as beautifully or as simply.

Naturally, CLOS seems to have some features that I now realize I have been mimicking imperfectly with events. It also has features that will probably replace events in many of the problems where I have applied them. That is an altogether different story.

First Impressions of CCR

I got a chance to mess around with the Concurrency and Coordination Runtime (CCR) bits recently. Before I get into that, first check out this real-life code I wrote this week.

public static class NotificationQueue
{
    private static Queue<Notification> _queue;
    private static Semaphore _work;

    static NotificationQueue()
    {
        _queue = new Queue<Notification>();
        _work = new Semaphore(0, int.MaxValue);
    }

    public static void Enqueue(Notification n)
    {
        lock (_queue)
        {
            _queue.Enqueue(n);
        }
        _work.Release();
    }

    public static Notification Dequeue()
    {
        _work.WaitOne();
        lock (_queue)
        {
            return _queue.Dequeue();
        }
    }
}

The idea here is to post notifications to the queue from many threads, and have a single notification thread sending the messages out from something like this:

private static void NotifyThreadProc()
{
    while(!Abort())
        NotificationQueue.Dequeue().Send();
}

The documentation for CCR is pretty sparse at this point, limited to just this paper [pdf], the Channel9 video, and this Wiki. Some of the particulars seem to have changed significantly, but I was able to figure out how to replicate my explicitly-threaded notification queue:

public class NotificationService : CcrServiceBase
{
    private Port<Notification> _port;

    public NotificationService()
        : base(new DispatcherQueue("foo"))
    {
        _port = new Port<Notification>();
        Activate(Arbiter.Receive(true, _port,
        delegate(Notification n)
        {
            n.Send();
        }));
    }

    public void Post(Notification n)
    {
        _port.Post(n);
    }
}

That's pretty awesome: notice that no explicit locks or waits are necessary, and I don't need to write the NotificationThreadProc or the code required to start it. I just need to make a NotificationService and start posting to it.

I can't say it's the most immediately comprehensible API I've ever seen, but hopefully that will change with more documentation and some polish. It's also possible that I am just warped from years of using the lower-level concepts. Overall this is awfully impressive for a library.

Faking Multiple Inheritance with Event Handlers

I'm going to take a page from the Book of Darrel and post some design patterns whenever I realize that I'm using them. I'd like to be careful because I think that there are a few camps when it comes to design patterns:

  1. Design patterns are very important, very specific, and are a great thing to quiz people about in an interview.
  2. Design patterns are more of a feel thing, something that is figured out when you're factoring code. There is no way you will not discover these on your own, if you are experienced and smart.

I lean to the second category. The quizzers tend to be solipsists and may know little else (you'll see the same attitude with plenty of other development topics).

Now that you know how to take my writing about design patterns, let's suppose that you want to make a Windows form that becomes a little translucent when it is inactive. That may or may not be annoying, but there is a very straightforward way to make it happen:

// Form that becomes transparent when it is inactive
public class Foo : Form
{
    private const double c_InactiveOpacity = 0.25d;
    private double _prevOpacity;

    protected override void OnDeactivate(EventArgs e)
    {
        _prevOpacity = this.Opacity;
        this.Opacity = c_InactiveOpacity;
        base.OnDeactivate(e);
    }

    protected override void OnActivated(EventArgs e)
    {
        this.Opacity = _prevOpacity;
        base.OnActivated(e);
    }

    public Foo()
    {
        _prevOpacity = 1.0d;
    }
}

Which works fine, unless you want TWO forms that do that, the second with a special base class not related to the heirarchy of the first.

public class Foo2 : SpecialForm
{
    // criminy
}

This conundrum could be resolved in a few ways:

  1. Ctrl+C, Ctrl+V.
  2. Multiple base classes.
  3. What I am going to call the "Extender Pattern."

If you picked the first option, I think it'd be better for both of us if you unsubscribed from my feed. The second option would work fine, but CLR languages don't support it. Some days this bothers me, but most days I think it's a good thing. Especially when I factor a solution that is just as elegant.

I'm calling that solution the "Extender Pattern" without bothering to find out if anyone has used this term to describe anything else. As I explained above, this is more about artistic sensibility than it is about hard rules and book learning. Not that I'm anti-book learning.

The basic idea is this: you have a set of components that support certain properties, methods, and events. The forms, in this case. You add in to the mix a set of small objects whose only responsibility is to wait for events from the components and make very directed changes to them.

So here is such a class for the problem stated above:

// Alters the target form's transparency level
// when it is activated/deactivated.
public class TransparencyExtender
{
    private Form _target;
    private double _prevOpacity;
    private const double c_opacity = 0.25d;

    public TransparencyExtender(Form target)
    {
        _target = target;
        _prevOpacity = target.Opacity;
        target.Activated +=
             new EventHandler(Activated);
        target.Deactivate +=
             new EventHandler(Deactivate);
    }

    void Deactivate(object sender, EventArgs e)
    {
        _prevOpacity = _target.Opacity;
        if (_prevOpacity >= c_opacity)
        {
            _target.Opacity = c_opacity;
        }
    }

    void Activated(object sender, EventArgs e)
    {
        _target.Opacity = _prevOpacity;
    }
}

Given this, we can write our forms very easily:

public class Foo : Form
{
    private TransparencyExtender _tExt =
        new TransparencyExtender(this);
}

public class Foo2 : SpecialForm
{
    private TransparencyExtender _tExt =
        new TransparencyExtender(this);
}

Keep in mind that I am not claiming that this is original. It's really the same as a small secondary base class in C++. However, I think there's value in looking at the same problem in different ways.

In a real application I'm working on, I've written a handful of other window/control styles that can be applied and removed on the fly or from the designer. Again, not original, but I like my little framework. Perhaps I'll post this someday, or turn it into a product.

I like event/message-driven programming the more I try to use it. I'm using Windows Forms as an example here, but it would be wrong to assume that's the only place this could be applied. I've done the same kinds of things in ASP.NET.

No True Object Programmer, Part Deux

Edit (2/28): What I have to say about raising an event asynchronously in VB is very incorrect. If you got here by googling “raise event async VB“ (or thereabouts), do not listen to me. Read Bill McCarthy's comment about it.


Well, Bill loves VB.NET, and knows a lot about it. I am in a slightly different camp, in that I (arguably) know a lot about it because I am forced to use it at work, but I haven’t grown to love it very much.

But as to your difficulty in parsing VB.NET code, well as you said, VB.NET is actually more natural. It is probably more that you need practice reading and writing the code.

I concede that this is probably true. I’ve been staring at C/C++/Java/C# since I was 11 years old, so it’s quite likely that’s the only reason I find it more natural. It doesn’t really help that I switch between VB.NET and C# projects on an almost hourly basis these days. I’ll jump to the VB project and start typing:

StringBuilder sb = …

Whoops. Wrong one. Apparently I can’t make the jump as effortlessly as the woman shouting into a cellphone on the train next to me last week weaved an intricate and impressive unbroken stream of Spanish/English (“Spanglish?”).

So yes. Readability is probably a personal problem.

This started out, I guess, as a discussion about which language was “more OO.” That’s may be a vague metric, so I’ll try to limit the discussion here to which language lets you accomplish the task at hand in the simplest possible way with minimal connectivity and shared knowledge between your objects.

In the case of events, I think that at best, this is a draw. This is an opinion.

VB wins when it comes to a few useful abstractions: the RaiseEvent keyword, and declarative event handling (the WithEvents/Handles keywords).

In a comment on Bill’s blog, I referred to these as “leaky abstractions” (to borrow shamelessly from Joel). What I mean by that is, they work beautifully in the simple cases, but in more sophisticated situations they break down and you’re forced to understand what is actually going on. VB may or may not leave you with a way out, once you’ve done the learning bit.

My first example here was raising an event asynchronously. Here is code that accomplishes calling event handlers on another thread in C#.

internal class MyClass
{
    public event EventHandler MyEvent;

    protected virtual void OnMyEvent(EventArgs e)
    {
        this.MyEvent.BeginInvoke(this, e, null, null);
    }
}

Here is code that accomplishes the same task in VB.NET.

Friend Class SomeClass
    Public Event MyEvent As EventHandler
    Private Delegate Sub EventRaiserDelegate(ByVal e As EventArgs)

    Protected Overridable Sub OnMyEvent(ByVal e As EventArgs)
        RaiseEvent MyEvent(Me, e)
    End Sub

    Protected Overridable Sub OnMyEventAsync(ByVal e As EventArgs)
        Dim del As EventRaiserDelegate = AddressOf OnMyEvent
        del.BeginInvoke(e, Nothing, Nothing)
    End Sub
End Class

Bill’s correct, you can raise an event asynchronously in VB.NET, albeit in a roundabout way. Unless there's a radically different method I haven't thought of, I need to write and then call OnMyEventAsync, which calls a traditional event raiser on another thread.

Here is where I think the claim that VB is “more OO” breaks down. The representation of the event as a list of functions (which is what C# gives you) was significantly simpler for us in this case. We got the job done with less code, so in my mind C# wins the OO battle here.

As to events in Vb.NET, I'm sorry but there is no "inadvertant GC rooting". I don't know who told you that, but you/they were sorely mislead.

On serialization, Vb.NET has absolutely no problems with XML serialization. There is however an issue with binary serialization and MarshalByRef classes. The real problem is MarhsalByRef classes, eg a Windows.Form, cannot be binary serialized. If you need to work around that, you can do so in Vb.NET 2005, and more elegantly than C#.

Poor terminology on my part, I guess. What I was referring to with “GC rooting” was the situations where a programmer attempts to dereference an expensive object so that it may be collected. A common mistake is leaving events wired up (and hence, a reference that has a gc root).

Is that any more difficult to deal with in VB than it is in C#? No, not really. Touché. But am I justified in calling an event a “leaky abstraction” if they require a deeper understanding of function pointers and GC in order to keep your program from hogging memory? I think so.

So that leaves the last sitch: serialization. MarshalByRef is actually not what I was thinking about, but it’s closely related. MarshalByRefObjects are at least serializable, and unless you are persisting to a storage medium you will succeed in serializing a graph if your only mistake is having a ObjRef going along for the ride.

Objects that are not [Serializable()] at all are a bit more problematic. You’ll get an exception which will be difficult to track down if you have event handlers wired up to any of these. C#’s got an easy way out (google it; my post is getting really long, dammit). The hacks VB will force you into in some cases is likely to make you cry. I know it made me cry.

So which language is “more OO?” That’s impossible to answer objectively, and it probably makes no sense to even try, but I’ll tender a personal opinion.

My feeling is that VB gives you some keywords that are useful for simple OO. Unfortunately, it obscures some of the underlying nuts and bolts, and this gets in the way of your own attempts at OO abstraction. C#, on the other hand, is a little better at ensuring that the realities of the CLR are quickly accessible if you need them.

In an ideal world, we’d have both in one language. But forced into a choice, I’ll opt for seamless access to the guts. Keeping my own objects as loosely coupled as possible is what I’m most interested in doing.

No True Object Programmer

Did you love the No True Scotsman argument? Well, get ready for the arguments!!

Explicit Interface mapping. This is incredibly cool. Unfortunately a lot of people just don’t get how important this concept is to true OO.

He continues:

As to VB.NET over C#, VB.NET is actually a far more OO language when you look at the actual implementation details.

(did I hear a record scratch?)

Far more?

At the risk of Ad Verecundiam, I’ve actually been on the phone with a Microsoft employee who said these words: “C# is a much better choice if you intend to do object development.”

Bill doesn’t expand on that argument really, other than the appeal of the End keyword. It would be a silly thing to get into an argument about, but my feeling is that End XXX makes VB code less readable. I would like to see more reasons why this could be true.

I apologize for any haughty, dismissive tone. I wrote this while working on a brick of Parmigiano Reggiano and sucking down a bottle of Chianti, so it just kind of came out that way.