The Best Code is No Code at All

As always, Jeff Atwood has an interesting around code being our enemy as developers. His proposal is that code needs to have better ‘brevity’.

I don’t think Jeff is talking about Brevity – and I think he even says that – but about Clarity. Clarity is simple, obvious, and to the heart of the matter. Real clarity is brief, but easy to read. That includes comments, too.

It could be made shorter in ‘text speak’, but how clear are those messages? There is a reason we don’t use 1 letter variable names!

It’s not tiny fragments of obscure code that does massive amounts (yes, I’m thinking of Perl in that, amongst others). And it sure as hell isn’t about lines of code – many languages (with notable exceptions) let you put an entire program on one line. Ever tried reading one? I did – you can’t.

It’s just about being simple, clear, and to the point. It’s kind of like Buddhist enlightnment – someday, with enough practice, I’d might just achieve that.

Unfortunately, I do think that we’re constrained – people often expect very complex things and lots of features from their software, and when people are demanding complex programs, you get complex code. Look at the complexity cost of, say, just having a simple UI for a Windows app, as opposed to a console app.

Some of the comments are very good, too. ‘Mickey’ is right – often, we’re trapped by bloated design. KISS is my watchword (and occasionally gets me a slap too).

Fred Ross is right, too, in his comment about code maintenance – but he does miss the point that often we’re under pressure from the boss to ‘just get it done’, and the idea of ‘get it done, but in a way that will save us time later’, well, usually, that dog won’t hunt.

Someday, we’ll get past the idea of using lines of code as a metric for how ‘good’ code is. I guess the problem is that clarity is more ethereal.

Comments from my old blog:

I agree with most of your points – but diverge in perhaps the same places you might too.

Examples… a typical .NET web application – which has C#, HTML, DHTML, Javascript, horrific call backs for AJAX, SQL, Stored procedures, triggers… the list goes on. There doesn’t seem to be any sensible way of making it “simple”.

The other problem (at least in my recent experience) is RAD or AGILE development… which often leads to spaghetti code unless the client is willing to pay a huge code tax for re-writing swathes of the project.

By Jonathan at 09:20:28 Tuesday 5th June 2007

The Best Code is No Code at All

Nice list of fonts

Nice fonts here. Now if there were some way to push them onto the client…

…actually, why the hell isn’t there? A truetype font is, what, 100-200k? Why aren’t these downloaded to some form of isolated storage, and used for display purposes in the browser. You can even, oh, I don’t know, have a font cache, so you don’t have to download them repeatedly. Perhaps some sort of signing mechanism to avoid version problems.

Comments from my old blog:

Yes – very good list. Myriad is a great font – it manages to strike a balance between being pretty, and practical too. Fonts are one of those areas where I benefit from having a designer for a brother, so was exposed to lots of barracking when I was younger and playing with DTP software… “make the line height 120%”, “make the body text smaller”, “no more than 2 fonts on a page!” and other rules of thumb…

By Jonathan at 18:06:08 Tuesday 5th June 2007

Nice list of fonts

Graphics and Developers

Coding Horror has blogged about developers needing to know graphics programs, and I agree entirely. Jeff’s right, we’re not designers, and never will be (I don’t even wear glasses, let alone ‘cool’ ones). Don’t try and learn how to build beautiful websites if you’re a developer – either, you’re gifted and you already can, or there is simply too much learning involved.

But we can build ‘fair’ sites, and rough mock ups. Every site doesn’t have to be a work of art, just as every ceiling doesn’t have to be the Sistine chapel. As developers, we should make an effort to not build websites that look crap.

And if you need to build the Sistine chapel, remember it’s a team effort. You can build the structure – and get a specialist to make the ceiling pretty.

Link to some tutorials Jeff provided (note to self – take a look)

Graphics and Developers

Excelllent – A CAML query generating library

To those of you who’ve never written a CAML query, this won’t seem exciting. For those of you have have spent hours digging through reams of XML searching for a fault in your query, this will be heaven sent:

CAML.NET assembly – write your queries in C# – and you can find it on Codeplex.

Queries are now as simple as:
string s = CAML.Query(
CAML.Where(
CAML.Eg(
CAML.FieldRef("SomeField"),
CAML.Value(someValue)
)
)
)

This is such a blatantly good idea that I’m giving it a

Comments from my old blog:

 

Now that *is* a good idea…

