Tag Archives: best practice

The Open Source vs Commercial Development Myth

The two can Co-Exist

Looking around the internet you could believe that open source software development, and commercial software development, are opposing forces that can never meet or work well together.  All experienced software developers know this is simply untrue, and yet the myth seems to perpetuate anyway.

By being careful, and being keeping with the spirit of the freedoms represented by the open source community.  It is possible for open source developments to benefit commercial software, and commercial developments to benefit open source software.  In the almost two dacades that I’ve now been involved in software development both open source and commercial;  I have never found a conflict between the two ideals that couldn’t be solved in a way that helped everyone.

Understanding the Types of Open Source License

The first thing you need to understand is that not all open source licenses are equal.  There are primarily two kinds of open source: copyleft and permissive.  For commercial software development I find it easy to divide the copyleft licenses into “strong copyleft” and “weak copyleft”.  Let me cover the three categories briefly here:

Strong Copyleft

When a software system or library is placed under a Strong Copyleft licenses the author is indicating two things:

  1. He wants others to be able to use the code he has produced.
  2. He feels the code produced has value enough to ask others to share their own changes to the code and share systems using the code under the same terms.

The most prominent Strong Copyleft licenses are: GPLv2 and GPLv3.

Strong Copyleft licenses are sometimes described as having a “viral” affect.  This is due to the fact that any derived work has to be distributed under the same license terms.  In the spirit of the license a derived work is usually intended to include software that references or links to Strong Copyleft software libraries as well as altered versions of the original.  This means for example you can only use GPL code in your commercial application, if you are happy to now distribute your commercial application under the terms of the GPL.

Personally I would describe Strong Copyleft licenses as the least friendly for commercial software development and many commercial development companies have to avoid it to meet the IP desires of customers and business owners wanting software developed.

Weak Copyleft

When a software system or library is placed under a Weak Copyleft licenses the author is indicating three things:

  1. He wants others to be able to use the code he has produced.
  2. He feels the code produced has value enough to ask others to share their own changes to the code under the same terms.
  3. He is happy for the library to be used in closed-source products.

Weak Copyleft licenses are most often used for libraries.  The author wants bug fixes and enhancements added back to the library so it can continue to improve, but doesn’t care about how you license the software that utilises the library.

The most prominent Weak Copyleft licenses are LGPLv2.1, LGPLv3, MPL, and MS-PL.

Weak Copyleft licenses are mostly about encouraging you to share fixes and enhancements to core functionality and keeping those fixes and enhancements “free”.  It does not generally have the same “viral” affect as strong copyleft licenses because software that references or links to weak copyleft software libraries as not intended to be considered derived works.  This means you can use LGPL code in your commercial application, and distribute your main software under any license you want, however any changes you make to the copyleft library must be distributed under the original copyleft license.

Personally I would describe Weak Copyleft licenses as very friendly to commercial software development.  It encourages you to get benefit from somebody else’s effort, and simply asks for improvements to be shared in return.


When a software system or library is placed under a permissive licenses the author is indicating three things:

  1. He wants others to be able to use the code he has produced.
  2. He’d like some credit for the work he has put in.
  3. He is happy for the code to be used in any future open source or closed source application.

The most prominent permissive licenses are BSD, MIT, and Apache.

Permissive licenses are about preventing wasted effort while people to reinvent the wheel.  The functionality of the code is shared freely for open source or commercial use.  There is no “viral” affect, and you do not need to contribute changes back to the original author or project team, although this doesn’t mean you shouldn’t.

Personally I would describe Permissive licenses as very friendly to commercial software development.  It encourages you to get benefit from somebody else’s existing effort rather than wasting time reproducing the same functionality.  In exchange usually all that is asked for is acknowledgement of the codes origins.

Keeping the Spirit of the Original License Choice

Its important to understand that open source licenses work within the restrictions of the existing copyright framework.  This differs slightly country to country, and generally only forms contracts between people code or software is “distributed” to.  If you are not careful you can get caught up in questions of “can I do this with license X?” or comments “I don’t have to do that because license Y says you are not entitled to it”.  This is not what the open source community is about.  I believe that as well as keeping to the letter of the licenses, you should honour the spirit of the license regardless of the “additional rights” awarded by copyright laws in your country.

If you take a GPL library you want to use, and try and come up with ways to use the software “indirectly” to avoid putting your own code under the GPL, stop and think again.  The code you want to use was shared by the author because he wanted to see enhancements to it shared too.  You may not want to share your innovations., you may not like the GPL.  But that was the intention of the author and you should honour it or choose not to use the GPL code.

Likewise don’t think that because you upload copyleft software you developed to a web server you didn’t “distribute” it so you can keep the source closed.  And don’t create a “wrapper library” around an LGPL library where you add your new functionality so you don’t have to share it.  This isn’t the intention of the author when they let you use their code, and you shouldn’t abuse their intentions for your own gain.

