Categories
Architecture Funny

Exceptionally Bad Exception Abuse

Nick Hodges' Coding In DelphiI was reading Nick HodgesCoding in Delphi again last night (insomnia). In chapter 1 on Exception Handling he opens talking about how not to use exceptions. It got me thinking about some of the atrocious exception usage I’ve seen. I thought I would share a few examples beyond the usual exception sins.

The Try / Except / Raise / Free Pattern

The documentation on the Try / Except pattern says that all the code after the Except block gets ran because the exception is handled. Additionally you can call Raise during the handler to send the exception further up the call stack.

I had just started a new job and was sitting with one of the senior developers to fix some bugs and get to know the codebase. He was creating a local object and so needed to free it. This is the pattern he used:

sl := TStringList.Create;
try
  // using sl
except
  raise;
end;
sl.Free;

I looked at the code for a minute quizzically, and then asked why he did that. He explained that everything after the except always gets ran, so he can be sure the memory is freed, but still let the exception bubble up to the global exception handler so it is logged. I told him that I was pretty sure calling raise in the except block prevented the code after the block from being ran. He assured me he had been writing code like this for a long time, and it always works.

I thought about it a bit more and then suggested we test the code. So we made a little test application with a message after the except block, and forced it to raise an exception, and sure enough, the message didn’t show. (Always test your theories and patterns with test code!)

There was a look of panic on his face. He’d been using this pattern for years, and it was all over multiple codebases. He claimed that the documentation must be wrong or it changed in a recent update, but I tried to assure him that is was clear and always worked that way, he just misunderstood.

Log ’em All and Let Support Sort ’em Out

This was using an early version of C# and WinForms.NET in Visual Studio. I took over a project and was having a hard time tracking down some odd behavior. Some code just wasn’t being ran, and there was no error messages. This was a project that was really, really early in the development process, and my first large scale project in C#, and I was getting really frustrated.

I finally discovered that an exception was being raised, but it was never showing up as an error. Even if the debugger was attached there was no exception message. The program just kept on running as if nothing happened, but the operation aborts. I started to question .NET’s ability to handle exceptions.

I dug and dug and finally figured out that the previous developer had setup a global exception handling and logging system that captured all the exceptions and logged them into the eventual support database with a detailed call stack. IIRC WinForms apps close automatically if there is an unhandled exception, so having an exception handler is a good idea, but silently logging them seems questionable. And then since there was an exception logging system in place the developer set the project options to have the debugger ignore all exceptions.

The result is an app running completely silent of exceptions, even while developing, but at least support will have a lot of debug information. I talked to the original developer, and he thought it was a brilliant idea, and said it is the first thing he does in all his projects. He just looks in the support database to see if things are working. His logic being users don’t want to see error messages. Not sure how hiding all the error messages is a good idea, especially hiding them from the developer during development.

Exceptions as Robust Return Objects

I was maintaining some code where a previous developer built this system where custom Exception were used to return a complex type system. He built this impressive hierarchy of exception classes, and then only certain types of exceptions were handled at different levels, where the data was needed. So instead of methods returning a result, or modifying a passed value, they all just raised different exceptions, with the properties set to different values.

There are really two issues here in my opinion. The first is raising and handling exceptions is rather expensive. A better option would have been to just create plain old objects (or even interfaced objects) and return them as results. You can still examine their types and decide when to handle them. You would just need to be aware of managing the object lifecycle (the automatic lifecycle handling was his justification for using exceptions).

The second issue is this was just one subsystem of a larger project. It was only this subsystem that used this bizarre data management system. So when you were fixing a bug here there was a mental tax of wrapping your brain around the different architecture. As soon as you figure it all out, fix the bug, and move on to other code you go back to the normal way of thinking. Again paying the mental tax of forgetting the atrocity you just witnessed.

I really believe that in a large project there should be some consistency in how the pieces are architected unless there is a compelling reason to do things different in one subsystem. That makes it easier for developers to work in different parts of the system.

So what are the craziest abuses of exceptions and exception handling you’ve seen?

By the way, Nick has a new book out on Dependency Injection in Delphi. You should pick up a copy.Nick Hodges' Dependency Injection In Delphi

Categories
Architecture

MVVM-MVC-RAD Architectures with ColumbusEgg4Delphi

Loosely coupled is good. We don’t want our business logic and data access all mixed together, that makes our code harder to maintain. But we all love RAD and being able to create our applications quickly. Drop some components on the form, set some properties and write a little code and we are done! Unfortunately we usually end up with tightly coupled code.

Most architectures I’ve seen for keeping everything separated results in needing to write all the data binding manually. You still get to design your forms with the visual designer, but missing the data binding kind of sucks.

Modern Delphi Architectures

That all changes with Daniele Teti‘s ColumbusEgg4Delphi. It lets you build loosely coupled applications where the business logic, data access and user interface are all kept separately, but you still get to use all those great RAD design tools. Daniele did a Modern Delphi Software Architectures webinar where he introduced ColumbusEgg4Delphi and explained how it works. You can catch the replay here . . . .

The first 10 minutes explains the need for ColumbusEgg4Delphi, then after that he explains how it works and shows a great example and answers questions.

