I’ve been experimenting with window managers lately: fluxbox, openbox, awesome, and musca. Fluxbox and openbox, are pretty much just generic window managers, at least in my eyes. That said, they are well worth using, for most peopel. Awesome and Musca are tiling window managers, and a lot more, eh, minimalist. While I used to collect window managers, among quite a few other odds and ends back when I had time for it: but I have never done the “Tiling thing” beyond a very brief test drive of dwm.

Awesome and Musca create an interesting experience: you create the windows, the window manager, manages them. It’s almost alien lol. Normally you create a window, the window manager figures out where to draw it. You do the rest, e.g. by resizing and moving it around as necessary. In these tiling window managers however, newly created windows are automatically arranged and sized by dividing containers.

Launching your first window is like maximising, lauching a second window causes everything to resize and give each program half the screen, and so on based on some tiling pattern. The most used seems to be 1 half sized window left and 2 quarter sized windows right; works better than you might think. Rather than resizing the windows individual, you resize the containers. So if the screen is laid out as:



|         | term |
| Firefox |------|
|         | chat |


>

Selecting either the term or chat window and attempting to resize will resize all three windows. Try to enlarge the chat window horizontally, and Firefox will shrink and term grow, horizontally. Try to shrink the term window vertically and the chat window grows vertically, and so on.

It’s mind blowingly better than what the style of window management people are used to these days, which dates back to like Mac OS 2 or Mac OS 3 back in the ’80s. It is also a little bit awkward to let the computer take care of something, that you’ve been doing by hand for almost twenty years!

Relishing the experience however, has made me think of something different. I was just experimenting with the MinOverlapPlacementPenalties and MinOverlapPercentPlacementPenalties settings in FVWM, and it hit me. What if you could dynamically define what windows are important? I.e. what screen space should have more “Don’t cover this up unless necessary”, and how big a frame (i.e. for auto-tiling) should be, and so on?

It is technically possible, if perhaps computationally ‘interesting’ to figure out at the machine level. The windows that spend the most time focused or are most often gaining the focus, would be prime candidates. If the user ‘uses’ the window more than others, give it a larger chunk of available space scaled to its idea of how much space it needs, then prefer minimising the percentage of those windows being covered over or shrunken to absorb other windows in the same screen space.

It is food for thought!

Hmm I must admit that custom configuring a Linux kernel, seems to offer three possibilities:

  • Lean, mean, and sexy kernel build
  • More modules than you can shake a stick at
  • Major headaches

I’m tempted to configure for a balance between the first and second, it is an interesting idea though. If I tuned a kernel build for my very specific system, it would strip out most of the usual bloat. The downside is there are so many configuration options, that making the config might take longer than compiling Linux!

A reminder of why I don’t miss Ruby

About two minutes if thumbing around the official documentation for Ruby’s standard library, I quickly realised it would be faster to Google how to use the module for MD5/SHA* stuff than read the official stuff:



    def encrypt_password
      # This is just a place holder implementation for now
      require ‘digest’
      self.password = Digest::SHA512.hexdigest(password)
    end
Compare the documentation for Ruby’s Digest to Pythons’ hashlib. Even an uncommented C++ header file would be more useful than the docs for Ruby’s Digest module :-S.

Programming: Things We Should Take For Granted

Since an anniversary is coming up, and I’ve accumulated a nice chunk of experience in the years since I started learning how to program—I’ve been reflecting on what languages have thought me, about getting stuff done. This is also, obviously a rant.

That’s the cardinal rule. I don’t give a shit if it has more fan boys than Apple, or if it’s the most brilliant idea since they blamed the invention of fire on Prometheus. It has to be useful for getting stuff done!

Here’s some nick nacks that you should expect from programming languages since the 1970s, oh how little we have moved forward…







Serious Scoping