If a product is dual licensed under copyleft and non-copyleft licenses, don’t constantly push the boundaries of what you can do with the copyleft version, contribute to the funding of the library or software by buying a license so it can continue to improve.

Giving Back

There are many ways to give back to the open source community as an commercial software developer.  Some are really simple but under commercial pressures are often ignored.

1. If you fix a bug in a library, no matter what license its under, submit the change back to the author or project team.

2. If you make minor enhancements that are generically useful, submit them back to the author or project team.

3. Don’t contribute incomplete changes or changes specific for your needs only back to the author or project team. These changes usually carry no reusable value and can waste the project’s time tidying them up for inclusion.

4. If you create a library or tool because you couldn’t find the one you needed in the market, and its not something you are wanting to commercialise on its own, make it available under an open source license you are comfortable with so others don’t have to repeat your effort.

5. If you create a useful program, library, or tool; consider duel licensing a “community” edition under a copyleft license.  Yes its true some developers and organisations won’t honour the license, but generally those people would have broken your commercial license terms if they had a chance too.  This dual licensing can be particularly useful for libraries as it can attract the attention students and others keen to learn your libraries or software, and this can in time become a major source of paid license users in the future.

6. Even if you are working on an open source project, don’t change the license of code from permissive to copyleft by adding enhancements and fixes under your project’s copyleft license rather than the original permissive license.  This practice has long been a point of contention between advocates of permissive licenses and those using their code in copyleft projects.  The overall project can still be copyleft, while honouring the spirit of the license for permissive code you use and giving back under the same license.

Commit Pitfalls

Here are a few of the pitfalls that can happen if you’re not careful combining open source software with commercial software products.

1. When you use an open source library don’t assume the author will carry on enhancing it in the future, and don’t assume someone else will fix the bugs.  Many open source projects are maintained in people spare time, and so every day some projects go stale as project teams move away, or change direction.  If you use an open source library in your commercial product, remember that you must plan to be able to maintain it in the future.

2. Always check the license before using an open source library.  Is it compatible with the IP requirements of you and your customers?  Does it have an explicit non-commercial use clause?  Its even worth checking this if you think you “know” the license the project is under.  Its not uncommon for exceptions or additional clauses to be added on top of standard licenses.

3. Don’t expect you can open source a dying product to “hand over” maintenance of it a community.  Be aware that the original author or team of an open source product, always end up the major contributors to that project long term.

4. Don’t assume because you didn’t pay for something, its cost is zero.  You still need to integrate the software or library into your solution, and you still need to train developers on its code base so you can maintain it within your SLAs.

5. Don’t dismiss a GPL library until you’ve checked the license.  Some projects prefer the use of the GPL over the LGPL but add explicit exceptions for the linking of close-source software.


Open source and commercial software can benefit each other, even if their license terms sometimes seem contradictory.  By following the license requirements, and keeping with the spirit that caused the author to open source their software in the first place, the open source projects can benefit from bug fixes and enhancements from commercial users of their software.

Closed source commercial software can benefit by using stable versions of open source libraries reducing development times and potentially delivering a richer experience.

Both open source and commercial users benefit from a dual licensing scheme where it is appropriate, with the larger user base providing a useful support and learning network, as well as a pattern of many active open source users progressing to paid services in the future.

The small print: I’m not a lawyer so please take this article as me sharing my experience as an open source and commercial software developer rather than legal advice about licenses and copyright law.

C# Code Guidelines

Coding Guidelines

Every development team or software development team need guidelines to follow to help them write consistent code that keeps maintenance costs low, and development productivity and code reuse high.

I recently updated the ones I use with my team, and though I’d share them to save others having to create their own.  Feel free to reuse in part or full for yourself or your team, and leave a comment with any general suggestions.  Style can be a very personal thing, so don’t be afraid to adapt them to meet your teams own preferences, the key is that all the team follow the same convention, and wherever possible that convention matches the underlying framework you are using.

Naming Conventions


Use PascalCasing for namespaces, types, and member names.

Use camalCasing for local variables, parameters, and user interface fields.

Use camalCasing with an “m_” prefix for private non-user interface fields.

In 3rd Party Templates or code that uses a “_” prefix within a class rather than a “m_” prefix then be consistant within the class and either rename all to “m_” or continue with the “_” prefix.

Type Notations in Variable Names

Hugarian Notion must not be used – When the type is an important part of the variable’s purpose include it in the name by prefixing or postfixing it to the name without abbreviation.

Do not use abbreviations – If an acronym is widely accepted and used in the framework or toolkit being referenced then it acronym may be used despite the rule to avoid abbreviations.

.NET Word Conventions

Following .NET conventions for the words:

  1. Indexes (not Indices)
  2. UserName (not Username)

