Sometimes you have many entities which have common parts, but also should be addressed uniquely in UI. For example, in a CMS, you have many content types (like news, images, articles, pages, etc.) which have title, URL, SEO settings, etc. in common, but which also have specific fields. For example, image have a path field, while news doesn't have that.

Now when you want to work with these items per page, you encounter long switch and if blocks. For example:

   case ContentType.Gallery:
       // Show gallery specific fields;
   case ContentType.News:
       // Show news specific fields;
   case ContentType.Artiel:
       // Show artiels specific fields;
   case ContentType.Page:
       // Show pages specific fields;

As you increase the number of content types, this lists gets longer and longer. What patterns are available to reduce the length or eliminate this long switch, but at the same time don't result in repetition. (I'm a big fan of DRY).

2 Answers 2


You should use a strategy pattern to handle the different content types. You can put the strategies in a lookup table and then retrieve them as appropriate. The lookup table could be fed from a config-file, if necessary.

public void RegisterContentHandlingStrategies()
    strategies.put(ContentType.Gallery, new GalleryContentHandler());
    strategies.put(ContentType.News, new NewsContentHandler());

public void HandleContent(Content content)
    ContentHandler handler = strategies.Get(content.Type);
  • Can I use strategy pattern for UI elements @Falcon? Commented Aug 4, 2011 at 8:40
  • Sure, strategy is not bound to any layer of the system. If you need strategies to create UI elements, that's perfectly fine. If creational logic is complex and there's a common denominator, encapsulate the strategy creation in a factory.
    – Falcon
    Commented Aug 4, 2011 at 8:43

I am assuming, you display the fields in a generic fashion (e.g. a propertygrid).

If so, you could make the model objects know about their 'public' data. For example, the model base class has a user_customizable_properties method, and in the view, instead of the switch statement, you could do something like

for field in currentLoadedContentType.user_customizable_properties():

Frameworks like ruby/rails or django provide their scaffolding/admin interface this way (although they use a little more reflection than my example)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.