By Jonathan at 17:11:14 Sunday 13th May 2007

Excelllent – A CAML query generating library

Busy, Busy, but some thoughts on demos

Though I did have a demo at a potential customer recently, this isn’t about them. These are just the things that I’ve seen repeatedly. I’m not sure what the answers to some of them are yet.

  1. The (potential) customer always wants to see 90% of the functionality in the demo – no matter how custom that development is. (This is a case of managing expectations)
  2. The complexity of the demo is inversely proportionate to the time available to build it. (Beat the salesman until he understands, then cut all the complex bits and proceed as above)
  3. The customer will want to see all logins for all the different users in a process used – and will then yawn as you switch between accounts (and yes, I know about ‘Run As…’. Even so, they’ll yawn). (Don’t show it. Or do it once, and then explain that you’re going to stop switching for the sake of sanity/getting to lunch on time)
  4. The bit that you spend ages on getting working because it “must be shown” won’t be shown. (Try to find out how important these hard parts really are)
  5. The bit that you spend 5 minutes on, doesn’t do anything, but looks pretty will get them really excited. (This is good! Make sure you show them the exciting stuff)
  6. The customer will be utterly confident that they know their business process – and then through the course of the demo show that they don’t. (Try to help them see this, and consider re-engineering/redfining the process. If they won’t, steer clear or work on a T&M basis…)
Busy, Busy, but some thoughts on demos

What did I learn today (and yesterday) about testing

I’ve been testing some code I’ve written for sending out notification emails according to a moderately complex set of rules. So, what have I learnt?

  • Developers make rubbish testers. We know our own code too well, and already have expectations of how things should work.
  • Testing has too many variables for any reasonable size application. You can’t test exhaustively. Equally, testing only what you think needs testing will also miss things. I’m beginning to think some automated, semi random testing (if you can) is the way forward – and you’ll still miss things.
  • Specialist testers are good. I’m convinced a specialist would see what I’ve missed, and have good ideas over how to test generally. I don’t think I’m alone in that..
  • Automated test is not a panacea… I really don’t see how it could apply in this case, at least not without a unit test program that could create database records, read a SharePoint library, and read an exchange server. All reasonable – but how do I then test the test app? ‘Cos it’s a complicated as my actual application.
  • … and Unit testing isn’t a panacea either… I know, they’re related, but this does at least imply that you’re testing, well, small units of code. That relies on problems not occuring because of mismatches in the interoperation between units.
  • … and with them both, you have to remember that you’re designing the tests. If you didn’t think of the case to handle it in your code, do you think you’ll think of it to test for it?

All that said, my application seems to work pretty well. Just there was a lot of manual cross referencing of results to check things worked, so I had a lot of time to think.

I’d really like a project where I can get thoroughly stuck into unit testing. Didn’t use it in this one, but I did think about how I would’ve done it – and I suspect I’d have missed one of the bugs I found. I suspect that unit testing’s main advantages are in forcing developers to actually think up front (sometimes rare), and in ensuring a consistent public interface despite internal changes. But I don’t see how you can get away from the fact that someone has to site and decide what to test – and that way things can be missed..

What did I learn today (and yesterday) about testing

Benchmark: Speed of Encryption and Decryption using .NET Framework classes

I was reading about security stuff in the .NET framework, and dealing with cryptographic classes in it, and it sort of set me wondering. Here are all these different encryption classes, with different block and keys sizes, cipher modes, all that jazz – but what are their performances like? Specifically, I’d read something saying how some ‘weaker’ encryption algorithms are better (in some speed-critical applications) ‘cos they’re faster. I wondered how much?

Thus, I decided to benchmark the Symmetric alogrithms in the .NET Framework – DES, Triple DES, RC2 and Rijndael. To make life interesting, I thought I’d try them with differenct key sizes and block sizes, and cipher modes.

So, I’ve linked to definitions of these factors, but for those who don’t want to read vast chunks of Wikipedia, here are my (simplified) definitions. For anyone really interested in learning how to program with encryption properly (and in learning why their 128 bit key probably isn’t 128 bits strong) I can strongly recommend the book ‘Practical Cryptography’ by Bruce Schneier and Niels Ferguson.

Symmetric ciphers are ones like you used when you were a kid. You have some operation that turns a message into garbage, and then the reverse of that operation turns that garbage into a message. Some algorithms don’t have a reverse – they are asymmetric ciphers, and are a whole different kettle of fish.

