Archive for the ‘Design’ Category

Extension Methods and Static Generic Classes

June 15, 2010 1 comment

This post refers to a question on Stackoverflow that I tried to answer a while ago and that still hasn’t received an accepted answer: Why is it impossible to declare extension methods in a generic static class?

Against popular belief, static generic classes are not a problem here, they are perfectly legal but not for declaring extensions methods. The original motivation of the person asking this question was to declare a static generic class defining a constrained generic type parameter once, so the constraints wouldn’t have to be repeated on each declared extension methods.

Consider the following extensions methods:

public static class ExtensionsForIMyInterface
public static void DoSomething(this IEnumerable source) where T : IMyInterface {};
public static void DoSomethingElse(this IEnumerable source) where T : IMyInterface {};

The purpose of this class is to provide extension methods for all types implementing IMyInterface. As you can clearly see, this constraint has to be repeated on every extensions method. If declaring extension method inside static generic classes would be allowed, we could add easily avoid repeating the constraint:

public static class ExtensionsForIMyInterface where T : IMyInterface
public static void DoSomething<T>(this IEnumerable<T> source) {};
public static void DoSomethingElse<T>(this IEnumerable<T> source) {};

But we can’t, so what’s the reason for this constraint?

Gorpik made a good point by mentioning that it would prove difficult for the compiler to locate non-generic extension methods on a static generic class. This would be the scenario:

static class GenStatic<T>
static void ExtMeth(this Class c) {/*...*/}

Class c = new Class();
c.ExtMeth(); // Equivalent to GenStatic.ExtMeth(c); what is T?

This is probably the best justification for the constraint because allowing the declaration of extension methods on static generic classes would make it necessary to constrain those classes to declare generic methods only. Adding yet another special case to provide a little syntactic sugar would pollute the cleanliness of the language design.

Categories: .NET, Design

TDD as a Means to Explore New Platforms

January 15, 2010 Leave a comment

On of my motivations behind the iRow project was to try a 100% TDD approach on a real world project. Being familiar with  features of .net testing frameworks (my favorite is MbUnit), my baseline expectations on the way such a framework should work and integrate into my development environment where set. Unfortunately, I was soon disappointed by the frameworks available. I have written about my research on iPhone unit testing frameworks before, so I won’t list their shortcomings here. In retrospective, working with a testing framework gave me unique opportunities to gain insight into the new platform.

The concrete advantages I experienced were:

  • learn about platform specific build systems and deployment details
  • forced to develop components in a loosely coupled fashion from the ground up
  • explore unique mechanisms of the language, that might require new or make known patterns redundant
  • fast compile-test cycle, less time spent in front of the debugger
  • combined with source control: painless experiments
  • combined with isolation framework: implementation shows how runtime manipulations can be made
  • testing framework implementation shows how code meta-data can be leveraged (or not leveraged)

I can imagine taking this approach to learning new platforms in the future. Plus, I think knowing how to verify the own code is an essential skill on every platform.

Categories: Design, Projects, Tools

Singleton Considerations

November 22, 2009 8 comments

I started out writing this post as a series of comments on StackOverflow but I decided there just wasn’t enough room to discuss this.

The original question is titled “What is so bad about Singletons?” and can be found at StackOverflow here. The answer receiving the most upvotes was:

Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
  2. They violate the Single Responsibility Principle: by virtue of the fact that they control their own creation and life-cycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the app. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.


I agree with him on that. In cases, where such a dependency is not obvious by the classes name, the dependency should be injected. Injecting Singleton Instances into classes proves a wrong usage of the pattern.


All Objects need to control their life-cycle in a way. All objects need to have a constructor/destructor. This is even more true in non-managed languages such as C++/Objective-C where you are responsible of releasing your collaborators (Java and .NET programmers tend to forget that).  A Singleton’s life-cycle is assumed to be the same as the application’s, so I don’t see the need to “control” that here. Most Singleton implementations are using a lazy-load mechanism to instantiate themselves. This is trivial and their life-cycle is unlikely to change, or else you shouldn’t use Singleton.


The GoF Singleton Pattern description includes the following: (p.128, Consequences 3.)

Permits refinement of operations and representation. The Singleton class may be subclassed, and it’s easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time“.

Contrary to static classes, Singleton Instances are normal classes and can therefore inherit from base classes and/or implement interfaces. In order to make a Singleton Instance swappable, you can either choose to inject (“initialize”) a “to-be-Singleton Instance” into the Singleton or lazy-load it based on some configuration info. Throwing exceptions on requests made before the Singleton Instance was initialized (and optionally, when an attempt is made to reinitialize it) ensures the same semantic behaviour as that of a simple Singleton Class. Eventually, this is no different from how an IoC Container would deal with Objects whose lifetime shall be that of a Singleton.


If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc. Note that log files are an exception to that. In most cases their state isn’t significant for the behaviour of the Application. Good examples for the usage of Singletons are PrintSpoolers (fire and forget).

Categories: Design

Cocoa Memory management conventions

October 15, 2009 Leave a comment

Apple uses reference counting as the default memory management technique in its frameworks. Augmented with an autorelease pool that keeps track of the current stack frame and releases objects when the current stack frame exits, it is a reasonable balance between the performance of manual memory management and the comfort of garbage collection I am usually used to working on .NET projects.

However, reference counting establishes the need for ownership conventions that define who is responsible for releasing an object and under what circumstances I can assume a reference to be valid. Unfortunately, I have found these conventions hard to remember every time I created an object, because there are many of them (at least if you have just started Objective-C programming). Thought as a memo to myself, here follows the (hopefully complete) list of conventions:

Creating Objects:

  • Objects retrieved via methods whose name begins with “alloc” or “new” or contains “copy” are retained. The caller is responsible for releasing the object.
  • CoreFoundation Objects retrieved via C functions whose name contains “Create” or “Copy” are retained. The caller is responsible for releasing the object.
  • In any other case, the caller is not responsible for releasing the object e.g. receiving a string from [NSString stringWithFormat:] returns an autoreleased object.

Loading Objects from NIB Files:

  • Objects in the nib file are created with a retain count of 1 and then autoreleased.
  • UIKit reestablishes connections between the objects using setValue:forKey:, which uses the available setter method or retains the object by default if no setter method is available
  • If there are any top-level objects you not stored in outlets, the caller must retain either the array returned by the loadNibNamed:owner:options: method or the objects inside the array to prevent those objects from being released prematurely.

Receiving Objects

  • The conventions governing receiving objects follow from the rules governing object creation
  • A received object can be assumed valid throughout the scope of the caller
  • If a caller wants to retain an object in another scope (e.g. storing it in a private field) he must call -retain and is responsible for releasing the object when done with it

This guide is probably not complete, however it contains the most important rules. For additional detail please see the resources below.


Categories: Design, iPhone
%d bloggers like this: