Learning Smalltalk

Smalltalk vs C# vs C++ - A generic template story

December 4, 2009

I got thrown in at the deep end at work recently. I was moved to work on a piece of software which was all written in C++. So I've been spending some time on the dark side.

I'm happy to say that all that power (complexity) has left a bad taste in my mouth. It's made me cling to my Smalltalk even more tightly, however I have to say C++ does have some pretty cool stuff going for it. The "simple" operator overloading (opposed to C#) ans also C++ templates.

I knew what C# generics were before I knew what C++ templates were. Although I knew that generics were based on templates, I'd never actually done anything in C++, so it was a kind of meaningless comment to me.

This post came about when I tried to write a simple Smalltalk like Interval class in C# and generics. I succeeded, but it required me to define two a generic Interval<T> class, two interfaces, one for doing the step addition, and one for doing the comparison between the current and end positions, and two implementations of the Additiona/LessThan operator interfaces. It worked, but damn it wasn't straight forward. I've put the code here if you're interested. I did two versions; One using anonymous methods, and one using interfaces. Interval.cs. This is not the "One True Way" (I could have used an enumerator and yielded each value, a new feature in C# 2.0.. anyways!) .. as you can see from the code, it's crufty. There is a lot of code to write for what should be something quite simple.

Next I wrote up a C++ version. Interval.cpp. Guess what, much simpler!

Finally here is a pseudo-Smalltalk version, because it isn't proper chunk format (I wrote it in notepad) which does the same thing. Interval.st.

One comment on this: I think it is the only time you'll see C++ code that is close to Smalltalk, and has the same requirements on the object the Interval steps over: that the object implements the messages #<= and #+. The issue with C# is that C# CAN NOT use operators with generics. I didn't realise why there was an uproar about this when generics for C# was first announced, but now I understand.

BTW, if you've never actually used Smalltalk before, there is already a very rich and useful Interval class which implements the collection protocol, so you can actually do things like iterate over it using #collect: #select: and so on. Very nice indeed. There is no such equivelent in the static world.

James has made a couple of posts recently on the issues with generics in C# and Java. Every time I start to write any generic code in C#, I wonder why people can make comments about Smalltalk being the train that "rusted at the station", when clearly that's just not possible when the Smalltalk train was made out of nice shiny stainless steel.

Update: Oops. Fixed the broken links

Dolphin

Smalltalk Inlining

December 4, 2009

Recently at a programmers meeting we were having a discussion about the inline keyword, and when it may or may not actually have the intended effect. It lead me to think about a shortcut construct Dolphin has which is sort of an inline (but nothing like the C++ form).

It actually came about when I was writing some extensions to the built in Dolphin Sockets package. Dolphin exposes enough of the Winsock library to implement completely functional Socket applications, however there are various socket options that you might want to add, which requires adding some loose methods of your own. ANYWAYS, I was asking myself a question: How to store constants?

  • In a Pool Dictionary
  • In a Class Message
  • Other

A Pool Dictionary was my newbie immediate choice. It maps straight onto the same "concept" of constants in any C language. It does require you modify the class signature to import the pool though?

Next I thought that the constants might be best implemented using class messages. Instead of having a RAAD_WRITE pool constant with a value of 1, I have a #readWrite class message which simply returns 1.

The only "downside" to this is that it requires a message send, which has more overheard than a pool constant (which is inlined at compile time)

However, Dolphin has special syntax for evaluating code at compile time only, ##(), useful for storing calculations which are more intention revealing as: minutes := ##(60 * 60 * 24) rather than minutes := 86400. You can apply it to message sends though.

So we have three options:

Pool Constant: value := READ_WRITE.

Class Message Send: value := self class readWrite.

Dolphin Syntax: value := ##(MyObject readWrite).

The CompiledMethod for both the Pool COnstant and Special Syntax form are identical. The compiler inlines the value (1) into the bytecode. Howver the message send bytecode contains the additional overhead of sending the #readWrite message to the instance methods class. So my question is, which is the best option?

In VisualWorks, I would assume that the JIT Engine is good enough to work out that the message #readWrite is constant, and should be inlined anyway, so I don't think you would even bother with a pool constant in VisualWorks? Then again, how do you inline a message which may be overridden by a subclass? Not for my feeble mind to understand... 

However, in Squeak or Dolphin, which are not JIT capable, you would probably want to use pool constants. I do like the Dolphin compile-time-expression syntax though.

Smalltalk

Why dynamic?

December 4, 2009

Last weekend I slapped together an SCGI handler for Dolphin. Actually it's pretty generic it could probably run in any dialect. Anyways...

While I've been testing it, I thought it might be useful to have counter for the number of requests the SCGI Handler has served so far.

So I added a requests instance variable, added two methods to get the current requests, and another to increment the requests when ever a request is handled, and I was done.

What does being a dynamic environment have anything to do with it? Well I hadn't actually taken the server down at any time. So while I was adding new functionality to it, it was still running, and still serving requests. Now the instance that is processing SCGI requests from Apache responds to the #requests message, and reports on how many connections it has handled.

No need to restart the system/server. How cool is that?

.NET

More on Extension Methods

December 4, 2009

I spent some time playing with extension methods last night. They're what I expected. The compiler replaces your psuedo-instance method calls, with your static method definitions. It's a nice feature, and will lead to certain pieces of code looking simpler.

I was still hopeful, so I started testing out some very basic double dispatch type code (Think Magnitude classes, think Seaside rendering framework). It ended up a failure. I ended up writing a lot of duplicated methods with overloaded function signatures to get the compiler to do what I wanted.

I even tried using generics to force the compiler into doing what I wanted, and that didn't even work. Here is the example. Please look at the code.

The output I am looking for is:

Integer: 1
Default
String: Hello
DateTime: 16/09/2005

Example one outputs the following:

Default
Default
Default
Default

While this might seem strange to those with a Smalltalk background. It isn't when you realise what the compiler is doing in the background. What the C# compiler does is just replaces calls to printOn with the closest matching printOn method it can find in the LooseMethods class (LooseMethods is just my name, it doesn't actually matter what you call it). In the case of example one, the closest matching method is always PrintOn(this Object obj, TextWriter writer). So I thought, Ok, I'll get a litlle trickier, and use Generics to try and help the compiler. Example two is using Generics. And the output?

