Archive for February 2009

Life without ‘if’s

A terrible week behind! After being privileged to work with WPF, I had to concentrate on fixing nasty bugs and adding requested new features to a “nearly finished” project we have been coding with six other developers. I felt *so* guilty because all I could do last week was to add more code lines and if statements to these sources my colleagues already have decorated with myriads of ifs. Sometimes it saves my day if I manage to reduce a prolix code passage into one line of just-to-the-point code. Last week there was no such day.

Every if statement we write makes our future life more miserable. The more ifs your code contains, the harder it is to grasp and maintain. If a logical inference doesn’t fit on one screenful of code, it is likely that a colleague that is going to maintain your code will not get your idea and only makes it worse with new ifs.

Ever had this feeling that the world would be a better place without if statements? When you write an if, your code “depends”, it’s contingent. Sometimes you can never be sure which branch of your code will actually execute. On the other hand, a code passage with no ifs can be thought of as necessary – it is always executed just the way you wrote it. The worst if is the one you write “just in case” when you have no idea what the actual situation will be when your code executes.

There are religions and even actual people that believe everything in the world was predestined – God needs no ifs. Being a mere mortal I must admit that I don’t know everything in advance and hence need to adapt to alternate situations with ifs. But there are things we know, and based on these things we must try to comprehend the world around us and express it as clearly and plainly as possible in our code. If you want to obscure the idea behind your code, write as many if statements as possible!

Let’s take an example! This is actual code I found on a project a few years ago. Based on a given sum value, it calculates the check digit of a Finnish bank reference number:

CheckDigit_a

Unaware of the existence of this code, I wrote my version like this:

CheckDigit_b

Look Ma, no ifs! To be honest, one if statement doesn’t make the whole difference here, and the first code line already shows that the author of CheckDigit_a has not comprehended the real idea behind this calculation. At the end of the code, it is not Destiny that decides whether the value of sum is 10 or not. It is something that can be calculated, and whatever the value is, it is necessarily what it is, not contingently. Once we are given a value for sum, the return value is implied and fixed – there is no room for hesitation, no ifs left!

Now we come to the point: Using an if statement is OK and even necessary when the condition is genuinely contingent, i.e. it comes from sources like user input, a value in a database column etc. When not, you should first consider saving one if and think whether the situation could be handled otherwise.

Since we cannot totally live without if statements, I would like to suggest that in order to keep the total number of ifs as low as possible, programmers should pay a fine for every if they write. If you want to have something left for the payday, consider the following:

  • Use arithmetics, character functions etc. where possible!
  • Try to reduce the amount of nested ifs by making an analysis of your conditions. Using a pencil, a piece of paper, and truth tables is a good method when the situation seems too complex to grasp. This way you will probably be able to combine several if statements into one and perhaps even find a branch that will never execute.
  • Use the ?: conditional operator for atomary conditional situations. Logically it is equivalent with if, but compact as is it, it is easier to perceive as one logical unit so that it does not blur the larger if construct it might be part of.
  • Use the switch statement instead of if .. else if statements where possible.
  • Don’t use if like duct tape! It might look like an easy solution to add just one little if, but analyzing the code a bit further might produce the real solution to the problem.

If your project shows a tendency towards an ever-growing number of if statements, there must have been something wrong at the very outset. Use cases might have been forgotten or all possible situations were not taken into account in class design. Or maybe the design was too complicated because it didn’t hit the target: You needed a nail file but you designed a Leatherman.

“Well planned is half done” goes the common saying, which we could turn into “Badly planned needs more and more ifs”. When your code is becoming bloated with ifs, it could be still possible to save in the total amount of work by redesigning your application. In real life this is hardly possible because somebody would have to admit that there was something wrong with the initial design, so all you can do is to learn from your mistakes, try to get rid of the project, and to be wiser at the next project, if there is going to be a next project!

Final Countdown for GDI

After writing my previous post, I happened to pass by my archival bookshelf, and an opus caught my eye: Programming Windows by Charles Petzold from 1988. It has been ages since I last opened this classic, and yet, if I narrow my eyes a bit, it looks like it was written yesterday. What we call Win32 API today was just Windows API in 1988, but the 16-bit ancestor is amazingly similar to its 32-bit offspring. Even if we program in a high-level language like C# and use the .NET Framework, this ancient API dictates a lot we do with managed classes. Especially this goes for GDI (in Windows API) and GD I+ (in .NET Framework).

When Graphics Device Interface (GDI) was introduced, there were no hardware-accelerated display adapters. All the grunt work of calculating logical coordinates to physical pixels had to be done by the main processor, either in the application program or in Windows (i.e. GDI). Because performance was rationed, optimizing graphics performance was a joint venture between Windows and the application. Windows tried to be as helpful as possible, but the decisions were left to the application that knew what had to be done and was able to choose the right strategy.