The ability to define modular scopes. In most cases this simply has to do with managing namespaces, either via built in language constructs (C++, PHP5.3, C#) or the natural order of modules in general (C, Java, Python), but really it’s trivial. It kind of has to do with building out of the whole ‘scope’ concept in general.  In other wards, we could say that a namespace is a kind of scope. Looking at the Wikipedia page, it seems someone agrees with that notion. Using this lingual functionality, you essentially have object oriented programming at your disposal: sans the the ‘tors hidden behind the curtain. Some languages even thrown those in, making OOP a real snap. While the inheritance model is popular and the less well known prototyping model is interesting, they are not required for achieving the core aims of object oriented programming; at least not the ones touted ;).

Anonymous Executable Code Blocks

Basically anonymous functions. This means we can write higher order functions, in other words functions can take and return functions. We can even do part of this in C through the use of function pointers (and C++ also has function objects, which are nicer if more verbose). But we can’t define those functions on the fly, right there and then, making things harder. C++ and Java will at long fucking last be gaining a solution to this, if we live long enough to see it happen. Most languages worth learning have made doing all this pretty easy.

Abuse of Lexical Scoping

This usually means lexical closures, which in tern makes the aforementioned anonymous functions a prerequisite for happiness in normal cases. They could also cook up something different but equivalent to that for a change, but alas don’t count on that! So the anon’ func’ thing is where it’s at for now. If the language lacks closures, it’s obviously a fucking moron, or it had better be old. C at least has that excuse. What about you Java? The road to 7 is a sick joke.  Anyway as I was saying, if you have both serious scoping and a way to define executable blocks without a name, you ought to be able to treat it just like anything else that has a value. Here’s an example in pseudo code:

var x = function {
  var y = 0
  return function { y = y+1; return y }
}

test1 = x()
test2 = x()

do { test1(); test2() } for 0 to 5

You can expect either of two things to happen here:

  1. Every function returned by x will increment the instance of y stored in x.
  2. Every function returned by x will get it’s own private copy of y.

The latter is the norm. I rather think the former is better, if you also provide means of doing the latter, syntactically; this makes the closing over of data more explicit. In terms of how it would look, think about the static and new keywords in many staticly typed OO languages and copy constructors, then you’ll get some sort of idea. I blame my point of view on this on spending to much time with Python. Ditto for my thoughts on memory allocation, courtesy of C.

While we’re at it, if the vaguely EcmaScript like pseudo code above was a real language: you should expect that function x {} and test1(), test()2 for … to be sugar for the relevant snippets out of the above, or else you ought to break out the tar and feathers! I wrote them as I did to make it painfully obvious what’s happening to people still struggling at var x = function {}. Kudios if you figured out why I wrote do { } for instead of for {}. If you’re laughing after reading this, after reading the above paragraph, yippe :-). If you’re now scrolling back up, then sorry.

Just shuddup & build it!

Which is so sorely missed in most compiled languages. There should be no need to define the relationship between modules or how to build it, it should be inferable from the source code. So should the type of most things, if the Lisp, SML, C#, and C++0x people are anyone to listen to. Building a cross platform C or C++ app is a bitch. Java is gay. Most dynamic languages are fine, so long as you keep everything in that language and have no C/C++ extensions to build. The closest that is possible to this “Just shuddup & build it” concept in most main stream languages, depends on dedicated build infrastructures built on top of make tools (FreeBSD, Go, etc) or IDEs. Either case is a crock of shit until it comes as part of the language, not a language implementation or a home brewed system. Build tools like CMake and SCons can kiss my ass. It’s basically a no win situation. JVM/CLI-languages seem to take a stab at things but still fail flat; Go manages better.

Dependency management also complicates things, because building your dependencies and using them becomes part of building your project. Most dynamic languages have gown some method of doing this, compiled ones are still acting like it’s the 70s. For what it’s worth, Google’s goinstall is the least painful solution I’ve encountered. Ruby’s gems would come in second place if it wasn’t for Microsoft Windows and C/C++ issues cropping in here and there. Python eggs and Perl modules are related.

Here’s an example of brain damage:

using Foo;

class X {
  public test() {
    var x = new Foo.Bar();
    // do something to x
  }
}

Which should be enough to tell the compiler how to use Foo. Not just that you can type new Bar() instead of new Foo.Bar(), should you wish to do so. Compiling the above would look something like:

dot-net> csc -r:Foo.dll /r:SomeDependencyOfFoo.dll
mono$ mcs -r:Foo.dll -r:SomeDependencyOfFoo.dll

Which is a lazy crock of shit excuse for not getting creative with C#’s syntax (See also the /r:alias=file syntax in Microsoft’s compiler documentation for an interesting idea). The only thing that a using statement lacks for being able to tell the compiler, is what file is being referenced, i.e. where to find the Foo namespace at run time. Some languages like Java (and many .NET developers seem to agree) impose a convention about organising namespaces and file systems. It’s one way, but I don’t care for it.

What is so fucking hard about this:

using "Foo-2.1" as Foo;

in order to say that Foo is found in Foo-2.1.dll instead of Foo.dll. If that sounds like weird syntax, just look closer at P/Invoke, how Java does packages, and Pythons import as syntax.

So obviously we can use the languages syntax to provide whatever linking info should be needed at compile time; figuring out where to find the needed files at compile and run time is left as an exercise for the reader (and easily thunk about if you know a few language implementations).

In short, beyond exporting an environment variable saying where extra to look for dependencies at compile/runtime, we should not have to be arsed about any of that bull shit. If you’re smart, you will have noted most of what I just talked about has to do with the compiling and linking against dependencies, not building them. Good point. If we’re talking about building things without a hassle, we also have to talk about building dependencies.

Well guess what folks, if you can build a program without having to bitch fuck about with linking to your libraries, you shouldn’t have to worry about building them either. That’s the sense behind the above. What’s so hard about issuing multiple commands (one per dependency and then again for your program) or doing it recursively. Simple. But no, just about every programming language has to suck at this. Some language implementations (Visual C++) make a respectable crack at it, so long as you rely on their system. Being outside the language standards, such things can suck my rebel dick before I’ll consider them in this context.

Let’s take a fairly typical language as an example. C# and Java for starters, and to the lesser extent of C and C++ as far as their standards allow, we can infer a few things by looking at source code. Simply put if the main method required for a program is not there, obviously the bundle of files refer to a library or libraries. If it is there, you’re building a program. Bingo, we have a weener! Now if we’re making life easier, you might ask about a case where the code is laid out in the file system in a way that makes that all harder to figure out. Well guess what, that means you laid it out wrong, or you shouldn’t be caring about the static versus dynamic linking stuff. D’uh.

Run down of the Main Stream

Just about every language has had serious scoping built in from day one, or has grown it over the years, like FORTRAN and COBOL. Some languages get a bit better at it, C# for example is very good at it. C++ and Python get the job done but are a bit faulty, since you can circumvent the scoping in certain cases; although I reckon that’s possible in any language that can compile down to a lingual level below such scoping concepts. Some might also wonder why I had listed PHP 5.3 earlier when talking about “Serious scoping”, well 5.3 basically fixes the main faults PHP had, the only problem is in common practice PHP is more often written like an unstructured BASIC. Die idiots Die. Languages like Java and Ruby basically run it fairly typical. By contrast Perl mostly puts it in your hands by abusing lexical scope. I love Perl.

In terms of anonymous functions, Perl, Lisp, and SML are excellent at it and modern C# manages quite nicely (if you don’t mind the type system). Where as C, C++, and Java are just fucking retards on this subject. Python and Ruby also make things someone icky: functions are not first class objects in Ruby, so you have to deal with Proc to have much fun; like wise Pythons lambda’s are limited, so you usually have to result to Pascalesque scope abuse to manage something useful, in the way of nesting things in the scope. Lisp is queen here, Perl and JavaScript are also very sexy beasts when getting into anonymous functions.

In terms of lexical closures across languages, I’ll just leave it to the text books.

As far as being able to shout “Just shuddup & build it!”, they all suck!!! Most of the build related stuff is not iron clad defined by the C99/C++03 standards documents, and you are a fucking moron if you expect the entire world to use any given tool X to build their C/C++ software o/. That rules out things like Visual Studio (vcbuild/msbuild), Make, and all the wide world of build tools you can think of. The most common dynamic languages in the main stream are better. In order of least to most suckyness Perl, Ruby, and Python make the process less painful; my reason for rating them thus is because of extension modules. PHP and Java, I’m not even going to rate. They provide tools to help you build and distribute your extension modules and your native modules. The only gripes come from the principal language implementations being implemented in C. For pure modules (E.g. no C extensions), they are excellent! The least painful language that I’ve gotten to use, has been Go – which has the best thing since CPAN. Which is still harder than it should be o/.

The question I wonder, is if it took until like the 2000s to get closures going strong after the serious scoping stuff took off by the late 1960s/early 1970s; will I have to survive until the 2030s-2050s to be able to bask in the wake of just being able to build stuff in peace? Most likely old friend C will still be there, but other languages should reach main stream in another 30+ years… not just the ones we have now. That, or we could go back to lisp…. hehehe.

Fun with linenoise

Well, it’s been a fairly productive night; I’ve managed to conclude the days research, take care of a few odds and ends, plus wrap up a few changes to linenoise. It’s essentially a micro-library for giving console programs capabilities for line editing,like GNU readline—sans the migraine headache.

On/off I’ve been tinkering with it since mid August. The linenoise API has almost everything you could want except for a few minor things, and it is insanely easy to use. As to what’s lacking: some common keybindings, direct access to the loaded history, and a completion hook. None of which is hard to add. Since it’s so damn nicer to use than readline, but lacking a few keybindings that I’ve come to rely on; I’ve been adding them to my own fork on github. Pull requests periodically sent to the author of course. It will likely be my first choice whenever requiring line editing support in one of my applications.

Two things that interest me also, is a Windows port and implementing completion. The former is a bit of work, where as the latter is only an intellectual issue: what keystroke to use. Using tab is an issue, in that one has to be able to figure out when to insert a tab and when to trigger completion. Something more like the (real) korn shells “escape escape” provides the simplest means.

