#329
One of the penalties of refusing to participate in politics is that you end up being governed by your inferiors.
Plato

The Ugly Examples

I wrote in the last article that this week I would be giving some code samples to further explain my position on why I consider code to be ugly. That will probably be the last time I mention a follow up on a post inside the post. Anyway, here it is.
Kia Kroas :=: 13 Apr, 2010 09:29:44


Open source projects give a lot of nice examples of good code. But good code isn't always beautiful. The Linux kernel is one prime example. It's very good code. It has to be. And after so many years and so many hours of work put in by so many people and so many experts, it better be some awesome goodness. And it is. But I still think the code is ugly (and also a little scary, go read a the comments in the source, you'll be scared too).

* I took out syntax highlighting and whatnot on purpose.

C

As a whole, it isn't that bad. But consider two examples from a random source file, cpu.c. They start around lines 57 and 511 respectively. This is relatively elegant C code. And relatively easy to understand for someone who has already sorted out all the definitions.

void put_online_cpus(void)
{
	if (cpu_hotplug.active_writer == current)
		return;
	mutex_lock(&cpu_hotplug.lock);
	if (!--cpu_hotplug.refcount && unlikely(cpu_hotplug.active_writer))
		wake_up_process(cpu_hotplug.active_writer);
	mutex_unlock(&cpu_hotplug.lock);

}
EXPORT_SYMBOL_GPL(put_online_cpus);


static DECLARE_BITMAP(cpu_online_bits, CONFIG_NR_CPUS) __read_mostly;
const struct cpumask *const cpu_online_mask = to_cpumask(cpu_online_bits);
EXPORT_SYMBOL(cpu_online_mask);


Assembly

Here's a hello world in Assembly for i386 on the Linux Kernel. That's right, the kernel and source matters because of the system calls. Stolen from Introduction to UNIX assembly programming - Chapter 2 It's a good beginner book, check out the full book if you're interested.

section	.text
    global _start			;must be declared for linker (ld)

_start:					;tell linker entry point

	mov	edx,len	;message length
	mov	ecx,msg	;message to write
	mov	ebx,1	;file descriptor (stdout)
	mov	eax,4	;system call number (sys_write)
	int	0x80	;call kernel

	mov	eax,1	;system call number (sys_exit)
	int	0x80	;call kernel

section	.data

msg	db	'Hello, world!',0xa	;our dear string
len	equ	$ - msg			;length of our dear string


SQL

SQL is fairly nice most of the time. Very elegant for simple queries like most in the declarative programming language family, but not very elegant when you need something complex, or multiple shards or heavy scalability. Two examples that make absolutely no sense without the table schema are below, and if you want an ugly example, check the MySQL documentation's 3.7.1. Find All Nondistributed Twins. It was written for MySQL 3.1.9, but it still applies since the SQL standard hasn't changed that much over the years.

SELECT * FROM table_name.databasename;
SELECT * FROM table_name.databasename AS t1 LEFT JOIN table_name2.databasename AS t2 WHERE col1 = 'abc' ORDER BY t1.id DESC;


Java

Netbeans is a Java IDE written in Java. It's close to C and C++. There's not much to say here. Java isn't especially known for elegance and beauty. http://hg.netbeans.org/main/file/9543e65624df/editor/lib/src/org/netbeans/modules/editor/lib/EditorRenderingHints.java lines 65 to 76.

public static final String TEXT_ANTIALIASING_PROP = "textAntialiasing"; // NOI18N
public static final String PROP_HINTS = "EditorRenderingHints.PROP_HINTS"; //NOI18N

public static synchronized EditorRenderingHints get(MimePath mimePath) {
    EditorRenderingHints erh = CACHE.get(mimePath);
    if (erh == null) {
        Preferences prefs = MimeLookup.getLookup(mimePath).lookup(Preferences.class);
        erh = new EditorRenderingHints(prefs);
        CACHE.put(mimePath, erh);
    }
    return erh;
}


PHP

'PEAR is a framework and distribution system for reusable PHP components.' Kind of like a packaging system, a PHP wannabe-CPAN. The example takes code from go-pear.php which serves to update PEAR. http://pear.php.net/go-pear lines 437 to 443. It gets worse.

foreach ($config_vars as $n => $var) {
    for ($m = 1; $m <= count($config_vars); $m++) {
        $var2 = $config_vars[$m];
        $$var = str_replace('$'.$var2, $$var2, $$var);
    }
    $$var = parse_dirname($$var);
}


CPAN

CPAN is the Comprehensive Perl Archive Network. It is both the repository of Perl modules and the interface to access it. CPAN is itself a module available on CPAN. It is the de-facto, one-stop shop for Perl libraries and modules. If it's not on CPAN, it's not worth getting.

The code below is from CPAN.pm lines 505 to 516. It's relatively nice since I don't believe this particular file has the complex regular expressions for which Perl is known.

sub _flock {
    my($fh,$mode) = @_;
    if ( $Config::Config{d_flock} || $Config::Config{d_fcntl_can_lock} ) {
        return flock $fh, $mode;
    } elsif (!$Have_warned->{"d_flock"}++) {
        $CPAN::Frontend->mywarn("Your OS does not seem to support locking; continuing and ignoring all locking issues\n");
        $CPAN::Frontend->mysleep(5);
        return 1;
    } else {
        return 1;
    }
}


Ruby

I think everyone who has ever heard of Ruby has heard of Ruby on Rails. Rails is a 'full stack, Web application framework optimized for sustainable programming productivity' (rubyonrails.org). It has done a lot to popularize Ruby as a language and gained a lot of hype this past year. (It is also the platform of choice for my workplace.) Here's a piece of ActionController that's adding to Railtie.

    initializer "action_controller.set_configs" do |app|
      paths = app.config.paths
      ac = app.config.action_controller

      ac.assets_dir = paths.public.to_a.first
      ac.javascripts_dir = paths.public.javascripts.to_a.first
      ac.stylesheets_dir = paths.public.stylesheets.to_a.first

      ActiveSupport.on_load(:action_controller) do
        self.config.merge!(ac)
      end
    end


Python

Python is known for removing the verbose parenthesis and curly braces in exchange for indentation requirements. It makes it look less code-like, but more blocky. Django is probably the most well-known Python Web Framework. It does for Python what Rails did for Ruby. Here is an example source from its dispatcher lines 229 to 241.

    def _remove_receiver(self, receiver):
        """
        Remove dead receivers from connections.
        """

        to_remove = []
        for key, connected_receiver in self.receivers:
            if connected_receiver == receiver:
                to_remove.append(key)
        for key in to_remove:
            for idx, (r_key, _) in enumerate(self.receivers):
                if r_key == key:
                    del self.receivers[idx]




I am not well-versed in functional programming so I can't quite give my take on it. If you want to check them out search around for LISP, Scheme, Haskell and Erlang. There's some mathematical elegance in this family of programming languages.

What do you think now?
Copyright Kia Kroas 2009