Use the following symmetric words when defining pairs of functionality:

  1. Add / Remove
  2. Insert / Delete
  3. Create / Destroy
  4. Initialize / Finalize
  5. Get / Set
  6. LogOn / LogOff
  7. Begin / End
  8. Register / Unregister

Use the following American words rather than the British words for member names:

  1. Color
  2. Initialize

Use of Plural and Singular Words

Name all classes with a singular word or phrase.

Name all collections or with plural words or phrases.

Name all namespaces as plural words or phrases unless the namespace has a special meaning in the MVC framework.

Compatibility with COM and other CLR Languages

Do not name two public or protected members with names that are the same excluding character case.  This would prevent reuse of the classes in languages such as VB.NET.

When an argument for a class is passed in to a method or constructor with the purpose of setting the public member, then use of the same name in camelCase rather than PascalCase is recommend over prefixes or suffixes.


Name all static singletons that initialise themselves “Default” unless there is a specific reason to use another name.

Name all static singletons that do not self-initialise “Current” unless there is a specific reason to use another name.

Simple Names

The following simple names are allowed for the uses specified:

  1. obj – to store a generic object who’s type is unimportant.
  2. i, j, k – for control of loops.
  3. s – to store a string value of a variable already in scope in a different type.
  4. e, ea, ee – for subclasses of EventArgs.
  5. e, ex – for subclasses of Exception.
  6. item, it – for the control variable in LINQ query expressions.

Use of Types in Variable Declarations

Use the most specific type available in a variable declaration that is not initialised in-line.

Use var for types that are initialised in-line.

Do not use var for types that are initialised in-line to values of a standard type (e.g. int, string, decimal etc.).

Use var for variables that are initialised as the result of method calls that return collections.

Use var for variables that are storing anonymous types.

Use var when the exact type of a variables is unimportant to the method as more than a return value from an invocation.

Use object for types that are initialised as the result of method calls where the return type is going to be worked with only via reflection.

Use interfaces for variable types if the work being done is dependent only on the interface.

Use dynamic as a variable type only if the type could not be known at compile time, and the code is not going to reflect on the type.


Constructor Performance

Avoid use of database connections in constructors.

Avoid use of network calls in constructors.

User Interface Design Time Requirements

Constructors for User Interface classes must be design time compatible.

Member Initialisation

Do not add constructor overloads that perform member initialisation as part of its parameters, these should now be handled by the member initialisation syntax.

Factory and Dependency Injection

Provide a zero parameter constructor unless the class is entirely unusable without a parameter.

Ensure the zero parameter constructor is suitable for use in a class factory or service locator.

Ensure the zero parameter constructor is suitable for use in dependency injection.

Ensure constructors do not over initialise to prevent subclasses from changing implementation details.

Virtual Calls

Avoid calling virtual members from constructors as the behaviour is unpredictable.

Static Constructors


Avoid initialising static members within static constructors.

Wherever possible initialise static members on first use.

Asynchronous Code

Use the await and async keywords when creating asynchronous code.

Prefix “Async” onto all methods that need to be awaited.

Do not prefix “Async” onto any method that cannot be awaited, even if the method contains asynchronous code.

When blocking methods are part of a Portable Class Library and cannot use the await and async keywords, use extension methods with the “Async” prefix to provide asynchronous alternatives for platforms that support it.

When to use Properties, Methods, and Extension Methods


Use a property if:

  1. The functionality behaves like a field.
  2. Is a logical attribute of the type.
  3. Is unlikely to throw exceptions.
  4. The contained code has minimum value when debugging.
  5. Does not have a dependency on the order being set.

Never use a property if:

  1. A get implementation is not provided.


Use a method if:

  1. The operation is a conversion.
  2. There is an observable side-effect from the call.
  3. The order of execution is important.
  4. The method may not return.
  5. The method may run code asynchronously.
  6. The result should be cached for reuse within the calling method for performance.

Do not use a method if:

  1. The return value is a collection that remains linked to the instance.

Extension Methods

Use an extension method if:

  1. The operation needs extend a sealed type.
  2. The operation needs to apply to anonymous types.
  3. The operation needs to apply to general IEnumerable types.
  4. Base functionality is provided for an Interface.

Do not use extension methods if:

  1. The behaviour may want to be specialised by a base class.

Place extension methods that form part of a classes or interfaces core API, or platform specific extensions to the core API, in the same namespace as the class, even if it is provided by another assembly.

Always place extension methods that extend core .NET types outside of the System.Collections namespace in a namespace ending in “.Extensions” to avoid littering the namespace of these core objects.

Method Arguments

Name method arguments with names that inform the caller of the intended purpose, not of its internal use.

When a Boolean argument is used as a flag to change fundamental functionality of a method, always call it using the “name: true” style.

Use Boolean arguments called with the “name: true” instead of two member enumerators for all methods, unless the method extends an API where an existing enumerator is better suited.


Catching Exceptions

Only catch exceptions of specific types if the error message being returned will be specialised for the type.