Keys are the password you use with your cipher. For example, if you’re cipher as a kid was to shift all letters in the alphabet, then the key might be the numbers of characters shifted. Big keys are harder to break. Think of it as being just like a password or PIN number. If I tell you that my PIN is 4 digits, you might be tempted to guess all 10,000 possibilities, and on average you’d figure my PIN out after 5000 tries. If my PIN was 8 digits, then there is 100,000,000 options – and you’re less likely to try all the possibilities, eh?

Block sizes. Well, okay, some ciphers work on blocks of data, rather than each byte (or each ‘letter’). These are block ciphers. There are also stream ciphers, where each byte is encrypted one by one. Anyway, in block ciphers there is a limit to how much data can be encrypted without ‘leaking’ information. Larger block sizes can encrypt more data without that leakage. (That’s not to say that the block has been decrypted, but an attacker could start to learn things about the contents of that block.)

Cipher modes don’t really have a parallel with how you did codes as a kid. I guess I would describe it that if the cipher is about how you make an apparently random set of bits, then the cipher mode is about how you then use them. There are lots of different modes, but the .NET framework classes only seem to support 3 – ECB (Electronic Cookbook), CBC (Cipher block chaining) and CFB (Cipher Feedback).

So, what are the algorithms:

  • DES – An old encryption standard, now regarded as offering poor security, but so widely used that it is still in operation as a legacy system.
  • Triple DES – An improved version of DES, made by essentially applying the DES 3 times.
  • RC2 – A moderately old encryption algorithm. Flexible key lengths, but short block size.
  • Rijndael (aka AES) – The latest encryption standard. The Rijndael algorithm was selected from several as part of a competition. It wasn’t regarded as the most secure, but it was quite quick. The Advanced Encryption Standard (AES) is actually a subset of Rijndael.

The Test

I found a nice text file – “The complete works of Shakespeare” – as my test data.

For each algorithm, for each mode, key and block size, the test program encrypted and decrypted the data twenty times, and reported the average ‘time’ for each operation. I was using the Win32 QueryPerformanceCounter function, which doesn’t really return a time so much as cycles. However, all the tests were done on the same machine, so they’ll do just fine for comparison purposes.

Results

With the several factors tested, there are many ways of slicing the data. It’s worth noting that these results are pretty rough, as the times taken also include file IO operations, and with any modern PC there’s also something else happening at any single time. Also, the times are the total time taken to encrypt and decrypt, which might not be the same for each operation. Treat the results as a loose guide.

First let’s look at the raw results. You can get the results here (Excel file) –EncryptionTimes.

Unsurprisingly, DES is fastest – given it’s age, and the low level of security it offers now. Triple DES with the longest key it supports was generally slowest. RC2 covered the full range of results, which is also unsurprising, given it’s flexibility, and Rijndael sort of falls in the middle.

The first thing I noticed was how few tests there were using DES or Triple DES. RC2 and Rijndael are much more flexible in their use.

Next, it’s interesting to note that RC2, DES and Triple DES using Cipher Feedback Mode (CFB) were all very, very slow. They all seem to suffer very badly using CFB.

So, excluding the CFB results then (as they are so exceptionally slow), what do the other results show? Well, Rijndael does not suffer so badly in CFB, although CFB is slower.

ECB appears slightly slightly faster in the table, though examining the CBC Mode Graph shows little difference.

To compare the modes, I looked at just the operations done with the Rijndael cipher.

Again, we see little difference between ECB and CBC, so I guess there’s no reason not to use the more secure CBC mode over ECB (for an example of it’s weakness see here). Also, for 128 bit blocks (as required by the AES standard), CFB is as quick as ECB.

Rijndael is not great in CFB mode with blocks of longer than 128 bits.

Okay, so let’s focus on just one mode (CBC) and look at the results shown in the CBC Mode Graph. Well, it’s interesting to note that RC2 with a 112 bit key was quite quick – faster than with some shorter keys. However, it’s only about 6.5% longer to use 128 bit Rijndael – which is a key that is 14% longer. Doubling the key with Rijndael to 256 was only 10% longer than 128.

Longer blocks take longer to encrypt and decrypt. 64 bit blocks seems a little short these days, only being safe for up to a couple of hundred megabytes. 128 bits seems more reasonable. 256 bits seems excessive. Rijndael seems to have little penalty for using 256 bits over 128, though if you do, you’re not using an AES standard encryption.

