Monthly Archives: March 2006

Backward incompatibility

After reading Jeff Smith’s Programming is a funny thing article I felt the need to comment.

As a strong advocate about simplicity I was according to the fact that “experts” writes clearer code then beginners. But I think Jeff missed the point when he said that in the software industry, beginners gets all the hard and big projects. They make it hard by their selves. For years software developers have been solving similar problems over and over. That’s why we end up with design patterns, frameworks, libraries, etc. But to be selective with all those tools, you have to know them. Software “experts” know them because they’ve been around for a while, so they know that for this kind of problem you do this kind of thing, and whoop! You’ve just divided your project in half the complexity and time and LOC and … Fred Brooks mentioned in his famous No Silver Bullet article (published in 1987) that all low-level problems had already been solved.

Sure knowledge is not everything. You could still have someone with 20 years of experience under his belt, knowing all about everything, but unable to select the correct solution for a given problem. You need to be good at synthesizing all that knowledge too.

I think I can sum this up like this: you’re not an expert when you can solve a problem, but when you can choose the best solution to that problem.

(I would have loved to put a nice analogy with some other industry, but yeah! I only work in the software one)

3 Comments

Filed under Misc

A C# interpreter in 50 lines of code

With all the hype around scripting languages these days, here’s my contribution. A C# line interpreter. The principe is simple: append the code to a string and evaluate it when a return statement is added. This is some magic we can do with the System.CodeDom and System.Reflection namespace. Not quite has dynamic has ruby or python, but better then nothing…

Run it. Type some c# code, each line will be compiled instantly, type a return something; to restart the session.

Here’s an example:

Instant C#, hack some code...
>>> string cool = "wow that's cool!";
>>> cool = cool.ToUpper();
>>> return cool;
WOW THAT'S COOL!
>>>

using System;
using System.Reflection;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
 
public class InstantCSharp
{
    private StringBuilder _code = new StringBuilder();
    ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
    CompilerParameters parameters = new CompilerParameters();
 
    public static void Main()
    {
        new InstantCSharp().Start();
    }
 
    public InstantCSharp()
    {
        parameters.GenerateInMemory = true;
        parameters.ReferencedAssemblies.Add("System.dll");
    }
 
    public void Start()
    {
        Console.WriteLine("Instant C#, hack some code...");
 
        string cmd = ReadCmd();
 
        while (cmd != null)
        {
            object obj = Run(cmd);
            if (obj != null) Console.WriteLine(obj);
            cmd = ReadCmd();
        }
    }
 
    private static string ReadCmd()
    {
        Console.Write(">>> ");
        return Console.ReadLine();
    }
 
    private object Run(string cmd)
    {
        string code;
        string returnline = null;
        bool haserrors = false;
 
        if (!cmd.StartsWith("return"))
        {
            returnline = "return null;";
        }
 
        code = @"
            using System;
            public class Runner
            {
                public object Run()
                {
                    " + _code.ToString() + cmd + returnline + @"
                }
            }";
 
        CompilerResults compiled =
            compiler.CompileAssemblyFromSource(parameters, code);
 
        foreach (CompilerError e in compiled.Errors)
        {
            Console.WriteLine(e.ErrorText);
            if (!e.IsWarning) haserrors = true;
        }    
        if (haserrors) return null;
 
        object obj = compiled.CompiledAssembly.CreateInstance("Runner");
        object returned = compiled.CompiledAssembly.GetType("Runner")
            .InvokeMember(
                "Run",
                BindingFlags.InvokeMethod,
                null, obj, new object[] {}
            );    
 
        _code.Append(cmd); // All ok so include the line
        if (returnline == null) // A return call means end of the session
            _code = new StringBuilder();
 
        return returned;
    }
 
}

2 Comments

Filed under Misc

Rock Star programming : my two cents

I was a little outraged when I red Mikael Grev’s My Top Ten Tips on how to become a Rock Star Programmer a couple of weeks ago when it ended up on reddit. And now that ironmonkey has done his own meaculpa I feel the need to add my little two cents.

Ironmonkey probably has the greatest tip of all, that not only apply to programming : to be the best, learn from the best.
One of the two original tips I was most shocked about was Don’t learn APIs too well. Keeping in mind that his tips were for becoming a rockstart programmer. Someone that, when you look at his code, all you can say is: WOW! How did he thought about it!
Cool code has to be compact, yes… but mostly brilliant and simple. Absurdly simple. People have to be ashamed that they haven’t thought about it before when they see it. That’s rockstar programming. Now how can you end up writing this type of code? You have to know the programming language and api and all libs you’re using by heart, its weakness and strengths. Let’s sum this up with an example in ruby (a rockstart ready language):