Linenoise is just one of the many things on the back burner that I would like to bring closer to the front flame.

To tired to focus on code at the moment, yet much to awake to sleep o/. Been tinkering with an old project: tpsh. Mostly I’ve been polishing the codebase and doing a bit of refactoring; there’s no a debug mode, which reduces some of the cruft that’s crept in from testing. Sometime I also need to import the test scripts lol.

One of the changes, is adding support for running off the Strawberry Perl distribution rather than ActiveStates Perl distrio for Windows. The downside is, most of tpsh biggest problems have to do with Perls portability, namely Windows quirks. Gotta love’em.

Since the merge of the “Code generator”, tpsh has supported a very limited subset of sh script. Not very usefully however, since the shell doesn’t have a real concept of $? yet. Likewise there needs to be some changes in the handling of environment variables. Most ideal IMHO, is a tied hash wrapping $ENV (a magicly tied hash of environment variables) with the ability to hook reads and writes, etc. Preferably in a user-exposabe way that can be extended by shell functions, rather than being limited to the scripts own Perl code.

It’s the more general case however, of having to build up the language rather than use its building blocks. The problemo isn’t in maintainability, but in portability and development time.

Having reactored a chunk of the shells initialization code,  I know that I’ll have to retackle the readline stuff.  To say that I hate Term::ReadLine would be an understatement. I’ve no love for the GNU Readline API either (I would use linenoise), but the GRL C API isn’t as nasty in practice as the plugable Term::ReadLine system Perl uses. The only good thing I can say is that there is a semi-useless stub version included. Licensing issues of just having a GRL backend aside >_>. In my experience, mileage varies quite a lot between Perl readline pacakges, even within the scope of the fscking manual. It’s just a load of crap.

Actually if there’s a way of accessing the API  functions needed for unix termios / windows console, I would be tempted to throw out the fucking thing and just write a Term::ReadLine::SANE module based on linenoise (A C library). I’m more familiar with the unix parts of that.

The STAMAN Project: Phase IV,

Having thought of tasks and storage formats, it’s now time to figure out an implementation language, i.e. what programming langauge am I going to write the task manager in.

O.K. based on what we’ve got so far, it is easy to infer the following is worth having:

  • Portable between systems—a must for me 😉
  • Easy access to SQLite—usually trivial.
  • Better tools than gmtime().
That means this page is rather useful, for what languages can be ruled out. In my répertoire this means Go (aww), Scheme, AWK, and shell languages can be skipped. Reason being the portability of Scheme bindings in general, and the others lacking sufficient portability (for my taste) at this time. That still leaves about 13 languages, lol. PHP, Java, Lua, JavaScript, and X86 assembly are easy for me to rule out. Reasons for that can all be easily guessed; at least if you remember how much I enjoy Suns Java tools. JS/Lua are great choices but I don’t want to screw with the bindings and stuff.

I’m not very interested in compiling SQLite in C/C++ on Windows, or the CLI binding everywhere. So this effectively makes the choice Perl, Python, or Ruby. Out of those three, none is perfect either: perl doesn’t come with the required database code, it just has the definitive interface for databases everybody mimics. Python and Ruby on the other hand, come with SQLite bindings—which many distributions separate out into separate packages. It’s just a lose, lose situation when you think about dependencies, but it does beat writing your own everything for every program. Sometimes. Setup with these three dynamic languages would be easy though, in so far as we’ve gotten with the above.

Time handling is another issue. Perl has fairly minimalist handling of time built in, but on the upside, if you need it, it’s probably three abreast on CPAN. Time::Format and the core Time::Piece module each come to mind. What isn’t built into Perl, often comes with it or can be added to it. Ruby provides a simple but effective Time class, that makes for more natural code than you may expect. More complex operations will require Googling for a Ruby gem, or hand coding it on demand. Python on the other hand provides a comprehensive datetime module, and supporting time and calendar modules, all out of the box! I would say Python takes the lead here.

Rule one of getting work done: know how to leverage libraries.

In terms of programming languages, Perl, Ruby, and Python are generally equal enough for most tasks, so long as you don’t shoot yourself in the foot. Some subtle differences that personally irk me:

  • Perls autovivification can be almost as much a miss-feature as it can be a convenience. You’ve just got to learn the damn language :-P.
  • Ruby functions are not first class objects! Some things can also be weird if you’re not used to Ruby.
  • Python doesn’t always stand up well to typos, especially if they involve indentation o/.