This strategy was known as the “mapping mode” that is still present in GDI+ as the GraphicsUnit property of the Graphics class. In fact all major structures and functions in GDI find their counterparts in GDI+ as properties and methods of Graphics: hDC -> Graphics, SetViewportExt() -> PageScale, SetViewportOrg() -> TranslateTransform(), MoveTo()/LineTo() -> DrawLine(), Ellipse() -> DrawEllipse(), etc. to name just a few. This is all logical because GDI+ has to call GDI to get the pixels all the way to the display device.

Now enter Windows Presentation Foundation! WPF is different because it does not use GDI but gets its message to the display surface through DirectX. Game developers and enthusiasts have known for years that DirectX can use hardware acceleration, which GDI can’t. The mapping mode is gone: WPF uses device-independent pixels, each of which is defined to be 1/96th of an inch. Mapping to physical pixels is done by DirectX assisted by display adapter hardware, which the application can be totally agnostic of.

Drawing methods like DrawEllipse() are also gone – you just place graphic elements like Ellipse or LinearGradientBrush inside other graphic elements, and WPF gets them painted. I would see this as a significant move from imperative to declarative programming, which becomes more obvious if you create these elements in markup (XAML) rather than code (C#). In plain English this means that you tell WPF what you want, not how to do it. I like declarative programming!

I now place Programming Windows back in my shelf next to Kernighan & Ritchie and The MS-DOS Encyclopedia. Sleep well, my friend!

WPF Rules!

I have seen the future, and it works! I just completed my first WPF project and was positively surprised. WPF has been blamed for poor performance, but the result of my work runs fast even on plain-vanilla displays, and it isn’t such a resource hog as blamed, either.

My project was a user control to be seated in a Windows Forms environment – a window into the new world, so to say. The control displays a scrolling structured document that responds to many mouse and keyboard events. The reason it was developed was to replace a document viewer control based on the Windows Forms WebBrowser control that caused a lot of problems. The new control displays a XAML FlowDocument instead of HTML, and, best of all, it doesn’t use any COM.

Struggling with HTML to make the document interactive was a chore and demanded a lot of JavaScript and DOM. Now every single element in the FlowDocument is a C# object and directly accessible. Boy, I like that!

Somebody might say that the future I’ve seen a glimpse of was planned by the Evil Empire. Evil or not, none else but Microsoft has put forward such an innovation to GUI programming. I have nothing against Open Source, but no player on the Open Source field has had the muscle for such an undertaking. Maybe some day WPF will be implemented on Mono, which might happen through experience obtained in the Moonlight project.

I have only scratched the surface of WPF, but so far I’ve seen solid gold only. Craving for new WPF projects!

Migrating Delphi Applications to .NET

I just came by a fairly new set of Delphi tools by CodeGear and RemObjecs, and being an ex Delphi programmer, my mind was flooded with intriguing ideas. How easy would it be to port old Delphi applications into this century, i.e. the .NET world, without the need of a complete rewrite? This would not be the first time it is attempted, but would it be easier now with these brand new tools?

If you have read so far, you probably already know what Delphi is. What you might not know is that CodeGear (now owned by Embarcadero Technologies) released a new .NET version of Delphi just a few months ago. Called Delphi Prism (just Prism here from now on), this MS Visual Studio plug-in is based on Oxygene CLR compiler licensed from RemObjects and fully compliant with the .NET Framework. Both Delphi and Prism compile their own dialect of the Pascal language, of course.

The first attempt towards .NET by Borland/CodeGear was Delphi.NET that first appeared as Delphi 8 in 2003. At first it aroused some enthusiasm, but after all it was no success and was never updated to .NET Framework 2.0. Oxygene/Prism, on the other hand, is not based on Delphi.NET and supports the whole .NET Framework up to version 3.5 and probably beyond.

Porting Delphi Code to .NET

Now, thanks to Prism, you might think that in order to get a .NET application all you would have to do is compile the Pascal sources with Prism, with minor syntax adjustments, perhaps. Well, for your disappointment I have to tell you that there is much more to it than just recompiling the source code. Let’s take a look at a minimal Windows application written in Delphi and Prism!

All this application does is stuff the current date and time into a label that was placed on the main form of the application. The Delphi version looks like this:

Delphi sample

And here’s the Prism version:

Prism sample

Because it’s also written in Pascal, this code bears some structural resemblance to Delphi, but the single line of functional code in our application looks quite different in these two cases: label1.Caption := FormatDateTime(‘c’, Now) vs. label1.Text := DateTime.Now.ToString().

For comparison, let’s have a look at the same application in C#:

C# code sample

The key thing here is the library, namely VCL in Delphi vs. .NET Framework in Prism (or C#). Yes, there is a Label control in both environments, but the most important property bearing the text content is named differently. And to get the current date and time, you would access the Now static property of the DateTime .NET class in Prism whereas in Delphi you would call the Now function that is not part of any class – to say nothing of the formatting of this DateTime value into a string. And this is just the beginning!

Delphi.NET tried to cloak the .NET Framework with VCL.NET, a VCL look-alike that acted as a wrapper around the .NET Framework and implemented the essentials of VCL as calls to .NET. It must have been quite a job to create VCL.NET, and porting it to .NET Framework 2.0 seems to have been even a harder one because it was never really attempted. Moreover, VCL.NET was a dead end because it did not provide a migration path to pure .NET Framework – if you started using VCL.NET, you would be stuck with the VCL object model for the rest of your career!

A more recent undertaking to create a VCL-topping on .NET Framework is ShineOn, an Open Source project initiated by CodeGear. The current version, sorry to say, is just a skeleton that has barely anything implemented. Knowing what happened to VCL.NET, one cannot expect very much from this project. It would be a daunting task to develop a comprehensive VCL replacement that perfectly maps VCL to .NET and does it with no performance penalty.

If these problems with libraries are not enough, look at the Delphi and Prism code samples above! Starting with the word Namespace, there are differences in structure and syntax that originate from the fact that Prism is a .NET language. To alleviate this problem, RemObjecs is developing a tool named Oxidizer that promises to “take care of a lot of the grunt work” that is needed when porting code with manual tools such as search and replace. When it works, Oxidizer can be a great help, but in the end reviewing and finishing the Prism code is something you will always have to do manually in the code editor.

Converting Visual Layouts

You may have noticed that the code samples above were not complete Windows programs – the visual form layouts were missing. We know that VCL forms store they layouts in .dfm files whereas the .NET form designer writes normal program code (Windows Forms) or XAML (WPF). Translating text-based .dfm code to C#, Pascal or XAML is basically something a translator program could do provided it knows the mapping between the UI controls and their properties in VCL and Windows Forms or WPF. Such a tool does not exist yet, but building one is the least of our problems. Even if the tool cannot find a 100 % mapping between the libraries, the amount of manual work is essentially smaller than porting general-purpose program code.

Best of Both Worlds: Running Side by Side

Another option to migrate to .NET would be keep your old native Delphi code as it is and link it with new managed code written in Prism. Calling unmanaged code from Prism or C# is no big deal, but the opposite is also possible. Although linking managed assemblies to Delphi is not as straightforward as linking native Delphi units, it can be done using one of a few routine methods that developers use every day when they move from C, C++ or Visual Basic 6 to C#.

The most common method is to use COM. Assemblies written with Prism or C# can be registered as COM objects that Delphi is able to call, and vice versa. The downside of COM is those woes that made .NET so welcome: the necessity to register all COM objects and the notorious DLL Hell. Were your application anything but trivial, very soon you would have to register and maintain several COM interfaces between Delphi and .NET.

Another method is to use mixed-mode DLL’s that have interfaces to both .NET and native WIN32 code. Unfortunately, they must be written in C++ so you would have to add a third programming language in the mixture.

But luckily there’s still another method, from RemObjects, again! They are selling a tool named Hydra that is based on the concept of plugins. Both plugins and plugin hosts can be written using Delphi or a .NET language (Prism, C# etc.), and thus Delphi applications can host .NET plugins, and .NET applications can host Delphi plugins. Plugins can be visual (kind of user controls) and non-visual (e.g. business components).

Hydra provides a set of wizards and helper components that open windows to the other world through interfaces. Calling the other side through an interface requires some typecasting or late binding, but it seems to work. The best thing is that Hydra does not use COM.

Which Way to Go?

As we have seen, porting Delphi code through Prism to the .NET world is not as easy as it would seem at first glance. If your code interacts with the user interface or relies heavily on VCL components such as datasets, there will be lots of manual work ahead. Only if your code mainly deals with your own classes and barely touches the run-time library, the porting solution would be feasible, but because we are porting a RAD solution, such a situation should not be very frequent. After all, the idea behind RAD has been to rely on smart components and controls, not to write everything from scratch.

What I would recommend is to start in a step-by-step fashion and implement new features and modules as .NET plugins. Depending on the structure of your application, a whole application layer, say the data access layer, could also be implemented as a .NET plugin. A VCL ClientDataSet fed by an ADO.NET plugin sounds quite realistic.

Over time, more and more modules would be migrated, and one day you could translate your form layouts from DFM to XAML, run a raw code translation to Prism with Oxidizer and hand-tune the rest. Personally, I would translate the code all the way to C#, but it’s your choice which .NET language you like to use.

If you are planning to stick with Delphi and completely ignore the evolving .NET world around you, don’t do that for long now! There are .NET technologies such as WCF that are likely to become a must on any line of business, and failing to support them makes your application hopelessly outdated. Delphi was a great tool that opened new perspectives for application development and influenced .NET and C# more than is generally known. The best way to pay homage to Delphi is to give Delphi applications an honorable old age and a chance to be reborn as .NET applications.