Conclusion

DES and Triple DES are old. DES isn’t secure, and Triple DES doesn’t seem to offer much given Rijndael and RC2 being much faster than it.

In terms of cipher modes, these classes only seem to support ECB, CFB anc CBC. ECB is generally regarded as being a poor mode – it’s not very secure. CFB was typically slower than CBC, and as Microsoft have already implemented the classes, some of the advantages CFB (i.e. encryption and decryption being identical operations) have been lost.

So, then examining Rijndael in CBC mode, well, there is little penalty for using 256 bit keys or 256 bit blocks. However, it’s probably worth sticking to 128 bit blocks as 1) it is plenty, and 2) it is AES compatible.

All in all, I was surprised by how similar a lot of the results were for different algorithms, and I was surprised by how slow some of the CFB mode operations were.

To be honest, I can’t really think of a reason not to use Rijndael with 128 bit blocks, in CBC mode. Unless time is a really critical factor, 256 bit keys are stronger. Finally, the RijndaelManaged class in the framework is a managed class, rather than a wrapper for a COM object.

So, the winner is Rijndael!

Comments from my old blog:

This is a very informative article. I have just started looking into encryption, and I have come across nothing on the internet that is as concise as your article.
Will you be doing something similar with asymmetric encryption as well?

By Firoz at 06:22:04 Friday 9th February 2007

Yup, well, at some point. The truth is, in the .NET 2.0 framework, there isn’t a lot of other asymmetric algorithms. RSA is about it. I think in the .NET 3.0 framework there is elliptical curve, and that would be interesting…

So, yes, when I get around to it.

By Andy B at 10:09:43 Friday 13th April 2007

Benchmark: Speed of Encryption and Decryption using .NET Framework classes

AES and Rijndael – AES is a subset…

Useful article from the .NET Security blog about AES and Rijndael. Essentially, Rijndael is more flexible than it’s use as defined in the AES standard. Can’t say I’ve ever come across a situation where I’d want to less than 256 bit, but then I’ve never had to do time critical encryption. Might benchmark it, that might be an interesting task.

The short of it is:

Essentially, if you want to use RijndaelManaged as AES you need to make sure that:

  1. The block size is set to 128 bits
  2. You are not using CFB mode, or if you are the feedback size is also 128 bits
  3. The key size is 128, 192 or 256 bits (Added by Andy)
AES and Rijndael – AES is a subset…

RSACryptoServiceProvider – "Key not valid for use in specified state"

So, I was trying to do some encrypted comms over TCP, only rather than using SSL, I thought I’d try to RSA encrypt and decrypt at client and server myself. I know, it’s re-inventing the wheel – the point is to get to know the APIs though, and it seemed a good exercise.

I started getting an error though – “Key not valid for use in specified state”. Odd. I was importing the key from an XML file, using the FromXMLString() function. It all seemed to work just fine. So, WTF? It’s not like the code is complicated:

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publickey);
byte[] encryptedData = rsa.Encrypt(data, false);

So what gives?

Well, eventually, I tracked it back to this – I was trying to send too much data. Not very much – less than a couple of hundred bytes – but this was too much.

The obvious thing to do was change the way this works to match the way it’s supposed to work – use RSA encryption to transfer the key to a block cipher, and then encrypt all your data with that block cipher. But I couldn’t be arsed – I just wanted to see the asymetric encryption work – so I reduced my data…

Comments from my old blog:

Sounds like you where in the 70-536 Self Study book from Microsoft. In chapter 12 doing some suggested practices.

Anyway.. that’s where I am and your message here on the blog helped.

I too will send a smaller file 😉

By Micke at 17:13:02 Monday 24th September 2007

Yup, I think I was. It was a bit daft that they didn’t mention the limits on the size of the data.

But that book has a _lot_ of issues.

By Andy at 10:18:03 Thursday 27th September 2007

RSACryptoServiceProvider – "Key not valid for use in specified state"

Creating Test Certificates with MakeCert

I was having a bugger of a time setting up an SSL connection using a test certificate until I found this article by John Howard. One thing I would say – when using MMC to look for newly created certificates, remember to ‘refresh’ the view. Otherwise this works – shame I don’t entirely understand how… … still, at least my error “The server mode ssl must use a certificate with the associated private key” is now gone…

Creating Test Certificates with MakeCert