Because of how many lines of code I’ve done in Python over the years, I am more familiar with it’s set of “Irks” than Ruby’s, like wise I know Sh, C, and Perl more intimately than other languages, so I really know their irks. For perl, it’s mostly thin things that get in inconvenient when combing the warnings pragmata with the nature of perl syntax. They spiritually conflict at times. Under Ruby, I mostly find gripes that have a bigger place in programmer culture. My issues with Python generally have to do with trade-offs that I disagree with as a matter of my convenience, even if it usually results in a Good Thing overall. It comes from a C-oriented background meshed with a love for the Perl programming language.

This is a fact: you will always be irked by your programming language, if you use it enough. What can I say, nothing is perfect. Shoot!

For this particular application, there’s some things worth noting also: language portability. If the machine doesn’t run perl, it’s not a real computer. Most systems you’re likely to care about will run Ruby and Python, and there’s probably a crusty old version of Python for those you don’t (nor directly should). In contrast however, Perl is often a lower level of “Cross platform” behaviour than Ruby/Python. You’ll find this highlighted well in the Camel book. One reason I use Python frequently, it always behaves as expected without so many subtle hiccups.

How much this pertains to the current matter, i.e. implementing STAMAN. Perl is the most universally available language, and I’m more prone to need such a feature than most people. A plus over Ruby is no crappy 1.8.x/1.9.x porting issues…! Of course however, I have a camel to ask about minor details, hehe. In my experience the Python 2k/3k thing is less issue than Ruby’s for writing code yourself, more of an issue in leveraging existing code.

So I reckon, that means Perl or Ruby is best called for here. I exclude Python, because I just use the frick’n thing to often.

The STAMAN Project: Phase III, of tasks and storage formats

At least, for me, there are only two pieces to STAMAN that are not trivial to work out before writing the code: choosing the storage format and implementation language.  Both also happen to be areas where experience strongly augments ones intrusion, more so than the rest of the app’.

In the design outline, I noted that YAML would work quite nicely, yet an exposition of the outline suggests that something closer to SQL could better serve the applications design. The reasons behind it should be fairly obvious, if you’ve ever worked with textual data before.

During Phase I, I concentrated on the data involved with task management. It’s not hard to implement an SQL schema capable of representing that. Even better, most dialects offer useful features for handling times/dates. Virtually every programming language has a way of interfacing with such an SQL database, either through natural bindings or calling out to scriptable client programs. SQLite, MySQL, and PostgreSQL in fact provide both means, I’m not familiar with MSSQL. So that’s a big set of pluses all the way around. We even get a reusable DSL to help without having to write it!

The problem however, becomes one of migration paths: what happens if you need to change the data structures, perhaps heavily? That means having a lot more work whenever restructuring is needed, and it’s IMHO, less scriptable than a little perl golf: sufficiently so that I’m not going to screw with it. Insert shameless plug for Ruby on Rails here ;).

In a commercial environment; i.e. oriented on making money off the program, XML would be more likely than any other textual format, but not very convenient for me. I also hate XML parsing with a passion. It is however sufficient for getting the job done, if a bit, ahem, jacking the amount of internal documentation you need to write (or later wish you had) several notches higher than it need be.

Someone might think of a simple Comma Separate Value (CSV) format, but CSV is any thing but simple. Don’t believe me? Just think about data that may contain commas. That being said, the only good things I can say about CSV, from a programming perspective, is CPAN rocks. Unless you’re munging address books or spreadsheet data around, and need a LCD: it is best to avoid CSV, period.

The best bet, in terms of structured text: but one sufficiently able to represent the data set, and be easily edited by hand. What is really needed is a dedicated format: enter YAML. It’s basically a hierarchial way of recording data as sequences of elements and key/value mappings. Works excellently.

The SQL solution relinquishes fine control over the operations, where as the YAML method is assured to slurp up memory in proportion to the input. It’s a lot more like DOM oriented XML, only the translation between the code and textural representation is a hell of a lot more natural. When working with program generated output, it also doesn’t need to be fed through a pretty printer to be comprehensible, which can’t be said of XML—without more pain for someone.

Pro YAML:

  • Easily edited by hand (notepad) and many unix tools.
  • So simple you can skip reading the spec0
  • If you have to write your own parser, make it YAML and save grey hairs.
  • It’s easy to serialize/marshal data around, as easy as it gets without eval().
  • More likely to benefit from compression.
Pro SQL:
  • Less imperative-style code to be written.
  • The hardest processing code is already in the database engine.
  • Can focus on querying data, not parsing it.
  • Languages/frameworks are more likely to ship SQLite bindings then a YAML parser.
Con’ YAML: 
  • It really is as simple as it looks.
  • You have to write your own list/dictionary handling code.
  • Scales less.
