Posts Tagged ‘programming’

Elegant Code vs Skanky Code

// February 23rd, 2007 // 9 Comments » // .net, c++, software development

I have been looking for a description of elegant code, and summing up everything I have learned and seen, I compiled a list of examples of what elegant code blocks look like. Now, the actual definition of “Elegant Code” is up to the reader, since there are so many different definitions. Each developer has its own very personal definition. I have even seen comparing the feeling of elegant code to beautiful code, and both are completely subjective. My own personal definition is: “Elegant code is a block of code that does a lot with little effort.” Performance is an issue for me, but it is not required for a piece of code to be elegant.

Disclaimer: These examples are not the only ones, but I think they build up a good idea of what elegant code actually is.

* First example:

Skanky Code

if(0 == x) {
   y = 0;
} else {
   y = 1;
}

Elegant Code

y = (0 < x);

It is more elegant, because it is easier to read (it is only one line) it is faster and way cleaner.

* Let’s see another example:

Skanky Code:

x = y * 256;

Elegant Code:

x = y < < 8;

This piece of code is not about lines length, is about performance. The second one, done using bitwise operations is faster, hence more elegant.

UPDATE: It is no secret that doing bitwise operation to multiply by powers of two is faster. Nowadays, modern compilers already do this optimization before hand. So now when you write: x = y * 16 the compiler transforms that as x = y < < 4. Now, compilers have gotten so clever, that when you do y * 17 the compiler generates it as (y < < 4) + y. Even if the compilers now does this optimization, doesn't take away the merit for this code for being elegant, even if the performance with modern compilers is the same.

* Another example:

Skanky Code

if(null == x) {
  y = 0;
} else {
  y = x;
}

Elegant Code

y = (x ?? 0);

* Last example :

Skanky Code

if(&quot;sss&quot; == x) {
    y = &quot;aaa&quot;;
} else {
    y = &quot;bbb&quot;;
}

Elegant Code

y = ( &quot;sss&quot; == x ? &quot;aaa&quot; : &quot;bbb&quot;);

If you know any more examples and want to share them, please do so…

Advanced Linux Programming

// February 20th, 2007 // 2 Comments » // linux, software development

I was searching through the web, and I found out about this great free book about Advanced programming for Linux. I haven’t actually read it, but as I went through it, seems fairily complete.