Catch the generic Exception type to isolate calls from the calling code.

A user must be informed of an exception with an error or warning message.

An error or warning message can be omitted if an exception is caught and ignored to avoid a known framework or platform issue and the issue is commented within the catch block.

Do not catch the general Exception type and hide its value from the user.

Throwing Exceptions

Use the existing Exception types to throw your own exceptions.

Only create Exception subclasses when they are to be used multiple times within a library.

LINQ, for, and foreach.

Use LINQ for queries to external data sources.

Use LINQ for queries over in memory data that is designed for use as a dictionary or database.

Use foreach () for iterating over any IEnumerable.

Use var as the item type for the foreach() loop whenever the IEnumerable implements IEnumerable<T>.

Use for() when the iteration is controlled by a numeric block.

Use for() to walk hierarchies.

Use for() or while() when the iteration is controlled by a non-numeric exit condition.

Use do { } while () only where it reduces code compared to a for() or while().


Member Comments

Every public member or class must be commented with an XML comment.

Every protected method and property must be commented.

The comment must be written to explain why somebody would want to invoke the code.

The comment must not be a substitute for a bad member name.

The comment should not attempt to list all exceptions that could be thrown but should exceptions of special Exception subclasses thrown directly by the code.

Do not comment private or internal methods that have obvious use.

Do not comment event handlers unless their implementation is non-obvious.

Ensure member comments are suitable for extraction into API documentation.

Do not repeat the XML comment for overridden methods if the comment has nothing new to add to the base type comment.

Do not repeat the XML comment for the implementation of a member for an interface if the comment has nothing new to add to the interface member comment.

Code Block Comments

Comment code with headers within blocks that perform multiple tasks discrete as part of its implementation.

Comment code blocks that cannot be understood by the code alone.

Comment code wherever a special or magic value is used.

Comment code when a condition in a control block could be misunderstood.

Comment Styles

Use /// Comments when commenting members or classes.

Use // Comments when commenting code blocks or statements

Use /* */ comments only if the comment has to be placed in the middle of a line of code or within a Razor syntax document.

Special Developer Comments

Always mark comments that are reminders of code to fix with “TODO” in upper case followed by a message.  This allows all TODO items to be found and completed or before the release of any solution.

If the last statement of a non-void method is not a return statement, place the lint style comment “/* NOTREACHED */ at the bottom of the method so developers know to maintain this when editing the code.

Braces and Brackets

Brace Positioning

Place opening braces for classes, namespaces, and members on new lines.

Place opening braces for code blocks such as if, for, foreach, while, do, and switch on the same line as the code control statement.

Place all closing braces on new lines.

Place both the opening and closing braces for automatic properties on the same line as the property name e.g. public int MyProperty { get; set; }

Place both the opening and closing braces for anonymous types used as property bags on the same line e.g. Html.Link(“Test”, new { this = “that” })

Place else and else if statements on the same line as the closing brace and keep the next opening brace on the same line too.

Bracket Positioning

Place a space between keywords such as if, for, foreach, and while, and the opening bracket.

Do not place a space between a method name and its opening bracket.

Keep the closing bracket on the same line as the opening bracket in the argument list is small.

If the argument list for a method call is long: keep the opening bracket on the same line as the method name, place each argument on a separate line ending with a comma, and place the closing bracket on a new line.

17 Years of Porting Software… Finally Solved

A History of Porting Software

I’ve been involved in creating and maintaining commercial and open source software for as long as I can remember, reaching back to 1996 when the world wide web was in its infancy, and Java wasn’t even a year old.

I was attracted to the NetBSD project because of its focus on having its software run on as many hardware platforms as possible.  Its slogan was, and remains “Of course it runs NetBSD”.

Although the NetBSD team worked tirelessly for its operating system to work across every imaginable hardware platform; much of the new open-source software development was talking place in for the i386 focused GNU/Linux operating system, not to mention the huge volume of Windows-only software that Wine tried, and mostly failed, to make available to people on non-Windows operating systems.

Advocates of cross-platform software like me were then constantly choosing between recreating or porting this software depending on its licenses terms and source availability just so we can use it on our platform of choice.

Some of the early of my open source contributions that are still available to download demonstrate this really well such as: adding NetBSD/OpenBSD support to Afterstep asmem in early 2000.  Or allowing CDs to be turned into MP3s on *BSD platforms with MP3c in the same year.

In 2002 when the large and ambitious KDE and GNOME desktops started to dominate the Linux desktop environments, I worked on changes to the 72 separate packages needed bring GNOME 2 and to NetBSD and became the primary package maintainer for a number of years.

As an early adopter of C# and the Microsoft .NET Framework I also worked through 2002 and 2003 to make early versions of the Mono project execute C# code to FreeBSD, NetBSD, and OpenBSD too.

The #ifdef solution

How was software ported between platforms back in those days?  Well to be honest, we cheated.