Default
Default
Default
Default

Strange? Probably. I think that this version should have had the correct output, but it didn't. However once I got to that point I wasn't actually caring any more, because the first example let me down so much.

The only way to get the code working "correctly", is to provide overloaded methods on the Printer/GenericPrinter for each specific type you intend to handle, it also means if you have abstract types, or cast something to "Object" (Or pull it out of an ArrayList of Objects) you won't get the behaviour you would if you were using Smalltalk.

Having said all that. The extension methods are still a nice way to tack on domain specific methods to existing classes, but definitely not a solution to mix-ins or true generic programming in something like Smalltalk.

general

Actually, maybe Extension Methods aren't as fantastic as I initially thought...

December 4, 2009

Reading the spec.. Its not going to be as useful as I initially thought.

Given that you can not declare a static method virtual, you can't add an extension method to Object, and then override that in your own objects, although I guess you could maybe declare a virtual method on your own heirarchy, and then every other (non-heirarchy) object gets the default Extension version, and then hopefully you can just add additional extension methods for any other built in types.

Also it only applies to Methods, but I'm assuming properties will also be covered because they're just syntactic sugar for methods anyway... so you could do something like...

public static class BaseExtensions
{
	public static TimeSpan Days(this Int32 value) {
		return new TimeSpan(value, 0, 0, 0);
	}

	public static DateTime FromNow(this TimeSpan value) {
		return DateTime.Now.Substract(value);
	}
}

And convert code that looks like this:

DateTime date = DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0));

Into this:

DateTime date = 7.Days().FromNow();

I'd argue that the Smalltalk equivilent is more readable (7 days fromNow), but still, there is some interesting things that could be done to enhance the object heirarchy in the .NET Framework, on a project by project basis of course.

I'm so sick of seeing projects with classes like StringUtils or CollectionUtils.

I'm just thankful I can go home at night, boot up the laptop, and use a real genuinely modifiable environment.

.NET

LINQ and Extension Methods

December 4, 2009

LINQ is the new integrated query engine for the .NET platform. There is a nice write up about it here.

However, one critical piece I missed in any of the information available on the internet so far, is a tiny little feature called Extension Methods.

Eric Gunnerson gave the details:

The second addition is something known as an extension method. Say that you're writing a new web-based game, and you need a way to convert from standard English to Leet Speak. You would like to be able to add a method to the string class, but because String is sealed (for some very good reasons), you can't. What you end up doing is writing a static method and calling it, but it's not very seamless.

With extension methods, you can write the following:

public static class StringExtensions
{
    public static string MakeLeet(this string source)
   {
      // return the Leet string here...
   }
}

You then write:

string s = "I have found the programming features of C# 3.0 to be most envigorating";
string leet = s.MakeLeet();
Console.WriteLine(leet);

and you get the following as output:

y0 d00d, C# 3.0 rox0rz, w00t!!!!!!!!!!!!

While I'm guessing you don't get access to the internals of the objects you tack your new methods on to, this is better than nothing. I'm not a fan of the syntax, but who cares, Wow, You can keep your LINQ. This is the feature I want. I requested this as a feature in C# long long ago (after really getting into Smalltalk), as have many other people, and lo and behold, it will be available in 3.0. This should allow you to do away with most is/typeof/GetType() code once and for all. Now if only they could some how work out a way to provide real classes, with real class methods.... For further details check the language spec.

"Re-inventing Smalltalk one decade at a time."

general

The US is definitely not prepared for a terrorist attack.

December 4, 2009

4 year since the attack in New York. 4 years and two wars later. Those of us who live in the rest of the world were pretty sure that the USA was spending lots of money on systems to make their country safer for citizens. I'm pretty sure now that this has been 4 years of smoke and mirrors.

You would think that given the situation the US finds itself in these days, that at least some amount of money would have been put aside for help/training/aid in a major emergency. ANY emergency. I guess that isn't the case.

Witness Katrina devastating the city of New Orleans. Now swap Hurricane for Nuclear detonation. Instead of putrid city sewage, replace that with radioactive material. Imagine the thousands of people actively turned away from help, and forced back into the glowing radioactive city of hell.

I think the worst "political bullet dodge" I have heard a politician vomit (EVER!), was that Katrina and caused more damage and chaos than anyone could have possibly imagined.

Looks to me like National Geographic should start publishing lotto numbers.

Dolphin

Nice looking Dolphin site.

December 4, 2009

Only noticed this by referrer links: Dolphin Map. Nice one Udo.

Dolphin

More Dolphin 6 News

December 4, 2009

I've been plugging away at a port of Seaside. It's been a work in progress for many months, shelved for a while, and now I'm back on it. Anyways...

I contacted Andy to see if Object Arts would be offended if I ported the old LPC Socktalk code to Dolphin Value Edition. The reason being Dolphin VE doesn't have a Sockets package, which obviously means no network support. A bit of a problem if say, you wanted to run Seaside/Swazoo.

Andy said it would be no problem, but suggested that I would be wasting my time, given that the Dolphin 6 Community Edition will include the Sockets package! Good news all round.

A month or so ago I begged for Dolphin 6 Community Edition to include sockets support. Looks like the begging was successful.