Tuesday, October 04, 2011

Choices I hate to make: Constructor exceptions vs. Initialize patterns

I'm writing a little sample for Silverlight 5 in Action. Part of it involves a class which integrates with a 3d accelerometer sensor on Windows. In order to use the accelerometer, I have to check to see if elevated permissions is enabled before I go about constructing objects which rely on COM automation. There's also a fair bit of construction activity after that check to create the actual sensor object and prepare the class for use.

There are three approaches to creating this object and performing the initialization. All three have issues. Here they are.
Code in the Constructor

It "feels" right to handle the permissions check in the constructor. However, throwing exceptions from a constructor is generally considered a bad… no, an EVIL practice. The code in this example is the smallest, and tends to be the most easily understood by other developers. Here's an example of what the code might look like (don't get hung up on the specifics of the code itself, as it happens to use the Native Extensions for Silverlight, but could be any similar functionality) :

public class AccelerometerJoystick
{

    private SensorManager _sensorManager = null;

    private Sensor _accelerometer = null;

    private PropertyKey _keyXGs = null;

    private PropertyKey _keyYGs = null;

    public AccelerometerJoystick()
    {
        if (Application.Current.HasElevatedPermissions)


Read more: 10REM.net
QR: choices-i-hate-to-make-constructor-exceptions-vs-initialize-patterns

Posted via email from Jasper-Net