We would find the parts of the code that were platform specific and add #ifdef and #ifndef statements around them with conditions instructing the compiler to compile, or omit, different sections of code depending on the target platform.

Here is an example of read_mem.c from asmem release 1.6:

 * Copyright (c) 1999  Albert Dorofeev <Albert@mail.dma.be>
 * For the updates see http://bewoner.dma.be/Albert/
 * This software is distributed under GPL. For details see LICENSE file.

/* kvm/uvm use (BSD port) code:
 * Copyright (c) 2000  Scott Aaron Bamford <sab@zeekuschris.com>
 * BSD additions for for this code are licensed BSD style.
 * All other code and the project as a whole is under the GPL.
 * For details see LICENSE.
 * BSD systems dont have /proc/meminfo. it is still posible to get the disired
 * information from the uvm/kvm functions. Linux machines shouldn't have
 * <uvm/vum_extern.h> so should use the /proc/meminfo way. BSD machines (NetBSD
 * i use, but maybe others?) dont have /proc/meminfo so we instead get our info
 * using kvm/uvm.

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#include "state.h"

#include "config.h"

/* sab - 2000/01/21
 * this should only happen on *BSD and will use the BSD kvm/uvm interface
 * instead of /proc/meminfo
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>

#include <uvm/uvm_extern.h>
#endif /* HAVE_UVM_UVM_EXTERN_H */

extern struct asmem_state state;

#define BUFFER_LENGTH 400
int fd;
char buf[BUFFER_LENGTH];
#endif /* !HAVE_UVM_UVM_EXTERN */

