OOA/D with UML and OO Patterns – Intro

So, we’re going to do a new series on this – based on the exellent book “Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development”, by Craig Larman.

Unfortunately I only have the 2002 2nd edition (from my student days, don’t recall a thing…) but looking at the updates in the 2005 3rd edition I think we can work around this, especially seeing as we have access to the new chapters via InformIT’s excellent Safari Bookshelf.

The updates to look out for are:

  • UML 2

  • A second case study

  • More tips on iterative and evolutionary development combined with OOA/D

  • Rewritten with new learning aids and graphics for easier study

  • New college-educator teaching resources

  • Agile Modeling, Test-Driven Development, and refactoring

  • More on process modeling with UML activity diagrams

  • Guidance on applying the UP in a light, agile spirit, complementary with other iterative methods such as XP and Scrum

  • Applying the UML to documenting architectures

  • A new chapter on evolutionary requirements

  • Refinement of the use case chapters, using the very popular approach of [Cockburn01]


OOP: Interfaces in C#

This post is based on Chapter 9 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” available from Apress.

The main purpose of interfaces is to enable us to build types (i.e. classes) that support multiple behaviours. On a more general note they are also at the heart of many OO Design Patterns as they allow you to program to an interface in stead of an implementation – we will return to what that means later on, but just know that if you really want to do OO design, classic inheritance is only the most basic step, and interfaces are a crucial tool for moving on from here.