Con’ SQL:
  • You have to learn basic SQL.
  • Not the most fun in some languages (C, C++, Java, and C#).
  • Can’t really get at the data, short of a database client.
Note that I haven’t said anything about separating the data store from the client application: using an SQL server is just as viable as storing YAML files on a network drive. It really is that simple.
My personal view? SQLs virtues likely outweigh YAMLs here—unless you’re going to be designing by exploration. I’m not in this case, and I am also competent enough not to shoot myself in the foot. If I was smart, I would make the application wide interface to the data store more abstract than writing SQL queries all over the place like an asshole. Yes, I can be that smart. Don’t tell your neighbours.
0: I read the YAML specification the first time I used it for a project, which was for a rake based built system. How else could I expect to hand write my build spec’s in YAML? :-).

Somehow, I’m really not sure what is worse: the curse of experience or a gringo’s rush.

Concept: tried Quassel IRC, didn’t like it – good software but not my bag. Switched to ircII – love the interface, don’t want to screw with hacking it. IRC clients are simple creatures but tend to be crap. While I could live with (or suitably script) ircII to my hearts content, I also want a more Windows usable client too.

Problem: When it comes to programming languages and what I want (something very ircII like, yet rather lisp like in a way). I can see all the pluses and minuses of any given implementation. If I was a nub, I would just pick a language, rush into it, and try and dig myself out.

Knowing so much can sometimes be a real let down o/.

For those that don’t know it, ircII is a very old school IRC client, even by the best CLI-whorish standards.

The typical IRC client is arranged as a text display area, for the current channel; a line edit for your messages; modern ones include a panel to list names in channel and some “Tab” like interface for marking the channels you’re chatting in. Text mode IRC clients work this way too.

ircII on the other hand, routes everything into a central display area and places a line edit under a “Status line”. Rather than jocking between tabs to see what’s up in other channels—which is very wasteful, even when using keystrokes: in ircII you simply use a command to change your current channel. Exempli gratia:

Typical:

  1. Click #chan1 tab
  2. Read what’s going on
  3. Reply if desired
  4. Change back to #chan0
Becomes:
  1. See what’s going on both in #chan0 and #chan1
  2. Use /j #chan1 to make your subsequent messages go to #chan1 instead of #chan0 until the next /j[oin] command.
It’s just more convenient for me than the ‘modern’ user interface. I like efficiency.

In terms of implementing something like this portably (unix/win), the issue is simply line editing. That’s not a subject I enjoy. Having worked on a unix shell, I know it’s a bitch of a subject. Colour support is another, but minor one. Cmd.exe doesn’t understand what a DEC does.

I also want something dynamically reprogrammable on the fly, basically access to a REPL. O.K. so lisp spoils you. This makes dynamic languages more convenient; which is also it’s own can of worms.

That’s the fact of Programming, it’s all a Kobayashi Maru problem: you’ve just got to deal with it.

Reflections on C#

Lately, I’ve been trying to use C#. No sense in learning a language and never using it, ever, lol. Over the years, I have generally skipped getting into C# – to much like Java for my tastes. Some months ago I picked up the lang’ as just a way of passing time. Found it interesting to note that C# was also about 3-4 times more complex than Java, syntactically. By contrast most of the complexity in Java comes from APIs or hoops you have to jump through to do xyz.

In putting my C# knowledge into practice, I’ve found that most of my linguistic gripes against learning it have been solved in .NET 3.0 / 3.5, and making portable code that works under Winows and Unix is just as easy as expected: in fact I test everything against the compilers from Microsoft and Mono. I’ve not had any troubles, and I am using like last years Mono version.  Although, I must admit that I think of Monos setup as the “Novell implementation” and .NET as Microsoft’s >_>. The portability of C# is every bit as good as Java and dynamic languages. In fact, if it wasn’t for the Mobile version (Java ME), I would say C# is more portable than Java these days.

C# already have features that are expected in Java 7 and C++0x, but everyone will be damned if they will get to use any time soon. To top it off given the blasted prevalence of Windows machines, just about everyone will have a liveable version of the .NET runtime that you can program to in a pinch. Between actually using the computer, newer Windows versions, just about all of them will have a modern version. Plus several popular unix applications (and parts of the Gnome software stack) are written in C#, so the same goes for many Linux distributions. Alas the same can’t be said of getting various C/C++ libraries compiled….

Compared to Java, C# is a mixture of what Java should have evolved into as a business language, and a bit of C++ style. C# also goes to lengths to make somethings more explicit, in a way that can only be viewed as Java or COBOL inspired. I’ll try not to think about which. I think of professional Java and C# programming as our generations version of Common Business Oriented Language without the associated stigmatism.