void error_handle( int place, const char * message )
	int error_num;
	error_num = errno;
	/* if that was an interrupt - quit quietly */
	if (error_num == EINTR) {
		printf("asmem: Interrupted.\n");
	switch ( place )
	case 1: /* opening the /proc/meminfo file */
		switch (error_num)
		case ENOENT :
			printf("asmem: The file %s does not exist. "
			"Weird system it is.\n", state.proc_mem_filename);
		case EACCES :
			printf("asmem: You do not have permissions "
			"to read %s\n", state.proc_mem_filename);
		default :
			printf("asmem: cannot open %s. Error %d: %s\n",
				state.proc_mem_filename, errno,
	default: /* catchall for the rest */
		printf("asmem: %s: Error %d: %s\n",
			message, errno, sys_errlist[errno]);

#ifdef DEBUG
/* sab - 2000/01/21
 * Moved there here so it can be used in both BSD style and /proc/meminfo style
 * without repeating code and alowing us to keep the two main functions seperate
#define verb_debug() { \
       printf("+- Total : %ld, used : %ld, free : %ld \n", \
                       state.fresh.total, \
       printf("|  Shared : %ld, buffers : %ld, cached : %ld \n",\
       printf("+- Swap total : %ld, used : %ld, free : %ld \n",\
#define verb_debug()
#endif /* DEBUG */

/* using kvm/uvm (BSD systems) ... */

#define pagetok(size) ((size) << pageshift)

int read_meminfo()
      int pagesize, pageshift;
      int mib[2];
      size_t usize;
      struct uvmexp uvm_exp;

      /* get the info */
      mib[0] = CTL_VM;
      mib[1] = VM_UVMEXP;
      usize = sizeof(uvm_exp);
      if (sysctl(mib, 2, &uvm_exp, &usize, NULL, 0) < 0) {
        fprintf(stderr, "asmem: sysctl uvm_exp failed: %s\n",
          return -1;

      /* setup pageshift */
      pagesize = uvm_exp.pagesize;
      pageshift = 0;
      while (pagesize > 1)
              pagesize >>= 1;

      /* update state */
      state.fresh.total =  pagetok(uvm_exp.npages);
      state.fresh.used = pagetok(uvm_exp.active);
      state.fresh.free = pagetok(uvm_exp.free);
      state.fresh.shared = 0;  /* dont know how to get these */
      state.fresh.buffers = 0;
      state.fresh.cached = 0;
      state.fresh.swap_total =  pagetok(uvm_exp.swpages);
      state.fresh.swap_used = pagetok(uvm_exp.swpginuse);
      state.fresh.swap_free = pagetok(uvm_exp.swpages-uvm_exp.swpginuse);
      return 0;

/* default /proc/meminfo (Linux) method ... */

int read_meminfo()
	int result;
	result = lseek(fd, 0, SEEK_SET);
	if ( result < 0 ) {
		error_handle(2, "seek");
		return -1;
	result = read(fd, buf, sizeof buf);
	case 0 : /* Huh? End of file? Pretend this did not happen... */
	case -1 :
		error_handle(2, "read");
		return -1;
	default :
	buf[result-1] = 0;
	result = sscanf(buf, "%*[^\n]%*s %ld %ld %ld %ld %ld %ld\n%*s %ld %ld %ld",
	case 0 :
	case -1 :
		printf("asmem: invalid input character while "
			"reading %s\n", state.proc_mem_filename);
		return -1;
	return 0;

#endif /* (else) HAVE_UVM_UVM_EXTERN_H */

int open_meminfo()
	int result;
	if ((fd = open(state.proc_mem_filename, O_RDONLY)) == -1) {
		error_handle(1, "");
		return -1;
#endif /* !HAVE_UVM_UVM_EXTERN_H */
	return 0;

int close_meminfo()
#endif /* !HAVE_UVM_UVM_EXTERN_H */
	return 0;

It wasn’t neat.  It increased code complexity and maintenance costs, but it worked.  And we all accepted it as the best we had for now.

Hopes of a Brave New World

Like many cross-platform advocates, I had big hopes for Java and C# with the Microsoft .NET Platform.  But sadly we never saw the fulfilment of their “platform independent” coding promises.  Too many times we have to choose between a GUI toolkit for a platform and looking out of place.  Other times we had to P/Invoke to native APIs to get at functionality not exposed or reproduced by the frameworks.  Even now the GUI toolkit Gtk# is recommended over standard Windows’ System.Windows.Forms on Mono when creating C# programs for Linux or *BSD.

Cross Platform Toolkits such as SWING for Java and Qt for C++ sprung up to abstract the user from the platform they were working with.  But they were primarily GUI toolkits and their APIs only went so far, and eventually, like it or not, all but the most simple applications ended up with a native API call or two wrapped in an #ifdef style condition.

How Web Development Made it Worse

With the rapid increase in Web Development many saw this as finally the way to deliver software across multiple platforms.  Users accessed software via a web browser such as Netscape Navigator and didn’t need the code to work on their own PC or operating system.

Of course behind the scenes the CGI programs were still platform specific or littered with #ifdef statements if they needed to work on more than one server OS.  But the experience of the end user was protected from this, and it looked like a solution may be in the pipeline.

But then the Netscape vs Internet Explorer browser wars happened.  Browsers competed for market share by exposing incompatible features and having sites marked as “recommended for Netscape” or “works best in IE”.  People wanting to support multiple browsers started having to litter their code with the JavaScript equivalents of #ifdef statements.  The same happened again CSS as it became popular.  Nothing really changed.

Enter the Mobile

Then along came the iPhone, and made a bad situation even worse.

Those who went for a native implementation had to learn the rarely used Object-C language.  This helped Apple to avoid competition as developers scrambled to be part of the mobile revolution, but deliberately made portability harder rather than easier.  That still remains part of their strategy today.

People turning again to the web for solutions found that accessing web sites carefully formatted to look great on 1024×768 screens, now being viewed on a tiny mobile phone screen in portrait orientation – was ugly at best, but more often unusable!  And it wasn’t just about text size.  Touch and other mobile specific service meant users expected a different way of interacting with their applications, and browser based software felt more out of place than ever. Yes Responsive Web design and HTML 5 go a long way towards solving some of these web specific mobile issues, but it doesn’t take us away from the #ifdef style logic that has become an accepted part of web application development as it did C and C++ development before it.

So What is to be Done?

Most of this article has been about a history of failures to tackle cross-platform software head on.  Each attempt did bring us a little closer to a solution, but throughout we resigned ourselves to the fact that #ifdef style code was still ultimately necessary.

As application designers and developers we had to choose between how native our applications felt and limiting users from using our software in situations we didn’t plan for.

For almost two decades I’ve been involved in trying to overcome this cross-platform problem.  Now the landscape is more complicated than ever.  Can the same software really run without compromise both inside and outside the browser?  Can we really have a native look and feel to an application on a mobile, tablet, and as desktop PC, is wearable computing going to be the next spanner in the works?

All this is why to move forward, we went back to basics.  We thought first about how software was designed, rather than the libraries and languages that we used.  We first made the Mvpc design pattern, and only then did we make there reference libraries and the commercial Ambidect Technology (soon to be known as Ambicore).  Its fair to say that our many years of experience led us to be able to finally learn from the past we had been so involved with, rather than allowing ourselves to repeat our mistakes again and again.

Because Ambicore provides access to the whole .NET Framework gives a complete cross-platform API that’s developers already know.  Use of C# as our first reference language gives us access to the great thinking that went into creating the Java JVM and Microsofts IL environments that really can abstract us from the operating system and help us avoide #ifdef statements.

Providing native GUI interfaces for each platform means applications using the platforms own recommended toolkit helps applications look and feel native everywhere – simply because they are native to each platform.

Providing a design pattern that works equally well in request-response stateless environments and in rich state-full environments allows us from day one to provide a browser based experience for those who want or need it, as well as a native rich client experience for those wanting to get more from their Windows PCs, phones, tablets, Macs, Linux, *BSD, or…

Its taken 17 years of personal involvement, and recognising and listening to visionaries in the industry.  But by standing on the shoulders of others we re-thought the problem, knowing #ifdef statements were as much part of problem as they were a solution.  We redesigned the development pattern to be portable by default, not as an after thought.  And we based our reference libraries on trusted platforms from market leaders such as Microsoft to make our technology available to the largest pool of developers possible in a language, framework, and IDE they already know.

We are stepping into a new chapter of software development where the platform and device is there to enable, not restrict, the end user from the software they want.  And just as we stood on the shoulders of giants to get here – we want you to join us in the new world too.


If like me you’ve worked with C# and the .NET framework for years then you will probably have written variations on following code hundreds of time when trying to display values on screen or save values into text based files or SQL statements:

object rawValue = SomeMethodCall();
string displayValue = String.Empty;
if (rawValue != null) {
    displayValue = rawValue.ToString();

The code itself is simple enough to get right first time, and easy to read and understand, but after you’ve written it a few dozen times it starts to appear like unwelcome rash across your code. A programmers next natural instinct is to see if there is a way to shorten the code.

Unfortunately the ?? operator can’t help us here unless we are exclusively dealing with strings for rawValue (in which case why are you calling ToString()?). We can however shorten things substantially with the ? operator:

object rawValue = SomeMethodCall();
string displayValue = (rawValue == null? String.Empty: rawValue.ToString());

This has helped and taken our code from five lines to two, and hasn’t noticeably affected readability. But if we are only interested in the displayValue woundn’t it be nicer if we were able to just do:

string displayValue = SomeMethodCall().ToString();

This code will execute fine, but as soon as a null object is returned from SomeMethodCall() we’ll get a NullReferenceException raised and if we didn’t see it in testing, our end users will see an unhandled exception we should never have introduced.

If we try to use the ? operator directly with the method call and the best you can get is:

string displayValue = SomeMethodCall() == null? String.Empty: SomeMethodCall();

You can tell immediately from the code that this would be at best wasteful if not potentially damaging depending on the side effects of SomeMethodCall(). Under normal circumstances, where SomeMethodCall() doesn’t return null, we end up executing SomeMethodCall() twice. If the method accesses a web service or database we will have potentially doubled the impact of the code on the server, and slowed down the user experience.

What can be done then? Should we just put up with the two line of code where one would work? Until recently I would have said yes, but with LINQ usage on the rise I’ve started to see this particular problem causing ugly code to be written for lambda statements, or worse developers knowingly being lazy with their handling of potential null values when calling .ToString()!

We can actually use a little used feature of extension methods to help us with this problem. As you will know extension methods allow us to invoke static utility methods in a syntax that mirrors invoking a member of a class. The compiler understands the code that calls an extension method and effectively re-writes the syntax from a member call to a static method call for us. To get an idea of how this works take a look at my previous post.

Because the member-like syntax is converted into a static method call, it is possible to call the member on a null reference.  Therefore the first line of the following code would throw a NullReferenceException, but if MyExtensionMethod() was an extension method that handled a null specially, the second will not.


Using this technique we are able to create extension methods that special case null values, but maintain the readable member-style syntax.

I’m going to throw a strong word of warning in here now. When you add an extension method that does not behave like a member method call, particularly ones that don’t raise a NullReferenceException when called on a null variable you are moving away from basics that programmers take for granted when reading code. Used incorrectly this can make code harder to understand and therefore harder to understand. You should be sure about what you are doing before you add extension methods that expose this non-standard behaviour. Its been my experience that methods that should follow this behaviour are almost always involved with displaying values as strings, or converting values between types to pass to an ORM or similar module.

My personal convention to make sure I can identify where the technique has been used is to suffix the method name with “Safe”, so the call above would be MyExtensionMethodSafe(). If everybody in the team follows this convention when they feel there is a genuine need for the extension method to treat nulls differently to a member method call then the code remains easy to read. Don’t forget however that even if you’ve adopted this convention throughout your team, you will still have to train new people joining the team on the convention.

Now with that warning having been strongly stated, lets return to looking at the problem at hand. In this case I believe it makes very good sense to provide a “Safe” extension method companion to ToString(). Here is the code for the ToStringSafe() extension method in full:

namespace Mvpc.Extensions
    public static class ObjectExtensions_ToStringSafe
        public static string ToStringSafe(this object value)
            // Nulls just return empty strings.
            if (value == null) {
                return String.Empty;

            return value.ToString();

If you read my post on async extension methods you will already know that I recommend placing any extension method that works on string, object, int, or any of the core types of the .NET Framework under a namespace ending in “Extensions” so they don’t litter the initilisense when the user doesn’t need them. This rule applies here too as the majority of code will not want to use the ToStringSafe() method.

After adding a using for the Mvpc.Extensions namespace it finally becomes simple to write:

string displayValue = SomeMethodCall().ToStringSafe();

We finally get our five lines of oft-duplicated code down to a single readable line.

Since introducing this new method I’ve completely stopped seeing programmers being lazy with their .ToString() handling of nulls inside lambda statements. Hopefully you will see the same too as well as being able to produce more readable null-safe code.

Increase readability with the var keyword and DRY in C#

When the var keyword was first added to the C# language many developers shyed away from it believing it to be a “Variant” type like found in VB.NET or the equivalent of declaring an variable as an object.  Both of these are wrong, but despite this I’ve come across plenty of companies that still ban the use of var in their coding standards stating that it is not type safe.

The var keyword is completely type safe and is actually the equivalent of you typing the name of the type yourself but deciding it was easier to let the compier type the whole name for you.  I find it better simply to look at the var keyword as a timesaver that instructs thecompiler that there is no reason for you to specify the type because: 1. anybody reading it can see the type immediately.  2. The exact type is unimportant as long as it meets the requirements of the code.

Its also worth pointing out at this stage that with modern IDEs I also consider the use of embedding type names into variable names using Hungarian notation or other similar approaches is also not only bad practice, but dangerous compared to proper use of DRY (Don’t Repeat Yourself) principles.

I use the var keyword all the time and find it makes code more readable, not less readable, especially when working with long type names.

For example line one here is much easier to read than line two. In fact in line two you have to search just to find the name of the variable.

Example 1

MyType hello = new MyType();
System.Collection.Generic.Dictionary<string, MyLibrary.Namespace.MyType2> goodbye = new System.Collection.Generic.Dictionary<string, MyLibrary.Namespace.MyType2>();

Using var both lines are equally easy to understand, and the name of both becomes the primary focus of the line rather than the type:

Example 2

var hello = new MyType();
var goodbye = new System.Collection.Generic.Dictionary<string, MyLibrary.Namespace.MyType2>();

Not to mention that you now have one less place to change if you decide to use MyType3 instead of MyType or MyType2 in this code block.

Using var on lines that already perform a cast can give similar readable and time saving advantages.

Example 3

var world = (Button)sender;
var universe = sender as System.Windows.Form;

I also recommend using var for variables that are used to store results from methods where the type is unimportant either because we simply returning it or passing it to another method, or in the of enumerables, we have to specify the type name when we use it anyway.

Lets have another couple of real world examples:

Example 4

var value1 = GetValueFromDatabase(1);
var value2 = GetValueFromDatabase(2);

var value3 = Combine(value1, value2);
return value3;

Reading the example alone you have no idea what type var is. This can upset some people, but if you are using Visual Studio its easy enough to mouse-over each “var” keyword to see the type that’s being used. But if you stop and think for a moment the reason you don’t know each type is because the current code doesn’t need to know. By practicing DRY here you’ve actually created code that’s much easier to maintain and is completely type safe. If in the future GetValueFromDatabase() was changed to return a decimal instead of an int it wouldn’t matter as long as Combine() had an overload that accepted decimals as parameters, or was changed at the same time. If we don’t use var then we would have to edit the code ourselves to switch value1, value2, and value3 from int to decimal, even though the changes has had no real affect on the current code block.

There are of course times when specifying the type explicitly over using var gives important extra information to the user then it should be used instead of var, but you will find these situations are few and far between. I might choose to use “int” for example if I was getting an int defined and returned from a method call in one line, but only if the fact I was performing some integer rather than floating point maths is important within the current code block. Otherwise I’m just making it hard to change the methods definition to work with double or decimal in the future.

Example 5

var form = new Form1();
var res = form1.ShowDialog();
if (res == DialogResult.Cancel) {
    // ...

We’ve already talked here about why line 1 is good practice, but we’ve been “lazy” on line two and used “var” even though we have full knowledge that the return type will be System.Windows.Forms.DialogResult, and whats more that return type will never change as its part of the core .NET framework. Why is var useful in this context then? The better question is why actually would you “repeat” what you already know and specify later here anyway?

You and everybody else who is used to the System.Windows.Forms namespace knows the DialogResult type inside out. But what about people new to the toolkit, is the code still readable to them? I would argue that because we always specify the enumerable name on use, and the only purpose of the variable res is to be checked, specifying the type explicitly gains us nothing in readability, but does cost us more key presses.

I guess we can’t really say line 2 would “repeat yourself” in the same way as declaring a variable with both an explicit variable type and the new keyword on the same line, but we can say if we explicitly put the type on line 2 then we know we are planning to repeat ourselves on line 3, so here we are practicing Don’t Plan to Repeat Yourself to help us keep the DRY pricinple and keeping our code shorter by result.

If you’ve shed away from the var keyword yourself until now hopefully you are now inspired to give it a try and not just when your forced to using anon types and LINQ. You will find that when you follow the suggestions in this post your code will not only start to practice DRY but will actually increase in readability as the code you write become much more focused on the true dependencies and functionality of the method, and not the types your working with.