Is ColumbusEgg4Delphi perfect? I don’t know, but it is a huge step in the right direction.

Check out Daniele Teti’s blog and his company site, his MVC framework, as well as his books.

Categories
Android Architecture iOS Mobile Source Code

Parallel For Loops

Parallel For Loops are a hassle-free way to supercharge your program with the Parallel Programming Library. The syntax is similar to the standard For loop, with the advantage of each iteration running on in a different task on the thread pool. This allows multiple iterations to run at the same time, taking advantage of the multi-core and hyper-threaded architecture common on laptops, desktops and mobile devices today.

Here is the replay of the Skill Sprint:

Here are the slides:

Parallel For Loops with the Parallel Programming Library from Jim McKeeth

Update: I was chatting with Allen Bauer today and he mentioned that while you technically can use Queue and Synchronize from within a Parallel For loop, he wouldn’t recommend it because it will dramatically reduce the speed of the loop. It is still faster than a linear loop, but not as fast as it could be. I’ll leave these examples here, but keep that in mind when optimizing your parallel code.

Here is the syntax in Object Pascal. The stride is the first parameter is it is optional. It controls how the iterations are grouped when being sent to the CPUs. Min and Max are your usual start and stop range for the loop. The last parameter is an anonymous method that represents the code to be executed on each iterations. It takes an Index parameter that is either an Integer or Int64 that provides the value of the current iteration.

TParallel.For(Stride, Min, Max, procedure (Idx: Integer)
begin
  if IsPrime(Idx) then
  begin
    TInterlocked.Increment (Tot);
    TThread.Queue(TThread.CurrentThread, procedure
    begin
      Memo1.Lines.Add(Idx.ToString);
    end);
  end;
end);

Here is the C++ code syntax. It takes a event instead of an anonymous method.

// . . .
TParallel::For(NULL, Min, Max, MyIteratorEvent);
// . . . 

void __fastcall TFormThreading::MyIteratorEvent(TObject *Sender, int AIndex)
{
	if(IsPrime(AIndex)){
		TInterlocked::Increment(Tot);
	};
}

There are some great blog posts and videos on the Parallel Programming Library

Stephen Ball has a series of blog posts on the Parallel Programming Library, including a Quick Introduction and one on managing the thread pool. As Stephen points out, while you can customize the thread pool, that doesn’t alway mean you should. Malcolm Groves also has some great blog posts on PPL.

Danny Wind has a great Code Rage 9 session on the Parallel Programming Library (be sure to download his samples). David I. did the C++ version.

Allen Bauer, our Chief Scientist, also has a CodeRage 9 session on the PPL Architecture.

If you want to take advantage of the new C++11 Lambda syntax on Win64 and mobile, then check out this community article or watch this CodeRage 9 video snippet. Get Bruneau and David’s code for C++ and Parallel libraries.

Update: Keep in mind that a Parallel For loop isn’t always the best performance option, but it is really easy to use. Check out Stefan Glienke’s Stack Overflow answer for an alternative using the PPL TTask for even better performance.

Categories
Architecture

Why Some Mobile Apps are So Slow

If you haven’t read the lengthy article on Why Mobile Web Apps are So Slow I recommend you check it out. It appears well researched, citing lots of tests, sources, benchmarks and authorities. In summary JavaScript is garbage collected, and garbage collection introduces overhead making it up to 5x slower than native code. This isn’t such a big deal on x86 desktops, but with the slower architecture of ARM it is killing the performance of mobile apps.

Take a look at it, even if you just skim it you will no doubt learn something about this heated debate. Oh, and everywhere it talks about LLVM and ARC remember that is the same architecture that Delphi uses [PDF]  for iOS development (and Android soon too).

Also keep in mind that JavaScript isn’t the only garbage collected language on mobile devices. Languages that run on the Java Virtual Machine and .NET Framework are also garbage collected, as are most all scripting languages. This includes the Dalvik Virtual Machine that non-NDK Android apps run on. Granted Dalvik is optimized differently than that Java Virtual Machine, but it is still garbage collected, so it will still pause program execution at some point.

Quote from the article by Herb Sutter:

Managed languages made deliberate design tradeoffs to optimize for programmer productivity even when that was fundamentally in tension with, and at the expense of, performance efficiency

Which was endorsed by Miguel de Icaza of Mono & Xamarin:

This is a pretty accurate statement on the difference of the mainstream VMs for managed languages (.NET, Java and Javascript). Designers of managed languages have chosen the path of safety over performance for their designs.

Points to remember:

  • Garbage collection is up to 5x slower than native code
  • This is a much bigger deal on ARM architecture than x86
  • Automatic Reference Counting (ARC) is not Garbage collection
  • Delphi uses LLVM architecture and supports ARC like Objective-C

Clarification: A big part of the slowdown is that JavaScript is also a dynamic language, so all garbage collected languages are not 5x slower than native code. There are pros and cons to GC and ARC. There is a comment on the article that points out the 5x comparison was between GC and manual memory management, not ARC. There is overhead with ARC, but it doesn’t pause your apps execution.

Read the article and draw your own conclusions, but I’d love to hear what you think.