The concept of “C++” style in C# however, is something of a moot point when we talk about Java too. Here’s a short comparison to explain:

// C++ class
class Name : public OtherClass, public SomeInterface, public OtherInterface { /* contents */ };


// Java class
public class Name extends OtherClass implements SomeInterface, OtherInterface { /* contents */ }

// C# class
public class Name : OtherClass, SomeInterface, OtherInterface { /* contents */ }
It should be noted in the above example, that C++ trades the ease of control over class visibility for fine grained control over inheritance. AFAIK, Java/C# has no concept of private / protected / virtual {x} inheritance. Likewise C++ is multiple inheritance, while Java and C# are single inheritance. This all leads to a more verbose class syntax in C++. 
Now this one, is where you know how Java is run 😉
// C++ foreach, STL based
std::for_each(seq.end(), seq.begin(), func);

// C++ foreach, common technique
for (ClassName::iterator it = seq.begin(); it != seq.end(); ++it) /* contents */elementtype

// C++ foreach, to be added in the *future* standard (see below for disclaimer)
for (auto elem : seq) /* contents */

// Java foreach, <= 5.0
for (Iterator it = seq.iterator(); it.hasNext();) /* contents */

// Java foreach, >= 5.0
for (ElementType elem : seq) /* contents */

// C# foreach
for (var elem in seq) /* contents */
As you noticed, there’s three different examples for C++. The first uses the for_each algorithm and leads to rather simple code; the second is the most common way; the third is being added in C++0x and I haven’t bothered to read the details of it, since the version of GCC here doesn’t support it.
C++ again gives very fine grained control here, the for_each algorithm and iterator methods are extremely useful once you learn how C++ really works. If you don’t, than please don’t program seriously in C++! The C++0x  syntax is +/- adding a foreach keyword, exactly what you would expect a foreach statement to look like, if C++ had one. Some things like Boost / Qt add a foreach macro that is mostly the same, but with a comma.
Java enhanced the for statement back in 2004, when Java 5 added a foreach like construct. Java hasn’t changed much since then. When you compare the keyword happy syntax of Java to the punctuation happy syntax of C++, it becomes clear that Java’s developers had decided doing it C++ style was worth more than adding any new keywords, like foreach and in. Guess they didn’t think to steal perls foreach statement for ideas on how to naturally side step it.
C# on the other hand, uses the kind of foreach statement that a Java programmer would have ‘expected’, one that actually blends in with the language rather than sticking out like a haemorrhoid. I might take a moment to note, that javac can be so damn slow compared to C++/C# compilers, that the lack of type inference in Java is probably a good thing!
In terms of syntax, Java is like C among it’s OO peers: it’s about as small and minimalist a syntax as you can get without being useless. I wish I could say the same about Java in general. Some interesting parts of C#, include properties and the out and ref keywords. 
Here’s a comparison of properties in Java and C#:
class Java {

private PropType prop;

public PropType getProp() {
return this.prop;
}

public void setProp(PropType prop) {
this.prop = prop;
}

public void sample() {
PropType old = getProp();
setProp(new PropType());
}
}

class CSharp {

public PropType prop { get; set; }

public void sample() {
PropType old = prop;
prop = new PropType();
}
}
C# has a very sexy way of doing getter/setter like methods for properties. Personally I prefer the more C++ like style of just having a public field, unless you need to hook it (with a getter) or use a private setter. I like how C# can make it look like a field, when it’s actually a getter/setter method like construct. That means you don’t have to remember which fields are accessed directly and which need member function calls when writing code. Java convention is getter/setter bloat; C# convention is to use properties for anything non-private. I hope C# 5.0 or 6.0 will replace { get; set; } with just add a property keyword alongside the access modifier.

C++ is just as lame as Java in doing getter/setter methods, except you can (ab)use the pre processor for creating such basic accessors as the above, as well as any similar methods you need but don’t want to copy/paste+edit around. Java and C# always make you write your own, unless they are the basic kind. Tricks involving Java annotations and subclassing can kiss my hairy ass. It’s also worth noting that some Java projects can use an insane amount of getter/setter code. Come on guys. Using an external tool is not the right solution.

When we compare the age of these languages: C++ => 27 years old; Java => 15 years old; C# => 9 years old. It becomes obvious that C# is the only one that doesn’t suck at the concept of “Properties” and getter/setters in general. Perl made love constructs that respect the programmers time more than the compiler writers: you should too.

To anyone who wants to dare note that Java IDEs can often auto-generate getter/setters for you, and dares to call that better than language level support, I can only say this: you’re a fucking moron. Go look up an Abraham Lincoln quote about silence. Now if someone wants to be constructive and create another Java example equal to the C# example in the above listing, I’ll be happy to add it: rules must be shorter than existing Java example, uses: no subclassing, no beans, no external programs or libraries. Be sure to note what Java version it requies. Cheers.