Let’s say you’ve just learned ruby, but have been using java for some year and consider yourself a good programmer. The simple problem for my demonstration is this: the second command line argument of a script is the language, if not specified, it has to be English (en). So I’m going to write it first has a new ruby programmer and refactoring it to a more rockstar fashion.

Ok I know ruby syntax, and I know how to do this, simple

if $*.size > 2
  lang = $*[2]
else
  lang = 'en'
end

That works… I don’t know the api, but I’ve looked at the docs ’cause I didn’t knew how to retrieve command line arguments ($*).

Now I read some more about ruby, check some code written by cool ppl, put sunglasses on and refactor to the following:

lang = 'en'
lang = $*[2] if $*.size > 2

Ha ah!!! from 5 lines to 2!!! How cool is that???

I read some more code, tear my shirt off, pierce my nose and refactor to the following:

lang = $*[2] || 'en'

What? Isn’t this throwing a IndexOutOfRangeException and those are not boolean expressions!?! (remember, I’m a java programmer) People who don’t know by heart a language or api would assume a great number of things, some are false, some aren’t. My point is that there’s no way I could have guessed that my last line would have worked in ruby if I didn’t knew the language by looking at other people’s code, books and tried it myself. You have to know API and syntax really well.

Other’s tips are also wrong IMHO, but I can’t make a point this clear about them, for now…

5 Comments

Filed under Misc, ruby

Code generator : the languages comparison

I’ve been hacking a code generator in various languages just to get the fell of each languages, none is the worst, but some are so much cooler. Here’s the results of my experimentation.

C#

Goods

  • Fast
  • Should run on any win32 machine with .NET

Bads

  • Too much of LOC
  • Had to use NVelocity has a template engine
  • Code to inject template bindings was ugly

Python

Goods

  • Easy to read class and attributes metadata
  • Scripting language so the developement cycle was faster, no compile step
  • Easely multiplateforme

Bads

  • Had to use Cheetah has the template engine

Boo

Goods

  • Fast
  • Implemented the generator code has a script in Boo

Bads

  • Playing with the compiler pipeline and stuff is complexe
  • lack of docs (but yeah Boo has not hit 1.0 yet)
  • No template engine usable for this with Boo’s syntax

Ruby

Goods

  • OMG!
  • Implemented in 2 LOC

    require 'erb'
    print ERB::new('mytemplate').run(binding)
    

Bads

  • Too easy 😉

Leave a comment

Filed under C#, Generator, python, ruby

AJAX and the whole 2.0 stuff

Some are all buzzed about it, some others are angry that someone has even thought about naming a fashion Web 2.0. Like their was a version for the “Web”. It’s like naming your own child “Version 1.2” (I know some guy did… That’s not my point). I’m not angry at this, I think it’s a marketing stuff, “hey come with us we got the next version of the internet wright now!”, hum… Pretty tempting. But all that matters to us programmers (and users) is if it will make our live easier.
Today I get to try Yahoo Mail boosted on Ajax. You can drag and drop stuff all around, and you even get a popup menu to tickle you mail. But man! It’s slow! I thought that AJAX was all about asynchronous processing to make web pages more fast. Now I have to wait 5 full seconds to even check if I got mail. I switched back to my old and comforting yahoo mail without all the glamour stuff, but the efficiency.

At the same time I’m building a web app and using AJAX to boost up my … ego. But on the functional side, It’s great, having to interact remotely with the server without posting or without not-so-cool spaghetti javascript packed with collections loaded at post time… hurrrrr… You know when you got a child collection to be modified on a web page without reloading, that’s the kind of stuff that makes your life easier and your code cleaner.

All my work has been done with Castle, MonoRail and ActiveRecord are like Ruby on Rails, but it’s the MicroKernel Container of Ioc that makes it super powerful. You can hack services (full of dependencies if you wish or have to), test them with mocks and them plug it in the container. Then you only add the interface to your service in the Controller’s constructor like this:

public ServiceController(IMyCoolService service)
{
  _service = service;
}


No factory, no crazy xml config file, cool!

1 Comment

Filed under Castle, web 2.0