So, what is an interface? Well an interface defines a behaviour that a class may choose to implement (indeed the java syntax uses “implements” for this, where as C# uses the : also used for inheritance). You can only inherit from one class in the .NET family of languages (see http://en.wikipedia.org/wiki/Multiple_inheritance for some issues around multiple inheritance), but you can implement as many interfaces as you like.

So what is the difference between abstract classes and interfaces, and when should you use what? Well for one thing interfaces have absolutely no implementation – they are simply a description of a behaviour – it’s the implementing class’ job to… implement the actual behaviour, in whatever way it see fit. So I might have two interfaces which defines the following:

	public interface IEnjoyBeer
		void DrinkABeer();

	public interface IActLikeADrunkenLoon
		void DanceOnTheTableInYourPants();
		void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout();

Now we can then define a class that chooses to implement both these – and hence must supply an implementation of all the defined members:

	public class DrunkAsASkunk : IEnjoyBeer, IActLikeADrunkenLoon
		public void DrinkABeer() { Console.WriteLine("Drinking a beer"); }

		public void DanceOnTheTableInYourPants() { Console.WriteLine("Dancing on table in pants!"); }

		public void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout() { Console.WriteLine("Arguing Passionately"); }

In contrast to this, we could do the same with an abstract base class, but we would have to roll both behaviours into one class (no multipl. inherit), which will give you a hint of the limitations of classic inheritance. Note also that we use the virtual method in the base class here to provide a default implementation for drinking a beer:

	public abstract class DrinkLotsOfBeerAndActLikeADrunkenLoon
		public virtual void DrinkABeer() { Console.WriteLine("Drinking a beer"); }
		public abstract void DanceOnTheTableInYourPants();
		public abstract void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout();

	public class DrunkAsSkunk2 : DrinkLotsOfBeerAndActLikeADrunkenLoon
		public override void DanceOnTheTableInYourPants() { Console.WriteLine("Dancing on table in pants!"); }

		public override void ArguePassionatelyWithPeopleAboutThingsYouKnowNothingAbout() { Console.WriteLine("Arguing Passionately"); }

What great examples – no idea how this came to me… Anyways – let’s discuss some aspects of the two examples.

In the last example we have an abstract type that drinks beer and acts like a loon – which doesn’t really ring true, I see an endless number of these types being instantiated across town every weekend, so already we have a hint of a design flaw here. Another good question would be “what about people who enjoy beer without acting like drunken loons?” Or indeed people who act like drunken loons for other reasons than enjoying beer…

In contrast to this, let’s look at the first example using interfaces. So first off the IEnjoyBeer interface makes sense as a separate behaviour – because enjoying beer does not necessarily entail acting like a drunken loon – but, of course for some types it does, but the point is: you have the option to implement either one or both behaviours! You could also have a type that acted like a drunken loon but did not enjoy beer.  Either way – having options is important!

Note also that interfaces are available across class hierarchies – so where inheritance has this fairly rigid tree-like structure, interfaces on the other hand can be plugged in anywhere and at any level.

That is not an exhaustive discussion of interfaces – and we will return to these later when we look at the Strategy pattern in the up and coming OO Design Patterns series – but for now do note that we are not saying that you should use interfaces in stead of inheritance, the two actually compliment each other – we will cover this later, but what you should do is remove variable behaviour from your inheritance structure and instead place this in interfaces. The next step from this will then be moving the implementation of the behaviour (i.e. the interface) out of the specific class, and keep these in reusable classes whose sole purpose is to represent a behaviour. So we will have a more generic interface called IEnjoyADrink – and then a class EnjoyBeer that implements this – and then finally we would design a class called perhaps Person or FridayNightLoon who would implement a IEnjoyADrink implementation of it’s choice – anyways, we’ll return to this… keep reading!

Finally – don’t ever forget to use the Visual Studio Class Diagram tool – this is your new best friend in the world of OOP, just open a new diagram and drop in the types you want to see:


C# Glossary

From: http://msdn.microsoft.com/en-us/library/ms173231.aspx

access modifier
A keyword, such as private, protected, internal, or public, that restricts access to a type or type member. For more information, see Access Modifiers.

accessible member
A member that can be accessed by a given type. An accessible member for one type is not necessarily accessible to another type. For more information, see Access Modifiers and Friend Assemblies.

A method that sets or retrieves the value of a private data member value that is associated with a property. Read-write properties have get and set accessors. Properties that are read-only have only a get accessor. For more information, see Properties.

anonymous method
An anonymous method is a code block that is passed as a parameter to a delegate. For more information, see Anonymous Methods.

base class
A class that is inherited by another ‘derived’ class. For more information, see Inheritance.

call stack
The series of method calls leading from the beginning of the program to the statement currently being executed at run time.

A data type that describes an object. Classes contain both data, and the methods for acting on the data. For more information, see Classes.

A special method on a class or struct that initializes the objects of that type. For more information, see Constructors.

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. For more information, see Delegates.

derived class
A class that uses inheritance to gain, augment, or modify the behavior and data of another ‘base’ class. For more information, see Inheritance.

A special method on a class or struct that prepares the instance for destruction by the system. For more information, see Destructors.

A member of a class or struct that sends notifications of a change. For more information, see Events.

A data member of a class or struct that is accessed directly.

Generics allow you to define a class and or method that are defined with a type parameter. When client code instantiates the type, it specifies a particular type as an argument. For more information, see Generics.

Integrated Development Environment. The application that provides the unified user interface for the various development tools including the compiler, debugger, code editor, and designers.

immutable type
A type whose instance data, fields and properties, does not change after the instance is created. Most value types are immutable.

inaccessible member
A member that cannot be accessed by a given type. An inaccessible member for one type is not necessarily inaccessible to another type. For more information, see Access Modifiers.

C# supports inheritance, so a class that derives from another class, known as the base class, inherits the same methods and properties. Inheritance involves base classes and derived classes. For more information, see Inheritance.

A type that contains only the signatures of public methods, events, and delegates. An object that inherits the interface must implement all of the methods and events defined in the interface. Classes or structs may inherit any number of interfaces. For more information, see Interfaces

An iterator is a method that enables consumers of a class that contains a collection or array to use foreach, in (C# Reference) to iterate through that collection or array.

A field, property, method, or event declared on a class or struct.

A named code block that provides behavior for a class or struct.

mutable type
A type whose instance data, fields and properties, can be changed after the instance is created. Most Reference Types are mutable.

nested type
A type declared within the declaration of another type.

An instance of a class. An object exists in memory, and has data and methods that act on the data. For more information, see Objects, Classes, and Structs.

A data member accessed by means of an accessor. For more information, see Properties.

Reusing previously entered code. The Visual C# Express Code Editor can intelligently reformat code to, for example, turn a block of highlight code into a method. For more information, see Refactoring.

reference type
A data type. A variable declared as a reference type points to a location where data is stored. For more information, see Reference Types.

A class or method declared as static exists without first being instantiated using the keyword new. Main() is a static method. For more information, see Static Classes and Static Class Members.

A compound data type that is typically used to contain a few variables that have some logical relationship. Structs can also contain methods and events. Structs do not support inheritance but they do support interfaces. A struct is a value type, while a class is a reference type. For more information, see Structs.

value type
A value type is a data type that is allocated on the stack, as opposed to a reference type which is allocated on the heap. The built-In types, including the numeric types as well as the struct type and the nullable type, are all value types. The class type and string type are reference types. For more information, see Value Types (C# Reference).

OOP: Encapsulation in C#

This post is based on Chapter 5 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” availble from Apress.

So the main aim of encapsulation is to keep things simple and manage the intricasies of an objects task within that object. We want to be able to tell and object to do something, and not have to worry about how it does it. This principle is used extensively throughout the .NET framework, for example when you tell a GridView to DataBind() or you tell a file to Load from a specific path – there is obviously lots going on below the hood, but we don’t have to worry about this, we just read the method description, supply the required data and happily carry on with whatever we are doing.

A second benifit of encapsulation is that we are free to change how a certain task is accomplished within the class or struct, without having to worry about any external code (as long as we maintain our parameters and return type of course).

So what are the building blocks for this? Well first and foremostly this is really a pattern or a practise that you have to aim for in your coding and system designs. I will be writing about OO Design Patterns later in this blog, but basically we are looking at responsiblity and maintaining this within the most relevant class. Taking the above example, it makes sense that all the details about loading a file from disk into memory is encapsulted within the File class.

Access Modifiers

One of the main tools you will use when designing encapsulation are type member access modifiers – so that is keywords used to restrict access to fields, properties, methods, or events declared on a class or struct (as we’re including struct here we will refer to “type members” as opposed to “class members”).

To quickly run through the access modifiers we have:

  • public: no access restrictions here – all classes and even external assemblies can access public class members.
  • private: this is the default for class and struct (type) members. These members can only be accessed from within the owning type.
  • protected: the defining type and any inheriting classes (remember structs do not allow inheritance) can access protected members.
    Using protected methods and fields implies a certain level of trust between the parent and the inheriting class. This is not neccesarily a problem, but some thing you should be aware of. If you want to protect certain data by business rules in the base class, it’s possible to define private fields, with protected get or set methods.  Also you can use the internal keyword to extend this principle at the assembly level.
  • internal: these are in a sense public – but only within the defining assembly.
  • protected internal: this simply combines protected and interal – of course it is possible to inherit from a class defined in another (referenced) assembly – this allows you to stop such inheriting classes from accessing your member(s).

The default access modifiers (if not defined) are private for type members and internal for types.

Desgining Encapsulated Classes (and structs)

First thing you want to do is wrap all accessible members in properties. This allows you to control how these are accessed and perform any validation or cleaning logic you need before anything is done to your class members. Note that in the Intermidiate Language code generated all properties are represented as get_[property_name] and set_[property_name]. Not sure what you will do with that information, but it might come in handy some day I guess.

Note that it is also possible to define properties with a different modifier on the get and set method respectively, basically you override the overall property access modifier within the property just before the get or set block:

	private string _someString;
	public string SomeProperty
			return _someString;

		protected set
			_someString = value;

Also note that you can have static properties. These of course work at the class level, and can be used in a similar way to static constructors to set members that apply globally to all existing and subsequent instances of the type.

Finally – you might want to have a look at the new auto implemented properties in .NET 3.5 – these basically just allow you to skip the trivial get/set blocks and just write empty statements as in the below example. Behind the scenes these are of course implemented in the same way in the CIL – and we end up with our get_ and set_ property members.

	public string AnotherProperty { get; set; }

OOP: Classic Inheritance and Polymorphism in C#

This post is based on Chapter 5+6 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” available from Apress.

Note: for interfaces see a later article covering chapter 9.


Aa mentioned in a previous post, we have two general OOP methods of code reuse, the is-a and has-a relationship between objects. In the following let’s look into the is-a, or inheritance relationship a bit more.

So the basics here is that you define base classes, and any protected members are inherited in an deriving classes. Note that C# does not allow multiple inheritance – but, it does allow classes and structs to implement multiple interfaces, which means that you really have no need for multiple inheritance. More on this later on.

Sometimes you might find that you want to stop all futher inheritance from a certain class (this is often applicable to utility classes where inheritance is senseless) – in such cases you can (and I guess it’s recommended that you do) use the sealed keyword, like this:

	public sealed class EmailUtilities
	{ }

Note also that structs are sealed by definition (implicitly).

Constructors in Inheriting Classes

By default, the base class default constructor will be executed before any logic in your inheriting class’ constructor. Note that if you have a base class with a constructor that takes say three arguments, and you inherit from this class, your derived class will not by default have access to this constructor.
Because of this it is good practice (and will often make a lot of sense) to use the base keyword to forward arguments onto the base constructor. So you will do stuff like this:

	public class DerivedClass : BaseClass
		public DerivedClass(string str, int x) : base(str, x)
			//Code here will execute AFTER the base class constructor logic


This is the black art of exposing one object from another, also known as a “has-a” relationship, as opposed to the “is-a” that we know (and love) from classic inheritance.

So what’s the point? Well, there is a lot of point to it. Once you get into designing your own class hierarchies (and do btw make sure you use the VS visual class designer tool for this, but always make sure you understand the generated code as well) you will find that it makes a lot of sense. Orders have OrderLines, Employees have Addresses etc etc. Really this is a very important part of OOP implementation, but it’s also one that you will find quite logical.

However, one important question is how do you actually do this in the best and most consistent way? Do you simply expose the entire object – or do you write local methods that utilise the object behind the scenes? So, for example, say we have an Employee and let’s just for the sake of illustration say that an Employee can only have one Address object. Should we then write a method called UpdateEmployeeUpdate in the Employee class – and within this update and save the contained Address object – or, should we place an UpdateAddress method on the Address object, and simply expose the Address object directly as a property of the Employee…?

The answer is: It’s up to you!! But fret not, or at least don’t fret completely, we will revisit this later in the upcoming OO Design Patterns series. For now, know and understand that we are once more looking at responsibility – and personally I like placing this as close to home as possible, so in the above I would indeed place this at the Address and never write any logic in the Employee that deals directly with updating address details.

Yet another alternative, a kinda soft middle ground, is to expose the UpdateEmployeeAddress method, but simply pass the params straight through to the Address object – however this to me just muddles the waters, and makes it unclear who is responsible for what.

Anyways – as I said we will return to these happy deliberations, for now, let’s focus on the mechanics – let’s look at the possible, not the advisable, if I may be so lyric (bloody late here I’m telling ya, falling asleep as a I type).

Yet another option for the has-a relationship is nested types. This is types defined within another type, so for example a class within a class or an enum or struct within a class.

Some implications of this:

  • You can declare these as private – and hence limit the access to the containing class.
  • The nested class is a member of the containing class, and as such has access to all members (incl private) of the parent class.
  • The nesting can be as deep (i.e. as many levels) as you require.

So this is not inheritance, but clearly a has-a, that gives you some interestin options. Generally, you will use this to define utility classes that are only used by the containing class. If this is not what you need, you should as a rule define an independant class and implement your has-a relationship using one of the aforementioned techniques.


So as mentioned in a previous post Polymorphism is a process that allows us to treat a bunch of related object in a consistent manner – effectively delegating the responsibility for implementing the requested action into each respective class definition (so really we are looking at another layer of encapsulation).
So an (overused) example could be the abstract concept of an Employee which forms the basis for an inheritance tree of different types of Employees – each of which you can tell to CalculateHoliday(); because the Employee object stipulates that all inheriting classes are able to handle this method.

So, how does the Employee class achieve this? Well – there are two options, the Employee class can either define CalculateHoliday() as an abstract method or a virtual method.
Virtual methods are basically a default behaviour, which inheriting classes are free to override (using just that keyword). In contrast an abstract method is just an empty method definition, which inheriting methods are required to override. Note that a class must be defined as abstract in order to contain abstract methods or properties – but that an abstract class can contain both abstract, virtual and “normal” members.

So, basically you would use abstract classes for concept that are too …well, abstract for it to make any sense to ever instantiate an object of this type. For example you might have a type called Product. Now, while there are a list of methods and properties that we can imagine all products should have, it generally speaking does not make sense to work with a Product object.

So, to recap – we can give Product some protected or public properties that will be applied to all kinds of Products via classic inheritance, we can have some virtual methods or properties that provide a default implementation of a certain functionality, but can be overridden in inheriting classes – and finally we can define some abstract methodsor properties, which have no implementation and must be overriden in inheriting classes.

When overriding virtual or abstract members, note that you can use the base keyword to call the base method you are overriding, and that you should always do this if you are reusing the logic from here (so if you are extending and not replacing – as will often be the case).

Also, make sure you use VS200x nice little shortcuts for this type of thing, just type override, and you will see a list of possible members , select one and hit enter, and your method stub is there.

Note also that you can seal a virtual method at any level in the inheritance chain by using of course the sealed keyword – so you mark the method as “override sealed” – and this means that thie method cannot be overridden again further down the inheritance chain (so your sealed override becomes the final implementation of that method).

A “polymorphic interface” refers to all the abstract and virtual methods and properties of an abstract class.

Member Shadowing

A not really related, but kinda similar topic – is member shadowing. This is when a derived class defines a member that is identical (by name and signature) to an inherited member. This is not illegal, but will give you a compiler warning, which should give you a clue that it’s not best practise.
However, you might sometimes want to do this intentionally. Say if for instance you are inheriting from a 3rd party assembly (or any other “no code access” scenario) – and you want to change some behaviour, you can then hide the inherited member like this – and use the new keyword to get rid of your compiler warning. So basically just define your member (be it field, property or method) with the new keyword in front the definition.

Casting Object

So a few notes on casting, which you will find yourself using a lot when working with polymorphic class hierarchies.

First of all, it’s always safe to cast downwards, and you can work with this anyway you want. However if you are casting upwards (so you have a derived class object in a base class type reference) you must do this explicitly using the (type) method.

Note that you can also use the is keyword to check for types – but really, this would be indicative of some missed polymorphic opportunity (you can imagine some nightmarish if/else statement doing different things depending on the actual type).

If you need to do type checking, always try and use the as keyword, this returns null if the case was not successful and allows you to use a simple if(myRef != null) check afterwards (it’s the best casting practise – use it!).

The Pillars of Object Oriented Programming (POOP)

This post is based on Chapter 5 of Andrew Troelsen’s “Pro C# 2008 and the .Net Platform” availble from Apress.

These are of course Encaptulation, Inheritance and Polymorphism.

So we Encapsulate logic within object to allows us to do wonderful things like MyObject.GoAndDoSomethingComplicatedWithoutTellingMeAllTheBoringDetails();

We Inherit to promote code reuse – so we define common properties and functionality in a base class. Another form of code reuse is the “has-a” relationship (as opposed to the “is-a” we get from inheritance.

And finally, we Polymorph when we have a load of related objects and we want them to do something – each in their own specific way. One example that springs to mind is the ASP.NET webcontrols that are all asked to render themselves as the control tree structure is parsed during the page render process. Here, we do not care whether we are dealing with a RadioButton, a Label or indeed a GridView – we just know that they are all WebControls and that they contain and handle the Render(HtmlTextWriter writer); method.
The question is then of course – how do we know that…?