The ref and out keywords in C#, are actually kind of oddities, if you come from another main stream language. In C it is not uncommon to pass a variable (perhaps more correctly a block of memory, if you think about it) to a function: and have the function modify the variables value instead of returning it.

    /* Common if not enjoyable idiom in C */
    if (!do_something("some", "params", pData) {
        /* handle failure */
   }
   /* use pData */

In this case, pData is a pointer to some data type, likely a structure, to be filled out by the do_something function. The point is, it’s intended as a mutable parameter. In C/C++, it’s trivial to do this for any data type because of how pointers work. Java passes by value just like C and C++ do: you can modify non-primitive types because a reference is used, not the ‘actual’ value. Making it more like a reference than a value type, in CS speak. C# does the same thing.

    // Java pass by value
    public void test() {
        int x=10;
        Java r = new Java();

        r.setProp(PropType.OldValue);
        mutate(x, r);
        // x = 10; r.prop = PropType.NewValue
    }

    public void mutate(int x, Java r) {
        x = 20;
        r.setProp(PropType.NewValue;
    }

Now a little fun with the self documenting ref keyword in C#:

    public void test() {
        int x = 10;
        var r = new CSharp;

        r.prop = PropType.OldValue;
        mutate(ref x, r);
        // x = 20; r = PropType.NewValue
    }

    public void mutate(ref int x, CSharp r) {
        x = 20;
        r.prop = PropType.NewValue;
    }

The out/ref keywords are similar, the difference has to do with assignment; RTFM. The important thing is that it is a compiler error to pass the data without the ref/out keywords at the call site.  I’m both enough of a Python and C++ programmer to enjoy that. This explicitness helps catch a few typos, and helps document that it’s meant to be passed by reference, not value. That’s good because a lot of programmers suck at documentation and some also blow at naming parameters. I think the contractual post/pre conditions in Spec# are a good thing: by removing writing the handlers form the programmer, and not having to make the programmer rewrite the flibbin’ things in prose somewhere in the documentation. Not to mention the classic “Oops” just waiting to happen in less DbC oriented syntaxes. Hate to say it but the ref/out keywords presence in vanilla C# are likely due to Win32 API documentation conventions o/.

Where C# really rocks is in the CLI. Java has something good going for it, over the past 15 years the Java Virtual Machine (JVM) has been heavily tuned for performance, Mono and Hotspot also present quite an interesting set of options (that .NET lacks afaik). I assume that Microsoft’s implementation has also been battle tested for performance as well.

The thing of that is, the JVM was originally designed to run JAVA, first and foremost at the end of the day, that is what it had to do. The Common Language stuff on the other hand was intended to run several different languages. Although admittedly languages native to CLI tend to be similar, but so are most languages in general. The interoperability between CLI languages is wonderful, and at least in native .NET languages tends to be “Natural” enough. By contrast things crammed into JVM bytecode tend to become rather ugly IMHO, when it comes to interfacing with Java. I’m not sure if that’s due to the JVM or the language implementations I’ve seen, the changes coming in Java 7 make me guess it’s the former. The CLI is likely the next best thing to making a group of languages compile down to native code (for performance) and share some form of common ABI. Fat chance that will ever happen again. I’m sure I want to ponder about VMS, but the whole CLI thing tends to work quite nice in practice The performance cost is worth it for the reduction in headaches.

I’m sure that in terms of performance that Java mops the floor with Mono in some areas, because of how much hacking has gone into it making it a cash cow. That the C# compilers seems to run ring around the defacto standard Java compiler, is what really catches my interest performance wise. Using the mono 2.4.4 and Java 1.6.0_18 compilers, on my very modest system mcs processes a minimal program about 30% faster than javac. In real opeartion it tends to kick ass. When you consider that each compiler is also implemented in the target language, Java really gets blown away. O.K. maybe I care more about compile times than many people, it’s the virtue of using an older machine :-P. Combine that with how many slow, buggy, monstrosities have been written in Java—I’ll salute C# first.  Another plus is less “Our tools demand you do it THIS WAY” than what Sun threw at everyone. Piss on javac and company.

What has hurt C# in my opinion is the Microsoft connection. The thing with Novell doesn’t help either. That Java is not exactly an insanely popular language among hackers, so much as enterprises, is another. The things that have hurt Java, being so closed and being academics choice for stupifying students.

What’s the upside to using Java over C#? Easier access to Java libraries, (J2ME) mobile phones, and more finger exercise from all that needless typing! Beyond that it’s essentially a win, win in favour of C#.