Design patterns are not just for architects. In fact, you already use Design Patterns but probably don’t know it. Observer, Proxy, Facade - these are patterns that allow us to better communicate our ideas with other developers. And once we understand the patterns, we can use solutions that people way smarter than us have already implemented.

In this session, Jeremy Clark takes a look at several Gang of Four patterns that we regularly use without realizing it. Don’t know who the Gang of Four is? Watch the webinar to find out.

Watch the webinar and learn:

  • What design patterns are (and what they are not)
  • How design patterns offer solutions to common problems
  • How we already use many design patterns, including Observer, Proxy, and Facade
  • How our modern languages support design patterns

Design Patterns: Not Just for Architects on Vimeo.

Download code samples.

Video Content

  1.  What Are Design Patterns? (3:33)
  2.  The Gang Of Four Book (5:29)
  3.  Anatomy of a Design Pattern (7:09)
  4.  The Gang of Four Patterns and Categories (10:31)
  5.  The Book Head First Design Patterns (12:49)
  6.  Why Care about Design Patterns? (15:33)
  7.  Observer Pattern (20:28)
  8.  Proxy Pattern (31:18)
  9.  Facade Pattern (40:39)
  10.  Summary (47:42)
  11.  Q&A (49:39)

Webinar Transcript



Hello everyone and welcome to today's webinar, Design Patterns Not Just for Architects. My name is Alex and I'll be your moderator. I work as a software developer here at PostSharp. I'm excited to be hosting this session today. I'm pleased to introduce today's speaker, Jeremy Clark. Jeremy is Microsoft MVP for .NET and a Pluralsight author. Today, he's going to show you how modern languages support design patterns.

Before I hand the mic over to Jeremy, I have a few housekeeping items to cover about this presentation. First of all, this webinar is brought to you by PostSharp. PostSharp is an extension that adds support patterns to C# and VB. If you're tired of repeating yourself in your code, you may want to check it out as did folks in Microsoft, Intel, Bank of America who have been using PostSharp who have been using PostSharp in their projects development and maintenance time.

Customers typically cut down their code base by 15% by using our product. So, feel free to visit our website,, for more details and to get a free trial. Next, today's webinar is being recorded and the recording will available after the live session. You'll receive an email with the recording link.

The last thing is we'd love to hear from you during today's presentation. So, please if you have a question for our speaker, feel free to send it through question window at the bottom of your player. We'll be answering the questions at the end of the session. If we don't get to your question, we'll be sure to follow up later afterwards. Without any other further ado, I'd like to kick things off by welcoming Jeremy Clark. Jeremy, now it's over to you.


Thanks, Alex. Today, I am going to talk about design patterns. The reason for this is I always thought that designs patterns were one of those things that were just for architects, but I found out that they're extremely useful to everyday developers as well. My eye opening experience was when I was working at corporate developer, I worked on a really awesome team.

The developer who sat next to me, he had 10 years of experience on me as far as being in the industry. One day he just pops up out of his desk and he's really excited. He says, "I've been using the facade pattern without even realizing it." I thought well, that's kind of cool but it's also a problem because that means that we've been using something accidentally rather than using it intentionally.

What I found is that, in looking at patterns, once I start to recognize the problems that they're trying to solve, now I can associate that with the design pattern, it leads me to a solution that I can look up implementations online and I can create my own implementations if that makes sense. That's really why I started getting into the design patterns world.

Now as Alex mentioned, I am a Pluralsight author and if you do want to dig into the topic a little more, I do have a course on Pluralsight called Design Patterns On-Ramp. It talks about some of the things I'll be talking about today, but it's also about three and a half hours long. So, there's a lot more material than I have time to cover.

If you're not familiar with Pluralsight, really awesome online training. If you learn well by video, I would highly, highly recommend it. I'll have a link to this at the end of the slides as well. But with that said, let's go ahead and get started talking about design patterns themselves.

What Are Design Patterns?

Now, I really hate putting big blocks of text up on the screen, but in this case, this is the definition that has entered our industry as far as what design patterns are. Each pattern describes a problem that occurs over and over again in our environment and as programmers we should recognize that.

There's times where I need to get notified when a state changes. There's times where I have to be able to create three different objects and inject parameters into them. There's times where I might say, you know what, I need to pass the message along between different objects. These are problems that occur over and over in our environment.

Now design patterns, after they describe the problem, they then describe the core of the solution to the problem. So, design patterns aren't actually telling us here is the code you need to write. They're saying here's the ideas behind it and it's actually up to us to implement that idea. In fact, if we continue with this definition, they describe the core of the solution to the problem in such a way that you can use the solution a million times over without ever doing it the same way twice.

Now, obviously that's not something we would normally recommend because we don't want to reinvent the wheel, but there are different kinds of wheels that you can choose from. Now, the really interesting thing about this particular definition that comes from Christopher Alexander is that it has absolutely nothing to do with software. Christopher Alexander was actually talking about architecture, like real architecture with buildings, and bridges and things like that. Now, it turns out that this definition did apply very well to the software environment and so that's why we picked up on it.

The Gang of Four 

Now, there were some, I would say, really smart people who thought about this and they created this book, which you might have heard of. It's that infamous Design Patterns book, Elements of Reusable Object-Oriented Software. If you've ever heard the term Gang of Four, this is what we're talking about. This is the Gang of Four book. Usually we call it that because it was written by four different authors and it's easier to say Gang of Four than try to list out all their names.

The Gang of Four book is one of those books that every developer has to have on their shelf because it makes you look really, really smart. The problem with the book is it's pretty academic and so it's a little bit difficult to read. So, you might say, "I don't know about this. Are design patterns important?" The answer is yes they are, definitely. This particular book described 23 patterns.

The reason why this became so important in our industry is because this was the first design pattern catalog. Now there's way more than 23 patterns now. There's hundreds and probably thousands of them out there, but this was again the starting point. This book was written way, way back in 1994. If you think about that, it's like what is that in computer years? That would be like 300 computer years. So, we start to question, are they still relevant? Again, the answer is yes and we'll see why as we go along today.

Anatomy of a Design Pattern

Now the Gang of Four, since they were kind of the first ones doing this, they were able to describe what does a pattern actually consist of. There's four basic elements and this again is something that has moved on to other pattern descriptions through the years.

The first one is the pattern name. So, this is a unique way of referring to the pattern. Hopefully, it's something that describes either what the pattern does or the problem it's trying to solve. It also is not something that would be ambiguous in our industry. Now since the Gang of Four were kind of the first ones out there, they got to pick some pretty simple names, things like bridge and observer and adaptor.

The patterns that are coming up after that, a lot of times we have to have a little bit longer names to keep them unambiguous. So, we end up with cool names like MVC, Model–view–controller or MVVM, Model–view–viewmodel, or IOC, Inversion of Control. A lot of times the pattern names that have come after that had to have been a little bit more descriptive just because all of the easy names were taken.

In addition to the pattern name, obviously the pattern has to describe the problem that it's trying to solve. Again, this is that thing that occurs over and over again in our environment. We'll be looking at some examples of this as we go along.

The third thing is the solution to the problem. Again, this is the core of that solution. It doesn't give a specific implementation. Now it turns out that most pattern catalogs will provide some code for us to look at because of course we're programmers and it's easy for us to think in code, but we don't want to think about that as the only way to implement the pattern.

What's more important is that we're staying true to the spirit of the pattern and the different parts that are described. How we actually implement it, it's up to us. Now definitely, we should use solutions that are already out there if they fit in our environment. But if our environment is a little bit different, it is okay to create your own solution to one of these problems.

Now the last thing that's part of the design pattern is something people don't like to talk about much and that's the consequences. Usually when we're having those day-to-day conversations, someone might come up and say, "Well, I was using the factory method pattern here and it was brilliant. It did all these awesome things that I needed exactly right for my code." But just like all of our other tools, our design patterns have both pros and cons. They have the solution to a particular problem but usually, there are some consequences that come along with that.

Now those consequences aren't usually showstoppers. They're not things that say, "Oh, I better not use this pattern because it's got this huge problem." Usually, they're just things that we need to keep in mind when we do implement the pattern so that we don't get ourselves into trouble. Again, we'll see some of that as we look at some examples today.

The Gang of Four Patterns and Categories

Now I mentioned that the Gang of Four described 23 design patterns and here they are. We'll be specifically looking at three of these patterns today because actually again, like I mentioned, as a developer I have used a bunch of these patterns just accidentally. So, we'll just picking out three of them specifically to see how we've been using them.

Now, the Gang of Four actually put these into categories. So, there's actually a set of patterns that are known as the Creational Patterns. These have to do with how do we instantiate an object or how do we get our objects into our application itself.

Then there's also a set of Structural Patterns. These have more to do with how do our pieces fit together? We've got these different pieces and can we put them together in different ways or somehow figure out different ways to present our objects in a way that makes sense?


Then the third category is the Behavioral Patterns. This just describes how our objects might behave in certain instances. Again, these are all designed to give a solution to a certain problem in our environment that occurs over and over again.

Like I mentioned, the Gang of Four book, it's really, really important. I would encourage you to read it at some point in your career, but I would not use that as a starting point. Like I said, the reason for that it is rather academic. If you're a hardcore computer scientist, you might really love it. But if you're just a developer who's just trying to get code out the door to make your users happy, it might be a little tough to read.

My copy is actually from 2008. That's when I got my copy and put it on the shelf to make me look really smart. I actually tried three different times to get through the book and it turned out, I just wasn't ready for it yet in my career. Now, when I did get through it again, it was really important. It's been extremely useful to me since then, but it is kind of hard to get started. 

The Book Head First Design Patterns

Now, if you're brand new to design patterns, I would highly, highly recommend this book, Head First Design Patterns from O'Reilly.

Now, the reason I give book recommendation is because that's how I learn best. I love books. I absorb books. They are really helpful to me. So if you're not a book person, there's lots of other resources out there, but this one is excellent. The thing that I like about this is that it actually covers 12 of the Gang of Four patterns. So, it takes 12 of those 23 patterns and it actually starts with the Gang of Four description itself.

It's not like it's trying to come up with something new. It's not trying to describe some new idea of what patterns are. It's just taking the Gang of Four patterns and describing them in a way that's a little bit easier to absorb. The Head First Design Patterns, the Head First series is all about how do we get information into your head in a way that we can understand. So, it's an excellent, excellent resource for that.


By the way, I remember it has also samples and I think all the samples are in Java language. Is that correct?


Yes, that is correct. All of the samples are in Java in this book. It actually mentions it in the introduction that if you're a C# programmer or another curly-brace language programmer, you'll have no trouble following along and that was actually my experience. But if you are specifically saying, "You know what, C# examples would be way, way better for me," there's tons of people who have created these samples in different languages online. So you will be able to find these examples in C# if that's what you really need.


Okay. Thanks.


Yeah. In fact, really the only thing that I ran into in this particular book is they had one that was specifically oriented towards JavaBeans. That's a little more specifically to the Java environment, but understanding the concepts was not difficult.


Right. Okay. Okay, cool.


I've told you here's what patterns are and I've showed you a book that I've told you not to read yet. I've showed you another book that says, "Hey, this is a good place to start." But again, if these things happened way back and started in 1994, aren't they relevant? Do they still matter to me? 

Why Care about Design Patterns?

Why should I care about these as a developer? The answer to that is there're several reasons. Again, these are things that have seen in my own career and why I just love talking about design patterns.

The first one is that these are well described solutions. People way smarter than me have been thinking about this for a long, long time. So, rather than having to come up with my own solutions to the problem, I can rely on somebody else who's already thought about it. Again, there's a lot of implementations out there as well.

The other thing is that this gives us a shared vocabulary as developers. Now pretty much every industry has its own secret language. So doctors and lawyers have all their own secret words that normal people don't understand. This is actually the secret language of developers. So we can talk in the hallway and say, well yeah. I've got a facade over here and a mediator over there. It's like talking in code.

Now, I like to think about it that way, but it's actually more useful than that because it gives us a very concise language that we can use to speak to each other. It's not just a secret code. For example, I could come up to you and say, "Well I have this one object. When it changes state, it actually sends out a notification and I have this other object that's subscribed to that. So, it receives a notification whenever the state changes," or I can say, "I'm using an observer here."

A lot of times when we're talking to other developers, maybe we're trying to work through a problem, it's not usually specific lines of code that we're having problems with. It's usually that we're having problems with the bigger concepts and how they fit together. So if I can say that I'm using an observer rather than describing a particular implementation, now I can have that conversation stay in that design area that I want it to be in. Something that I love in my world, because of that language is that it does let me stay in design mode longer.

I'm one of those people who just loves the whiteboard. I don't do heavy, heavy design upfront, but I like to know where my code is going. So, here's the big pieces. Here's how they fit together. I had an awesome manager when I was working at this particular corporate job because whenever she would walk by my desk and I would have my feet up on the desk and I was just staring at the whiteboard not doing anything else, she knew I was working because as a developer, my job isn't really to type as much code as I can. My job is to actually solve problems.

So, there's a lot of thought that goes into that. Again, patterns let me figure out how do these big pieces fit together, how do we make them work, and how can I get this into my particular application and make my users happy because in my world, it's all about making my users happy. If I'm not making their lives easier, then I'm completely failing in what I do.

The last benefit when we start using design patterns in our every day speech is that it will hopefully encourage other developers to look into them as well. So, if you're having a hallway conversation and you're like, "You know what, I was using the mediator here. It was a perfect thing for this particular problem that I had and here's the implementation I used and it actually solved the problem." If there's another developer that's overhearing that conversation, they might say, "I'm not sure what the mediator pattern is, but maybe I should look into that."

It just will spread the use of this design pattern language just through our industry as new developers join all the time. That's a huge part of it because our industry is doubling in size every five years. That means that half of all developers out there have less than five years experience. If you're a senior dev like me who's been in the industry for a while, it's great to think about all the new people who are joining and how do we get them up on board and get them to a great productive place like I have been for a while?

This is what design patterns are and why we should care about them, but really where I want to spend the rest of the time is looking at how we as developers are already using these patterns even though we don't realize it. I'm going to look at three of the Gang of Four patterns. We'll see, you know what, how we're using this and once we recognize it now, we can use it more intentionally.

Observer Pattern

The first pattern we have is the observer pattern. Like I mentioned, the Gang of Four descriptions can be ... They're not difficult to read, but you do have to stare at them for a little while. Here's the Gang of Four description of the observer pattern. "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Do you know what that means? All it means is a publish–subscribe relationship. That's what the observer is. It's describing a publish–subscribe relationship. As an example in the real world I'm going to point to everybody's favorite time waster which is Twitter and in particular, the follow functionality in Twitter. If you follow me on Twitter, you actually become an observer of me. When I change state, meaning I publish a new tweet, you're automatically notified of that. That's all it is. The observer pattern is simply a publish–subscribe relationship.

Let's go to some code and see how we actually use this in our day-to-day coding practices. The code is all available on GitHub. I'll have a link on the last slide so you can go download that. If you look at the solution that I have here, it has a set of five different projects that describe different patterns. Like I said, we have time to look at three of these today. If you want to get some bonus content, you can download the code and take a look through it.

I'm going to start out by looking at the observer pattern. Now, before I write any code, I want to run this application because I want to show you my amazing UI development skills. I'll give you a second to take that in because I know it's a little overwhelming. What we have here is a button which doesn't do anything when we click on it. There's a couple of text blocks on there that don't have any content at the moment. Well let's go ahead and fill in some code and we'll see how implementing an event handler is really an example of the observer pattern.

I'm just going to go to the code behind my form and rather than hooking up the event handlers using the designer, with the properties, we'll do it in code. My button is called ClickMeButton. So I just have to say ClickMeButton.Click. Then I say plus equals, and Visual Studio says, "Hey, it looks like you're trying to hook up an event handler. Would you like me to create that? If so press tab." Yes please. "Do you want to call it this?" No. Let's go ahead and call this observer one and hit enter.

I just love things that do this for me. Visual Studio has awesome, awesome stuff built into it. Now, in this case, I just don't want to hook up one observer. I want to hook up three. I'm just going to duplicate some code here. We'll have an observer two and observer three and we'll just copy this method down. I've got an observer two and observer three.

Now in this observer one code, I'm just going to set the TextBlock1.Text to hello from Observer1. Down here in the second one, I'll set TextBlock2.Text to hello from Observer2. Then way down here at the bottom, we'll switch things up a bit and we'll do a MessageBox.Show and we'll say hello from Observer3.

Now hopefully none of you are baffled by this code, and that's really the point because what we're looking at is we're looking at things that we do all the time. When I run this application, hopefully there are no surprises. If there are some surprises, then I'm going to get a little depressed about my programming abilities, but when I click on the button, oh look at that. Our two text blocks built in and we also got the message box popup.

But we've also used an implementation of the observer pattern. We have actually set up a publish–subscribe relationship. In this case, the state that we're subscribing to is the click state of the button. Whenever the click state of the button changes, all of my methods in this case get notified, "Hey, this has changed. Go ahead and run your code." That's really all there is to implementing the observer pattern.

Now what's interesting about this is that there are a lot of different ways that we can do this. Since it's no longer 1994, our languages and frameworks actually implement a lot of these patterns for us so that we don't have to worry about it. For example, if we're talking about the observer specifically in the C# world, obviously event handlers are out there and hooking up an event handler is one of the first things that we learn as developers. You do that hello world with your first form application and you click the button and there you go.

Creating an event handler is not all that much more difficult than that. So, it's something that developers can do really, really easily. But the thing is we might look at our problem and say, "You know what, an event handler isn't the right solution for this. I know it's built in and it's there. If it works, great. I don't have to write any extra code. But if it doesn't fit our scenario, we can look elsewhere."

There's something called an event aggregator. I first ran across this concept with the Prism framework. Prism is a framework that's designed to work in the XAML world. There's this concept of event aggregator. When you use this, the publishers and the subscribers don't have to know anything about each other. That's a benefit because I can have publishers and subscribers completely separated.

So, all each object needs to know about is the centralized event aggregator. So an observer, a subscriber, all they have to do is hook up to the event aggregator and say, "Hey, please notify me if this particular event happens." In fact, you might even say, "You know what, notify me if this event happens and it has this particular value in the payload." It can get kind of interesting with what you do with that.

On the publishing side, again the publisher goes to the event aggregator and says, "Hey, I would like to publish this event please and here's the payload that you should use for that." Again, the publishers and subscribers don't have to have any direct connection.

Now you might also say, "You know what, that doesn't work for me either." Well, starting in .NET 4.0, we got two new interfaces, IObservable<T> and IObserver<T>. These are just shells. They're frameworks that we can use to fill in our own methods that says, "You know what, here are some ethics that you can use to implement your own custom observer." You might even say, "You know what, this doesn't work for me either."

That's the thing about design patterns. We're not locked into a particular implementation, but once we recognize the problem and I say, "You know what, I have this publish-subscribe problem. What do I do?" Well, I can say, "You know what, event handlers are built in. Will that work for me?" That way, we don't spend time spinning our wheels coming up with custom code when we can go look for solutions online or inside our own frameworks themselves.


Okay. I was just wondering are there any consequences of observer pattern because we just looked at the implementations, but usually there should some consequences or maybe some downsides or?


Yes. There are always consequences. Again, with every tool that we have, there's consequences. Let's just go back and look at our code and see if we can think about what those consequences would be in this case. When I'm using the Observer pattern, something to think about is I might never get notified at all.

So, it's possible, let's just rerun this application, that I have this application and nobody ever clicks the button. Now for our simple example, that's not really a big deal, but let's say we were creating a stock ticker application that was getting communication from some service that was providing us with values of different companies.

Well if we never get that first notification, well what are we going to do? Well, we might decide we put in the default message or something like that or we might have something that says, "Hey, we haven't received any data yet just to let the user know what's going on." Again, it doesn't stop us from using the pattern, but it's something to keep in mind.

Another thing specifically with the observer is that we don't know how frequently we're going to get notified. I might get notified once an hour. I might get notified a million times a second. I don't know. Now in our particular application, we kind of have a limiting factor because our message box is a modal dialog so we have limited how quickly we can handle things in this particular application, but again it's something to keep in mind.

Then the other thing is that we don't know how frequently we'll be notified. Did I say frequently or often? They're so related. I might get notified one time or I might get notified a million times. Regardless of the total numbers of notifications I get or how close together they are or how spread out they are, those are things that we think about with the observer.

Alex: Okay.


It would be nice if things came for free. But then again if we didn't have to judge the pros and cons of each of our tools, they wouldn't pay us the enormous amounts of money that they do to be programmers. I hope everybody is paid enormous amounts of money. That's the observer pattern. Again, it doesn't have to be complicated. Now obviously the situation that I showed was pretty simple, but it's something that we can think about in the future. "Hey, I've got publish-subscribe. What do I do about it?"

Proxy Pattern

The next pattern I want to look at is the proxy pattern. Here's the Gang of Four definition, "Provide a surrogate or a placeholder for another object to control access to it." Now for this, I'm going to use a legal concept from the U.S. which is where I live, and it's called power of attorney. My brother actually lives in Bamako in Mali, West Africa. I live in California on the West Coast of the United States. Now, he has assigned me power of attorney, which really makes me his proxy.

What that means is let's say someone wants to do business with my brother. Now, they could figure out well okay, how do I get this papers over to my brother in West Africa to sign. Unfortunately, U.S. has some kind of archaic laws. Like a fax signature is legal. So. it's like okay, well let's fax them over and he can sign them and fax them back. Of course, the first thing you have to do is find a time machine so you can go back to 1996 to fax something. But another option is that this person could have me sign the documents as my brother's proxy. That in the U.S. is exactly the same as if my brother had signed those documents himself.

As his proxy, I can work on his behalf, and to the individual interacting with us, interacting with me is exactly the same as interacting with my brother who is 6,000 miles away from where I live. That's actually a pretty common implementation when we're talking about the proxy pattern in code. A lot of times we're dealing with a network resource.

In this case, I want to show an example of working with SOAP services. Now, I know SOAP services have gotten a bad wrap recently because people are like, "Oh, REST is the trendy thing to do. You should be doing that. SOAP is archaic. You should never use that. REST is the replacement for SOAP." To that, I say, no. Both REST and SOAP have their pros and cons just like all of our tools. I love that we have more tools in the toolbox, but let's see which ones are great for certain things and which ones are great for other things. Rather than replacing my tools, I just want to make my toolbox bigger.

Now in the case of SOAP services, what's awesome about this is they're self-describing. What that means is that my development environment, in this case Visual Studio, can actually create a proxy object for me. If you've used a SOAP service in .NET, you've actually used an implementation of the proxy pattern.

Let's take a look at the service that I have. You can see it's really exciting. It just has one method called GetPeople and it returns a list of person objects. If we just peek at this, we'll see that the person class is pretty simple. It's just the first name, the last name, a start date, and a rating. That's just the shape of our data. Then in this case, I just have a hard coded collection of objects that it's returning. So, I'm not even going to database or anything like that. This will provide us with the data that we can use in our UI.

Now before we look at the UI code, let me just go ahead and run this application because again I want to you to be amazed with my UI skills. This time with have a button and a list box. Yes, I know we're moving up in the world. Again, the button isn't doing anything at this point in time. Now the advantage of using the WCF SOAP service is that I can have Visual Studio generate a service reference for me, which is really creating a proxy object.

For this, I just right click. Inside the project where I want to use the service, I say add service reference. In this case, I can click the discover button and that will find all of the services that are in my solution. I can say, "Oh yeah. Here's this one here. Is this the one I want?" Yes. It has that GetPeople method in it. I can just fill in the rest of this and click okay and it will stab out all of the things that I need. Now I have already done that in this project, so I won't do it again but let's see how we actually use this in the code.

Again, we'll go ahead and go to the code behind of our form. Again, this is just the form that has the button and the list box on it. Now, all I need to do is new up an instance of this proxy object that Visual Studio created for me. So I'll say var proxy = new PersonServiceClient. That's just the name Visual Studio gave to my proxy class. Then if I say proxy., you'll notice that I have a GetPeople method exactly like I have on the service object.

When I look at this, I see this returns a list of person objects. Okay. List<Person> people = proxy.GetPeople. That looks like I need a using statement for bringing in the collection. Then all I need to do is get this into my list box. Well in this case, I have something called a PersonListBox that I can just say it's ItemSource equal to what's coming back from this. When I do this and run my application, again hopefully there's no surprises, we click on the button and we'll see that our list box actually populates.

Now, that's not very impressive because this code looks pretty normal to me. But the thing is once we start thinking about what's going on behind the scenes, now this becomes more important because if I want to call a SOAP service, what actually has to take place? Well, first of all, SOAP is XML based. To create a SOAP request, I have to make this big ball of XML in a specified format. Then I have to send that SOAP request across the wire usually by HTTP. Then I have to wait for a response to come back. Then I have to retrieve the response, which again will also be by HTTP.

Then I have to parse the response that comes back because it's actually a SOAP response which is a big ball of XML. Then I have to take the things out of that that I need and turn them into C# objects that I can actually use in my code. This is what I have to do with a SOAP service, or I can use the proxy class that my IDE generates for me.

Let's take a look at the service itself. Again, this just has a single method. Let's pretend this wasn't a service. What if we were just using this directly. How would I use it? Well, I would new up an instance of this person service class. So new person service and then I would call Service.GetPeople. That's how I would use it directly just to use that GetPeople method on an instance object.

How am I using this proxy object? Well, I'm newing up an instance of person service client in this case, which again is the proxy, and then I'm just calling proxy.GetPeople. So, I'm interacting with this remote resource exactly the same as if it were a local resource. Again, that's very, very powerful. Again, this is one of the things that I really love about SOAP services is that they are self-describing.

Now the Gang of Four actually, something that's interesting, is the example that they use for their example of the proxy and that is well, let's say you have this picture. Back in 1994, our networks were really slow. So if I just wanted a photo to come across the wire, it might take 30 seconds to a minute, and that would be for an extremely low resolution picture compared to our current standards.

So they said well instead of doing that, what if you create a placeholder in your application rather than bringing down that big resource off the network. Then if somebody clicks on that, then you can go through the process of retrieving the object itself. At first, I thought, well nobody has got that problem anymore. Our networks aren't that slow. I'm just laughing about how long it takes for a picture to come across the wire, but then I started thinking about our mobile devices.

Yes, we like to think that our mobile devices have high speed connectivity everywhere, but at least in the U.S. I ran into big chunks of country that have very little connectivity. So I might stop along the side of the road to take a break and pull out my phone to check Twitter and my connection says 2G. I'm like 2G? I haven't seen a 2G connection for years.

I'm trying to look at Twitter, but Twitter is just eagerly downloading all of the images because that's what it normally does. It's like well, maybe this application should be more network aware and say well, if you're on a constrained connection, maybe I should put placeholders and only download things when you actually ask for them. Those are things that we can actually use in our current day-to-day operation.

Facade Pattern

Now I do have one more pattern that I want to go through and that's the facade pattern. Again Gang of Four description, "Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use." All this is talking about is wrapping a complex API and making it easy to use.

As a real world example, I'm just going to talk about my home entertainment system. Now, I'm one of those people that's got multiple remote controls pointing to multiple pieces of equipment. If I want to play a DVD, I have to turn on the TV if it's not already on. Then I have to set the input to HDMI 1. Then I have to turn on the stereo if it's not already on and make sure the stereo is set to Aux input. Then I have to turn on the DVD player if it's not already on and press play on that.

Now this is absolutely no problem for me because I'm a couch potato and I can reach over and find those buttons on the remote controls without even looking. But the problem is is that I also do a lot of travel and I have two cats that don't do a lot of travel. So, I have a friend that stops by and checks on my cats when I'm out of town and for whatever reason, she likes to watch DVDs with the cats.

I don't want to try to teach her how to do this complex subsystem. So, for that, maybe I need a universal remote control, and there's just a button on there that says play DVD. It's up to that universal remote to figure out okay, what do I need to do to make this actually happen? That's really all that the facade pattern is. Wrapping something complex, making it easier to use.

Now as far as coding is concerned, if you‘ve used a foreach loop, you have actually used an implementation of the facade pattern. I love foreach. Foreach is just one of my favorite things out there because it seems like I'm constantly iterating through stuff. Let's just take a look at this.

This application will look familiar. It's a button in a list box. Again, right now the button is not doing anything. If we look at the application itself rather than accessing a service, I just have a hard coded class here that does the same thing the service did. It will just return the hard coded list of these person objects that I can use.

If I flip to the code behind, what I see is that I'm already calling that GetPeople method and I'm using an IEnumerable<person>. Now IEnumerable is an interface that's pretty much on every collection in .NET. It also shows up in a couple of interesting places. Anything that uses IEnumerable or that implements IEnumerable, we can use in a foreach loop.

So I can foreach over this and say foreach (var person in people), PersonListBox.Items.Add(person). I can just iterate over that because the IEnumerable describes that and foreach makes it really easy to use. Now when I click on the button, my list box is populated.

Now like I said, foreach is actually is a facade. It's a wrapper around IEnumerable itself. Let's just comment on that code and see what it would be to use this directly. If I look at the people object and say people., in addition to the stuff that we get from object, there's a method called GetEnumerator. This GetEnumerator will return me an IEnumerator<person> which we'll call enumerator.

Then once we have this enumerator, this is the thing that we can use to kind of loop through things. If I say enumerator., we'll see we have quite a few things that we can choose from. First is MoveNext because when we're talking about something, we can enumerator through. All we're doing is saying, "Hey, give me the next one. Give me the next one. Give me the next one. Give me the next one. Give me the next one," until there aren't any more normally.

In addition to the MoveNext, there's also a current property and that will be whatever the current item is that I just moved next to. There's also a dispose because this implements the IDisposable interface. Then there is a reset, so the reset will go back to the beginning of this enumeration so that we can start over.

If we look at MoveNext, this doesn't return the next item. Instead it returns a boolean value, a true false, and that lets us know if that MoveNext was actually successful. Well, that looks like something really awesome to do in a while loop. I can say while MoveNext. Then inside the code, I can say PersonListBox.Items.Add and I can say, enumerator.Current. That will actually give me the current item that I'm on after I move next.

If we run the code in this state, we'll see we get exactly the same functionality which is that my list box is populated after iterating through these objects. So, foreach actually takes this code and wraps it into a way that's easier to use. It actually goes a step further because like I said, the IEnumerator also implements IDisposable. I'll probably want to wrap this up in a using statement so that when I create it I also make sure that dispose gets called properly.

The thing is if I'm one of those nerdy people that looks at IL, the code that's generated by this code here and the code that's generated by the foreach is actually exactly the same in the IL. So the foreach is in fact just a wrapper of facade around this code.


Well, we know we can go even somewhat deeper, a bit deeper and we'll see that using I think can be called also a facade, right?



That's actually absolutely right because what using does is that it makes sure that dispose gets called regardless of whether there's any exceptions. So if you actually look at the code that's generated by using statement, it creates a tri-finally block and it makes sure that dispose is called inside the finally. So yes. That's a facade around a more complex infrastructure as well. These are all things that make our code easier to code and easier to use. Now, when we're talking about consequences to the facade, not all of the members are necessarily exposed. So we thought there was a reset method on the enumerator. There's no way to access that reset method when we're in a foreach loop, but quite honestly, generally what I would do is just spin another foreach loop and start over again. So a lot of times those consequences, again something to keep in mind, but not necessarily something that keeps us from moving forward.


Those are the three patterns that I wanted to focus on today to show us that you know what, we're already using this. If we look at design patterns, again these help us solve problems that occur over and over and over again in our environment. Again, it's just the core of the solution. It's not giving us a particular implementation. In fact, it describes it in such a way that you can use the solution a million times over without ever doing it the same way twice.

Now again, I would not recommend that because we should not be reinventing the wheel, but once we understand design patterns, now I can say, "You know what, I need an observer. So rather than building my own observer, let me go online and see what other people have done and if I can use that, awesome. But if I can't, you know what, maybe I'll take a wheel and tweak it a little bit."

Again, why do I care about this? These are well described solutions from people who are way smarter than I am and I just love to leverage their code so that I can move forward more quickly. It's a shared vocabulary that gives us a very concise language. Hopefully right now if I say I'm using the observer pattern you know what I'm talking about. Even if you don't know a specific implementation, you kind of know the big pieces that are there.

Again, this allows me to stay in design mode longer, and I really love that because now I can think about the pieces and how they fit together. Then of course, if I start using this in my every day speech, hopefully it will encourage the other developers around me to use it as well.

That's what I have for you today. Again, here are some links that you can get to the Design Patterns On-Ramp course on Pluralsight, as well as the code samples on GitHub. If you follow the GitHub link, there's also some links to some articles and other things as well. With that, let's see what our questions look like. Alex, have you been keeping track of those?



Q: Is there some restriction implementing patterns in JavaScript?

A: Well, there are different patterns that are using in different environments. For example, the Gang of Four patterns are very much geared towards the OO world. In the functional world and other worlds, there are different patterns that are talked about. JavaScript is one of those interesting languages because we can kind of treat it like an OO language even though it's not and we can kind of treat it like a functional language as well. So it really depends on the approach that you're taking.

There, I would say, yes there are definitely patterns that are useful in that world and I'm sure there is ... JavaScript is not my world so I'm not going to talk about any specifics, but I would say yes, there are definitely patterns out there in that world as well.

Q: Is copy-paste also a design pattern?

A: Copy-paste actually is anti-pattern. I also have a talk I do on clean code. I talk about how copy and paste is generally evil because it causes us problems. In fact, I don't even call it copy-paste in my normal development. I call it copy-pasta because if you do it enough times, you will end up with spaghetti code.

Q: Should we say that facade is an example of obstruction or something like that? 

A: That would be something I would need to think about a little bit more. I guess it could be considered a form of obstruction, but it's more of a wrapper. I would have a tendency to say wrapping rather than obstruction because when I think of obstruction I think about things like interfaces. I love interfaces. I have a whole Pluralsight course on interfaces. Those can help us with loose coupling, things like DI and that kind of thing.

This is one of actually those gray areas. It's actually an interesting topic because I'll often get asked is X an example of the Y pattern? That's where we have to stop and think about what's the spirit of the pattern. What is trying to accomplish. In that situation, obstruction actually isn't a design pattern in that case. It's more just a programming concept, but it's kind of that same thing. It's like what are the goals of obstruction and what is it trying to do? My gut instinct is to say no, but it's a gray area. It's one of those things that we can have great discussions with each other about.

Q: Does the usage of foreach have disadvantages in performance in comparison with using the reset method, what you talked about in this example?

A: It has absolutely no difference. Again, I'm kind of one of those nerdy people who likes to look at the IL code that's generated by the compiler. Again, the code that I showed using enumerator with the while loop and the MoveNext and all that, that is exact. If you look at the IL, exactly the same code is generated between that and the foreach loop. So there's absolutely no runtime differences at all. I would guess there might be a compile time difference, but it's probably one of those things you wouldn't notice.

Q: Out of all the design patterns, how does a newbie decide which patterns to use for a given problem1? In other words, is there a way to filter out the patterns to arrive at a subset of suitable pattern?

A: This is a difficult question to answer. There are multiple ways to solve a problem. And there are also multiple design patterns to solve a single problem. The differences in the pattern have to do with what approach is taken. And this often leads to a different set of consequences. I would start by understanding the Gang of Four patterns. These are very common problems/solutions. And it will help understand the more complex patterns than you might run across. Just like learning anything new, start with the basics and talk to people or look online to see what people who are working in the same problem-space are doing.

Q: Does design patterns always obey SOLID principles? Or is it even important to do so?A: The SOLID principles are “best practices” in the object-oriented programming world. I don’t like to use the term “best practice” because that sounds like it is always the right answer. But with my experience (but success and failures), I’ve found that they are a good place to start. If I have a reason to not use the practice, I’m okay with that as long as I understand the pros and cons of a particular situation. In general, the Gang of Four patterns can help us adhere to the SOLID principles, but it all comes down to how we use them.

Q: Any example of factory or abstract factory which we are using and not aware of?

A: Unfortunately, I can’t think of one off the top of my head. But I have use the Factory Method to dynamically load objects from the file system. If you’d like an example, you can see my materials on C# Interfaces:

Q: Isn't Proxy pattern built-in pattern with tools like Visual Studio?

A: The implementation of the Proxy pattern that we looked at (accessing a SOAP service) is definitely built in to Visual Studio. But there are other scenarios we might want to use the Proxy, such as using a thumbnail image instead of bringing down a full image or the difference between downloading a song and streaming a song. So we do have certain implementations of patterns that are built into our language and tools. Some other examples in C# are Iterators (IEnumerable) and Observers (Event Handers / IObservable).

Q: How do we know that we need to use design patterns to a specific problem? Because most of the problems can be solved without using any design pattern.A: Learning about design patterns helps us see what solutions are available (and hopefully we can borrow someone else’s solution rather than creating our own from scratch). We can build a house by stacking bricks, but if we understand the patterns of walls, lintels, and foundations, we’ll end up with a much better structure. Programming patterns are the same way. I spent many years using patterns accidentally because I ended up solving these common problems. But once I could put a pattern name to a problem, I could look at how other people implemented the pattern. Sometimes I use those solutions, and sometimes I used them for ideas to incorporate into my own solutions. But that lets me use much better than what I could come up with on my own.


Q: There are plugins which allow patterns to be implemented in Visual Studio. Would you advise using them or rather learn the codes and implement them?A: I haven’t used the tools, so I can’t give an informed answer. As a general rule, I like to understand what the tool is doing before I use it. For example, I use Dependency Injection (DI) containers when I code, but I was not able to use them effectively until I understood what the containers were doing – and more importantly why. I would think it’s the same with pattern tools. I want to understand the patterns (particularly the “why”), and then I would be fine with letting a tool do the hard work for me. This would be similar to how I let Visual Studio create the SOAP proxy for me. I don’t need to understand all of the details (XML, HTTP, etc.), but I do need to understand why I’m using the proxy.


Q: What pattern should I use for creating exception handling library?A: Exception handling is a pretty big topic. It turns out that the built-in exception handling in .NET uses the Chain of Responsibility pattern (this is one of the examples I show when I have a bit more time to talk about patterns). When an exception is thrown, it looks for a catch block that can handle it. If it can’t find one in the current method, it walks up the call stack to the calling method. Then it just keeps walking up the call stack until something can handle it, or it drops off the end. (And this is why it’s a good idea to put a global exception handler somewhere in the code to make sure the user has a good experience.)


Q: Instead of using Proxy pattern for WCF services, I prefer use ChannelFactory object to use same object from the service without any MAPPER. Is there any other way to use Proxy for this case?A: As we saw in the definition of design patterns, there are a million different implementations. If there is a built-in implementation (such as the WCF Proxy in Visual Studio), I like to start there since it’s “free”. But if I find that my needs are a bit different (like I want to optimize for speed), then I’m free to look for different implementations or create my own. So there are lots of ways to use a Proxy in this situation. Unfortunately, I haven’t looked into them since the built-in one has worked for the situations I’ve needed.


Q: What about structure diagram and code?

A: Often when patterns are described in pattern catalogs, they are accompanied by a UML class diagram. Personally, diagrams often cause more confusion for me than help, so I tend to not use them. It’s easy for me to look at a class diagram and get stuck in a particular implementation when I really would rather understand the spirit of the pattern and the concepts behind it. Both the Gang of Four book and Head First Design Patterns include class diagrams (although the Head First book uses them for specific example code rather than the overall pattern).


Q: What pattern should I use for micro service implementation?A:Micro-services is a big topic. Looking for *a* pattern is like looking for a pattern for a web site. Generally, we would use multiple patterns to address the different problems that we are trying to solve. If we think of each micro-service as a self-contained application, then we can imagine using quite a few different patterns in putting it together.


Q: What is the difference between proxy and facade?

A: The main thing about design patterns is to look at the problem they are trying to solve. One way to think of the Proxy pattern is as a way to access a remote resource as if it were a local one (it’s a bit more general than that, but that’s the example we saw with the SOAP proxy). The Façade pattern is a way to reduce complexity by creating an easier way to interact with something (as we saw with the “foreach” example). The implementation of the SOAP proxy can also be considered an implementation of the Façade pattern since it’s wrapping the complexity of making the SOAP call (XML, HTTP, etc.). This is part of the fun when we start looking at patterns. We find that complex systems are often a combination of multiple patterns.



Q: When I have multiple patterns that can be used to solve a problem, how can I choose one, or can I combine them?A: This is one of those areas where we try to understand our tools better. There are multiple patterns that address the same problem (for example, there are many patterns that are variations of the Gang of Four patterns). In that situation, look at what the pattern is optimizing for. It may be addressing a particular consequence, such as performance or memory usage. If you are concerned about that consequence, then it may be a good choice. But if that consequence isn’t important to you, then something else may be better.

Q: Taking into account the example of IEnumerator and foreach, what would be the most correct to use?A: Since “foreach” gets compiled into the same code as using “IEnumerator” directly, I would use foreach. This makes our code more readable – and we need to make sure our code is readable by humans in addition to the computer. If there were a difference (for example, if the direct use were faster), even then I would look very carefully to see if that difference is important to me.

Q: You said foreach is a facade pattern. Is it also an iterator? Does it mean that any concrete implemenation can be a combination of multiple patterns?A: Yes, foreach is an example of the iterator pattern. In fact, I talk about this when I have more time to talk about design patterns. Many things we run across are implementations of multiple patterns. Another example is data-binding. This implements the Observer (when the UI elements change, the backing objects are changed) and also the adapter pattern (when a backing field is a number, it is displayed in the UI as a string). In reference to “foreach”, I usually call this an ‘Iterator” since that is its primary purpose – to iterate over items. The “Façade” pattern is more an implementation detail than the primary purpose.

Q: Which design patterns are useful in writing cross-platform code?A: There are a lot of patterns that we can use in cross-platform code, just like there are lots of patterns we can use in any application. The patterns we use depend on the needs that we have. For example, if I wanted specific UIs for each platform and wanted to share presentation code, I would look at various patterns that could help with loose coupling, such as Abstract Factory or Inversion of Control. But these aren’t strictly limited to cross-platform concerns.


About the speaker, Jeremy Clark

Jeremy Clark

Jeremy Clark makes developers better. By drawing on over 15 years of experience in application development, he helps developers take a step up in their skillset with a focus on making complex topics approachable regardless of skill level. He is a Microsoft MVP for .NET, and he has authored seven courses for Pluralsight, including "C# Interfaces", a course aimed at giving developers a clear understanding of abstraction. He loves speaking and has delivered over 200 technical presentations in the last 7 years in the United States and Europe. Jeremy lives in Southern California with 2 cats and a banjo. Jeremy's blog.


In this webinar, PostSharp’s founder and principal architect Gael Fraiteur demonstrates some of the most exciting new features of PostSharp 5.0:

  • Logging: PostSharp 5.0 comes with a fully revamped logging aspect, which allows for much more flexibility than before. Key new features include complete customizability, support for semantic logging, and super-fast performance.
  • Caching: You can now cache method return values and invalidate the cache easily, with custom attributes. PostSharp 5.0 will include support for MemoryCache and Redis, two-layered caches, and local caches with pub/sub invalidation.
  • Async methods: We have filled the gaps in OnMethodBoundayAspect and MethodInterceptionAspect for async methods.

Watch the webinar and see what's coming up in the new version:

PostSharp 5.0 Sneak Preview Logging, Caching and Async on Vimeo.

Download source code of the examples.

About the speaker, Gael Fraiteur

Gael Fraiteur

Gael has been passionately programming since childhood; building and selling his first commercial software at age 12. He is President and Chief Architect at PostSharp Technologies based in Prague, Czech Republic. Gael is a widely recognized expert in aspect-oriented programming and speaks at developer conferences in Europe and the United States.


Structured exception handling and defensive programming are the two pillars of robust software.

Both pillars fail however when it comes to handling internal faults, those that normally originate in software defects rather than in any external factors.

In this webinar, Zoran Horvat demonstrates advanced defensive coding techniques that can bring the quality of your code to an entirely new level.

Watch the webinar and learn:

  • When throwing an exception is the right thing to do
  • Why exceptions and defensive coding cannot be applied to recover from defects
  • How to handle situations when internal software defect is causing the fault
  • How to treat fault detection as an orthogonal concern to normal operation

Advanced Defensive Programming Techniques on Vimeo.

Download slides.

Download code samples.

Video Content

  1. Bird's View of Defensive Programming (3:21)
  2. Demo (6:47)
  3. Design by Contract (16:24)
  4. Q&A (50:34)

Webinar Transcript


Hello everyone and welcome to today's webinar on advanced defensive coding techniques. My name is Tony and I'll be your moderator now. I work as a software engineer here at PostSharp and I'm excited to be hosting this session today. I'm pleased to introduce today's speaker, Zoran Horvat. Zoran is CEO and principle consultant at Coding Helmet Consultancy, and today he's going to share about what should you know about defensive programming and how to improve internal quality of code. 

Before I hand the mike over to Zoran, I have a few housekeeping items to cover about this presentation. So first, this webinar is brought to you by PostSharp, that's why this slide is there, this is not Zoran, neither me. PostSharp is an extension that adds support for patterns to C# and Visual Basic, so if you are tired of repeating yourself in your code, you may want to check it out, as did at Microsoft Intel or Bank of America who have been using Post Sharp in their project to save development and maintenance time. Customers typically take down their code base by 15% by using our product, so feel free to go to our website, for more details, or you can get also a free trial there, and now back to our webinar. Today's webinar is being recorded and the recording will be available after this live session, and all of you who have registered to the webinar will receive an email with the link to the recording. 

And last, during the webinar we also love to hear from you, so if you have any questions for our speaker, feel free to send your questions through the question window at the bottom of your player, and all the questions will be answered in the end of the session. If we do not get to all of your questions, we will also follow up after the webinar, so all of your questions will be answered in the end. So without any further ado, I'd like to kick off things by welcoming Zoran Horvat so, Zoran, over to you.


Yeah. Thank you Tony. Hello everyone. As Tony has already told you, on this webinar I'm going to talk to you about certain aspects of defensive coding. You may know me from Pluralsight courses mainly, I have five courses published there, and things that you will see in this webinar might be seen generally in all five of the courses I have published this far. Those are general programming principles applied, and applied on a very specific and narrow goal of making code internally more stable. 

Now, without any delay, I will just tell you precisely what this demonstration is going to be about, because the term defensive programming is talking about a large area, and I will identify a very small subset of problems that we are going to address today. 

Bird’s View of Defensive Programming

So, historically, you may probably be aware that the whole thing about making programs stable first started with garbage in garbage out concept. Which was very good in one respect which we programmers like a lot. You don't have to code anything to put garbage out. So a lot of software was written in a way that code is not responsible for invalid, for behaving in the face of invalid input, and that worked quite well for many years only now and then producing distraction and that, it was generally very good. 

But as time progressed, as years passed, programmers were more and more interested in having stable software, so that is how defensive coding came into being for the first time. And then I'm pretty sure that you know more or less everything about defensive coding already, and you might be asking yourself, why, what am I going to tell new today. Probably nothing, but anyway, let's draw the map of defensive coding.

For one thing, you want to defend from input, from invalid input to reject invalid input right away, and to only let valid input in, or to standardize communications with outer systems, which not only means other services or, I don't know, network, things like that, or database, but also the libraries that you might include in your own process. If you don't trust other people's code, you might sanitize the output from a library. However there are more things there, and today I'm going to talk to you about things that are not, that don't have to do with outer layers of your system or your component, or whatever you are writing. I'm going to talk to you about defending from yourself. 

Many people don't really understanding that there is a concept of defending from your own code, and I will give you a hint now, and you will hear about it in around 20 minutes to think about that hint. For example, if you face non reference exception, what do you do? How do you defend from that? If it's not something that came from a third party code, from a library, or from any metric service or anything, if it originated from inside your code, how do you defend from that? And that is what we're going to be talking about today.


So I'm going to introduce a very small example, it's going to handle students and subjects there enlisted to listen and to have exams, so student is going to be identified by name, and is going to keep a list of grades from exams that student has passed, and student will expose three methods, add grade, remove last grade, and get average of grades, and now as you look at this API, this is very small API, you can already start thinking about what can go wrong with only three methods we have, and many things can go wrong already. And you will see even more things will go wrong when we introduce training, which is, for example, a university subject, and students can enlist for the training. Training will expose another three methods, you will be able to add a student to enlist for a training, and then two more complicated methods will come, that top student will have to work through the list of students and sort them by average grade. And the last methods add grades, will be the most complicated of all, it will be involved supposedly after the exam, it will receive the list of student's names and grades, it will work through the list of students and add a grade to each of them. 

And now, what can go wrong? This is usually a place where I apologize for using PowerPoint and step into Visual Studio. This is the code, I'm going to show you the code which is implementing all these six members. First let me show you the grade, grade is just an enum. It's an enumeration defining grades, and the only working code is located in the student and training classes. So I will show you first things that can go wrong in these two small, very small classes, and you can imagine how bad it could all be when applied to a large project.

Sometimes people tell me that I'm showing too simple examples and non-realistic, but you will see that only six very small functions, half of them one-liners, can cause you so much trouble that you will have to reconsider your entire coding practices, all the practices you're using every day, if you want to survive six simple functions.

So let's start. Grade average. There's the list of grades, down below I'm adding grades to the list, and this is the grades average. Every grade is first converted to double, this is my extension method, it is not important at all, what is important here is the average extension method, which comes from the link library. This method will throw an exception if the list is empty. So we already have one thing to defend from, and I'm even helping the course by introducing a new member, he has grades, which returns boolean, telling whether these grades is empty or not. It returns true if there are any grades in it.

So if you want to avoid an exception coming automatically from this property getter, you better check where this property returns true beforehand. 

Now remember, this moment, I'm telling the callers to make sure to check potential output before using the member. That is hiding half of the answer to the great question, how to defend from the inside of our repetition.


Excuse me Zoran, I have a question here about this great average property. You say that we should check in advance whether the student has any grades or not. What if we, instead of that, return some special value from the grades average, like, not a number, or if we make the double nullable and we return null?


Yes. I could answer that question on several levels. On one level, you should ask yourself, what have you got by returning, for example, null or double? Did you get anything more compared to a boolean and a double? No. Nullable is still a type which has a value boolean property and a value double property, so you still have the same thing in your hands. 

On more elaborate level, if you return something that could mean one or the other thing, then you are placing a burden on the receiver of this result, to be afraid of what he might get. I think it is much better to put the thing straight before the caller. Now, if you call grades average, then make sure to not receive an exception back, So if you get to the point of calling grades average, then you should have already made sure, either by adding a grade, and therefore making sure that there is something to average, or by asking whether there are grades or no, and after you have made clear that it is safe, then you call this, and then you get an exact result. No speculation beyond this point what you have got back. I hope ...

Tony: Okay, thank you.

Zoran: ... This is enough.

Tony: Thank you.


Okay, so the add method. First, let me make a disclaimer here, this method is returning a flag as an indication whether the operation passed well or not, this is not how you should write code in my opinion, and I will remove these flags by the end of this demonstration. I have started the demonstration with an ancient way of defending, which was based on status codes returned for matters. So people used to return, for example, false, if operation cannot be conducted to the end, then true if it went well.

So this is the old way of dealing with unknown input, so this input was not sanitized before, and now we have to deal with it, and I have a piece of private logic here, it is very simple, I'm asking if this grade is defined in this enumeration, so don't send me a grade value of 57, because it's not an existing grade. If something like that happens, I will just return false and be done with it, right?

Why is this bad? Again, this is bad on a couple of levels. On one level, I am making troubles to the caller. The caller doesn't know what's going to happen after he calls my method, and that is a bad thing. We don't like non deterministic code. We don't want to call a function and not know what is going to happen after that. Imagine a list of five steps that you have to make one after the other. You made the first step, the second step, the third step, now fourth step is calling this function for example, and the fourth step returns false. That means that now you have to roll back the first three steps, which might be very complicated. It might include calling dozen of other methods to roll back the effects of these three steps.

So returning a flag is a bad thing to do from that aspect, but there is another aspect which is even more important. You see, if I give up at this point, it's not only that I give up. I must also recover from this situation somehow. It's not the end by returning from this method. Every ever must have a recovery. If you don't recover, you must kill the process, alright? If you want to keep going, to keep running, you have to recover from every single, every bit appears during execution. How is add grade going to recover?

Design by Contract

So this is the first concept, the first important place where I will mention design by contract. If you haven't met design by contract, it was introduced by Bertrand Meyer quite a long ago, and it's still not widely popular. I suppose it's not widely popular because it is a bit complicated, but I will try today to tell you the most important part of the theory, which will make you not really understand it to it's fullest extent, but it will make you start thinking in a different way. 

So here we have a function, add grade, which is defending from invalid input. And I say that is wrong, because this function doesn't know what it means to recover, it is easy to just give up. Now, how to recover. This function cannot recover, do you know why? Because it doesn't know who called it. And that is an extraordinary idea. I myself was defending at the called site, so inside the method that was called, for many years, until I understood that the method that was called cannot defend because it doesn't know the context in which it is executing.

Is it a web application recovering from a format error? Could mean to send HTTP status, internal server error, 500, or temporarily unavailable, or not found, whatever, so it needs to send an HTTP response back. If it is a desktop application, recovery means to pop up a message box, or if it is a unit test, it has searched false and made the test fail. So only the caller knows what it means to recover.

Okay. You keep thinking about this and I will keep talking about current code. Remove last grade is removing the grade at the last position in the list, but only if there are grades. It also returns boolean flag and that's it. And now to the more complicated class, training. It keeps a list of students, it allows us to add a student, but we can only add non-null students, you will see why. Here is the get top student, this is the method which is sorting the students by their average grade descending. But now, we have two kinds of students, those that do have grades, and those that don't.

And now you see that story about the caller and the callee. The calling class training knows exactly how to recover from the situation when the student doesn't have any grades. It is very simple at the disposition. I can pick only the students that do have grades, and sort them descending by their average grade. And then, just concatenate those that do not have any grades. Do you see? This list is going to have students all descending by their grades average, and then all those who didn't have any exams yet at the end of the list, and it's never going to fail. This function is safe, only because the student class has given me the means to test them, so that I can recover from potential. It's still not an error, it is a condition, I can recover from something that might end up in an exception, and I would have to recover it using other means if I had the exception from the grades average. Now there's no trouble at all.

So this is the great concept, giving public members to the caller to test the state, and prepare defense from any condition in advance. 

Okay, let's move forward, set grades. This is a terrible, terrible piece of code, don't write code like this ever, but I had to. I had to do this, let me show you what this function is doing. It is receiving a sequence of tuples, each tuple consisting of a string representing the name and the grade to give to a student with this name. 

Now, what can go wrong? A student might not exist in the list of students. There is a list here. So the student might not exist here, and this function should fail. I'm still returning boolean flags to indicate failure. And on a more detailed level, the student might exist, and we might try to settle the grade to that student, but add grade could fail, saying, "No, no, I don't want this grade, goodbye." So we might face a failure deep inside the loop, and that is, that scenario, which I told you already, like having five steps and one of them fails.

So look what I am doing here. I am first defending from the situation, forgive me the syntax, this is going to be much cleaner later. This is a query which has... For any tuple in the input, now all students say that their name is different, and that's meaning that there is a name which doesn't exist in the list of students, then give up and return false right away.

So I'm defending from one sort of troubles, but the other sort of troubles comes only inside a loop. Much later, when I try to add a grade to a student and this might return false. Now if one student returns false, then I must work through the list of all students who did accept their grades and roll back the change. That is that roll back which I mentioned, so you can see how terrible code is produced if I try to defend from a flag returned from deep inside a loop. So this is the roll back list, any student who accepts a grade is put into the roll back list, if any of the students later decides not to accept the grade, I must walk through all the students who were successful, and roll back changes, and then return false. So this code is terrible.

Alright. Let's start fixing it. The first thing, if you want to defend in your code using status codes, which I strongly advise not to do. If you insist on doing that, then it's better to do that right away at the beginning of each method. You see, it's better to ask all the students first whether they exist, second whether they accept grades. So I would need another public member, this is the student class here. I would ask for a can add method on the student class so that I can ask them upfront, and if I do have that method, then all this doesn't have to look like this. It becomes much simpler, you see? I can just walk through the list of students and find each of them by name, picking the first one with that name, and adding a grade to it. This time I know that the first that this creative, or the student by name, is not going to fail, and second, I know that every student will accept the grade, because I have asked both of these things up front.

Alright, now I need this can add method, so here it is. It is just repeating the logic that I already had in the add grade. You see, this is the same thing, only this is the negation. So, I could rise this theory to a higher level and say, and really introduce contracts at last, and say, student and training classes should have an agreement how they work together, and that agreement is called the contract. And a student class says, listen, don't call add grade unless you're sure that can add grade will return true. If you're not sure, ask. If you are sure, alright. And then, after having can add method, I must change add grade to actually use that method. Previous code was this, and this is a pretty much private piece of logic. 

Now can add becomes part of the documentation for the add grade method, and add grade method will check can add according to documentation. I'm not sure whether you understand this, but the idea is to ... Let me rephrase, contract will be defined in terms of public members only, and then the contract will be checked in terms of those same public members. 

Okay, now. Now we have a situation in which add grade method is checking the public contract and giving up immediately, if the contract is broken. But then, why returning false? We can push contracts to even higher level and say, contract must never be broken. Never. The other class must not call add grade if can add is returning false. It can throw an argument exception for example, and stop execution not only of this method, but of the caller as well. The caller must be sure that the object and arguments are correct before calling the method.

And so, this remove, okay. Remove is going to test public member, HasGrades, it was public from the very beginning, and now HasGrades is a contract. It says HasGrades must return true, or otherwise I will fail. So you may start thinking, but this is a bit too hard, maybe this is too much, why not keep returning boolean flags? I will show you.

Before that, let me fix these two complicated preconditions as well. The difference between these preconditions and those nice preconditions in the student class is that, again. I'm having a private logic, something I cannot write this into any documentation, because nobody has access to students, for example. So what I'm going to do will be to give access to the students, not just indiscriminate access, I will introduce a very concrete contained student method, so if you're not sure whether I contain a student or a given name, then ask, and after you asked, you will be free to call set grades and pass that name as part of that list of names, because you know that it is inside. If you are not sure, I keep right to throw, and I will stop your execution if you didn't obey my contract.

Similarly, this will have to be turned into public contract again, I will imagine some accept grade method on this class, which will receive name of the student and the grade, and it will tell you transitively whether the student with this name will accept this grade, if yes, then you are free to include that tuple in this list and call. 

So I'm finally giving up all these return flag instructions, then I am going to not return any flag from this method as well. So all the methods that are doing stuff are just returning void in my solution this time. I need this accept grade method, it is very simple, it is looking up the student, now I know that the student exists, because that is a precondition for the precondition, so to say, and I ask every student whether it can accept a grade. 

So, we have moved this solution to a higher evolutionary step, and this is typically sa far as many people would go. But now, if you were throwing argument exception, for example, or argument null exception, or index out of range, or invalid operation exception, things like that, then it is the time for you probably to think why did you do that?

So, the question is, you can think for yourself, did you ever throw argument exception? And you probably say yes, all the time. Then I ask you the second question, did you ever catch argument exception? And I don't know, I suppose that nobody has ever done that. The problem with argument exception, argument null exception, and similar exceptions, is that nobody ever catches them. People catch exception, and they do that at a very topmost level before the exception goes out of our scope and becomes an unhammer exception. We are handling exception just to protect our process from failing. We are never catching argument exception. And the reason why is that because we have no clue what to do with it. It is as simple as that. You cannot handle argument exception, because handling and recovering from that exception would mean to correct that argumented call, make a call again. But then, if I knew what's wrong with the argument I am passing, I would pass the correct argument right away, I wouldn't call the exception in the first place.

This is a mind-bending idea that might need to mingle in your head for a while before you start thinking the same way I'm thinking. I don't know how to make you believe me in a one hour session. That is my point. But anyway, we could ... Suppose that I have persuaded you to not throw concrete arguments and not to try to handle them, what is the next evolutionary step?


Excuse me Zoran, before you go farther, I would have a question here. Wouldn't it help if you are more specific in these exceptions, because here you just say student not found, but if someone on the top level catches the exception, wouldn't it help him to know, for example, which student hasn't been found, or which student has an unacceptable grade, or which grade?


Mm-hmm, yes, so you are suggesting to make even more specific exceptions, like our own custom exceptions, and populate them with more specific information, right?

Tony: Exactly.


Okay, so again, what would we do with that? Suppose that there is a student name which exists here but doesn't exist in the student's ... Where is it, student's list. Now we would include that student name in the exception. So what would we get with doing that? The caller would have to catch specific exception, to expect that exception, and then to dig for specific information there, our student's name, and then do what? Once again, we have no clue what to do. So a student is not there. Is it going to add it? No, it doesn't have a grade for that student, so we have an impossible situation. So we are not going to recover in any ways, including more specific exception, plus, even if you do catch a more specific exception you are still going to do the same things as in this contract scenario, so we are going to understand that this student does not exist in that list, alright? But we could do that by asking whether this list contains that student for every student name. 

So all the code is still there, it's only packaged in different places. So you're not going to have any functionality more than you already have, and you are still not going to be able to recover from the error.

Tony: Okay, thank you.


And then, the revelation. If precondition is violated, in any place in code, do you know how that is called? How do you call remove last grade when there are no grades? What do you call that? Or what do you call adding a grade which is not part of the enumeration, which is invalid grade? You call it a bug. Precondition violation is identically equal to a bug, and if you ever thought why you cannot recover from mistakes like having a name of a student which doesn't exist in a list, or having a grade which cannot be accepted by an existing student, if you thought why you cannot recover and keep going, but you must stop execution of data operation, of course, and just stop it, there's no more execution of data operation, then the answer is because that happened because you have a bug.

And then, checking preconditions means to catch bugs in your code. There's no recovery, just stop execution, that's why people throw exceptions, they don't return status codes, there's no more execution beyond this point. And now, as good programmers, we could do a new thing, completely new thing, and say, "Alright then, checking preconditions is a separate concern. Let's create a class," we are object oriented programmers, and we resolve issues by creating new classes, alright. So here's the contract class. This class will be a library somewhere on the side, not part of real production code. And in the contract class, I want to define a utility code requires. It is even a static, static method, it will receive a predicate which must return true. I will call this predicate, if it returns false, I will throw an exception, and listen, I don't care what exception, I will just throw an exception, because this is the end of the road, I'm writing precondition violations, there is no more. No specific exceptions, they carry no information which has any meaning at a disposition.

And now, … using this, for example in the add grade, I will call requires and say this is ... I can add, I can accept, can add a call with this grade, this must be true. Done. Remove last grade would be another. An another, an another, let me find number five. Another precondition, has grades, it must be true, and that's it. 

Now look, preconditions have been turned into a declarative code. It's not imperative, and just declaring what must happen in order to start doing this. Alright? Now I suppose if this is the first time that you see preconditions, at least in this way, that this is a bit too fast for you, you will have access to code and to code snippets who would be able to repeat this whole process and see the evolution of code yourself. 

I will move faster towards the end. Now look in the training class, I have these complicated preconditions, they are complicated because they are working in a collection. They must work on all elements of the collection. So we could even, now that we have moved the contracts to a separate class and declared them an orthogonal concern, now we can add universal quantifying precondition. Alright.

So contract extensions is going to be the class that will hold that. You see, this is another extension method, this time it is an extension on a sequence of whatever, it receives predicate on that whatever, and it just calls, requires for you to … elements in the sequence, nothing more. This is just a universal quantifier for preconditions. 

I was able to define this very easily because I have moved this different concern into a separate class. So, back at the training class, let me rewrite these preconditions in terms of universal preconditions. Now this reads like names and grades, for them I require that all tuples satisfy that I contain a student with this name, this is the name of the constraint, and I request that I'm accepting a grade for this student name and this grade, this is the name of the constraint.

Do you like this code? It is 100% declarative, and one even more important thing, it is encapsulated. It is encapsulated here, not in my production code, but in some other library. And now, what can we do with the encapsulated code? We can change it without affecting the caller. That is what object oriented programming is all about. 

So, look at this. Suppose that somebody has said ... I'll return to this. Somebody said, "Listen, this is working for the  sequences, it's even working twice, I don't want this to work on every call in production, this is flow." Alright. And I'm pretty sure that this will never happen, that this precondition is false, we have really tested the code to the end. Alright. We want universal and existential quantifiers to be switched off in production. 

Do you know how you switch off this code in production? One way is to add conditional compilation, that is a feature of .NET. You can specify that this piece of code is going to be included in the assembly, but then when just in time compilation is performed, calls to this function will be removed if this symbol, debug, is not defined. 

So let me show you what happens if I end testing and decide to go to production. So this is debug configuration, now I turn to release, and this goes great. Compiler removes both calls at just in time compilation. So you can keep quantifiers alive in debug and turn them off in production, making code safe during testing and making it fast during execution. That is one thing you can do when you treat a contract as a separate concern.

Or, even more, you could, this is the, requires you change the method, you could do something like this. This is the old fashioned conditional compilation. You can say that in debug mode, I want to assert, I want to kill the process. Now, why would I kill the process? Why not keep throwing plain exception? Because, exceptions can be caught. Sometimes people inadvertently catch exceptions and do nothing with them. They catch exceptions because they fear that those exceptions would propagate up and make damage. Alright, that fear is not well placed, you should not catch an exception unless you know perfectly well what to do with it, but people still used to not handle exceptions, but just cover them up. And if you throw a precondition violation exception like this, then even in the testing code, it might happen that somebody has hidden the fact that exception has been thrown. And then, you have a bug, and your code has raised a flag saying, "This is a bug, you have a bug, fix it," but somebody has hidden that flag from you. And then you deliver buggy software to production.

So in order to avoid that, you may choose to assert in debug mode. Assertion, if predicate is false, assertion will kill the process. There's no way for you to hide that, to catch assertion, it will propagate to the operating system. And it is very often a good idea to assert on precondition violations during debugging, because then everybody on the team will know that there is a bug, and they will have to address it. And again, if you go to build configuration, when you finish testing and go to release, then you switch off assertion, and even without that, I was using this assertion from debug name space, so this wouldn‘t affect the release build anyway, so you get back to throwing an exception, because, well, it's not nice to assert in production, you don't like big red screen, windows and message boxes on the screen, alright. 

So then you throw, even if that means that some exceptions would be silently ignored, just for the sake of end users, keep throwing the exception rather asserting. And another thing, the last thing in this demonstration, there's even more interesting idea. What exception should we throw? Not plain exception, plain exception really says nothing. Maybe we could throw some exception like contract exception, you see, and it says precondition violation, this precondition, alright, but what is the contract exception? 

I could, I could define contract exception as a private class inside my contract class, for example. So that nobody can see it, only I can see it. So when it comes to doing something, for example, I know this add grade might fall, I could wrap it in a try catch, but catch what? Contract exception? No. There's no such thing, it is a private class, I cannot write a synthetically correct catch block which includes contract exception. I cannot handle contract exception, the only way to handle it is to handle the base exception, which is a bad practice, and I suppose nobody of you is doing that, you should only catch general exception on the very last level in your component, just to stop exceptions from propagating outside of your component, so you would generally capture general exception and say, if you are writing a service, you would return either 500 in internet, or whatever code, or temporarily unavailable, or I don't know, not found, things like that. 

If you are writing a desktop application, you would return some object which indicates to the user interface that it should pop up a message box and excuse to the user, so that is the place where you catch general exceptions. The very limits of your system, not inside. On the inside, I would suggest you to throw private exception class so that nobody can really catch it. And again, the reason is because any precondition violation equals to a bug, and you cannot recover from a bug. You cannot fix an argument and try again. If you knew what's wrong with the argument, you wouldn't cause the exception, so that is the simplest way to look at precondition violations.

Alright, this was the demonstration, I hope that you liked it. Now you can ask questions, I have left a bit more time for your questions, because I expect to have at least a couple of them, and I would like actually to hear you, and to try to respond to your questions now. 


Q: Would the debug assert be removed from release build even without the debug compile directive?

A: It is not an easy decision to remove parts of the logic that is checking the conditions. If you are absolutely certain that you have checked everything in testing, you can remove all precondition checks from your application and make it absolutely fast, as fast as possible. If you are not sure, then you leave preconditions in production, but that is one of the concepts. Also, there is that gray area in between. You might add a lot of heavy checks that are good for debugging, like just imagine a sorting algorithm, an algorithm which sorts the array. Can you imagine how many checks you could perform during the execution of that algorithm? Including the final check that the array is really sorted at the end.

All that would make the sorting algorithm tremendously slow. And then you just remove all of that with a compiler directive from production code. You don't have to check the debug symbol. You could introduce your own symbols, like heavy precondition, or things like that, and switch that off not only in release build, but in the build which is going to be on staging or in production. Then, for example in .NET core, you can use environment and check what environment it is, and then to have heavy checks in development, less checks in staging, no checks or almost no checks in production, so that is the point.

It is very important to understand the concept of preconditions as a separate concern which is not turned into 100% configuration question. It is not a question of your code, it is not part of your code anymore. You could see that I was changing the way preconditions are compiled without making a single change in production code, that is the most important part.

Q: Why not use Microsoft code contracts? How does this presentation apply to PostSharp? 

A: Zoran:

Microsoft code contract is a grade library, which unfortunately having hard time right now. Recently it was turned into a community project and I don't see much activity on there. For those who do not know, code contracts library is defining preconditions, post conditions, and variants, even precondition inheritance, you can define preconditions on an interface, not on a class, and the compiler ... Not the compiler, the code contracts library would jump after building the byte code and rewrite your byte code so that all classes that implement certain interface with contract, the contract code will be injected into them after compilation, so it is tremendous idea. 

Unfortunately it never got popularity, and it had a grain of poison from the day one. That byte code rewriting is a heavy hammer. You don't want your production code to be rewritten by any tool. If you imagine deploying such code to production, and knowing that some tool has changed it after you, then you have probably decided not to do that, and code contracts library, I like it very much, it is great idea, unfortunately it is not popular today. And it's not going in any direction towards success right now.

PostSharp is including the tools for code contracts, right now the tool does not support all these concepts that I have shown, however it is hitting the central point by turning contracts into a separate concern. In PostSharp, contracts are implemented as aspect, so again, it is outside of your production code. It is a very important idea to not keep contracts as part of your code.


PostSharp allows you to add patterns to C# without changing your language, and it comes with some ready made contracts library, which covers part of what you have seen in this presentation. But you are also free to create your own contract aspects, so if you don't like how we have prepared this, you can still use PostSharp and make your own pattern implementation. 

Q: Is there any situation in which non private custom exceptions should be used? 

A: Yes, of course. Exceptions are what their name says. Just imagine, I don't know, metric exceptions for example. Metric exceptions are giving you the way to handle an external situation, something that did not originate and end inside of your inner code, but it came from the outside, the network failed. You could write a library which terminates execution by throwing an exception, alright, that is perfectly valid solution. However, you must make a clear distinction between situations which are suspicious in terms of looking like a bug, from situations where something has prevented you from completing the operation and nobody could see that in advance. 

It is easy to see that, for example, a user is blocked and you cannot move money to that user, so it is trivial to see that. If somebody, even after that, calls you and asks, "Now give money to this user," and you see that the user is blocked, there's no point in throwing an exception. Because that caller might handle exception and keep going, thinking that the money is there, and it's not, it cannot be. So that is a bug, that is not an exceptional situation, it's a clear bug and you must stop execution right now. There's one saying, popular saying, which says, "Dead process makes less damage than the crippled one." If you catch a bug and let your process keep going, it is a crippled process, something has happened and you have no clue what, and then if you let it keep working, this might damage the data, it might commit something in the database that it should have rolled it back.

I hope you understand the distinction now. There are bugs, and there are exceptional situations, so throw exceptions only in the second category.

Q: Doesn't the argument against the rewriter for Code Contracts also apply to PostSharp?

A: Actually, no – IL rewriting done by Code Contracts makes the code you see during debugging not the same as the code you execute. PostSharp respects the whole development chain, so even though it is rewriting the IL, the debugging experience remains untouched. You can debug not only your production code, but also the aspect code including even your custom build-time logic. And the PostSharp Visual Studio extension helps you to keep track of all the enhancements PostSharp does in your code.

Q: Why not using the standard Microsoft Code Contracts library instead?

A: Code Contracts are obtrusive, and my experience shows that development teams are not ready to take the risk. The teams I was leading have never even considered using Code Contracts library, and I didn’t want to push the matters either.
If I had to pick the sole reason for not advocating use of Code Contracts library, it would be the fact that it is modifying the IL code in a non-transparent manner. Even the original documentation states that IL code rewriting may be the reason for teams to avoid using Code Contracts.
In my opinion, Code Contracts could have been designed as a regular library, and that would remove that veil of mystery that surrounds the process of code rewriting. I suspect that primary concern was performance. But then, if you look at spectacular performance gains of ASP.NET Core, for example, we could question that reasoning on grounds that performance could have been improved using other means. We will probably never know.

Q: How does this relate to Code Contracts?

A: If you decided to try Code Contracts on this same example, then you would find that there is correlation between syntax I have shown and Code Contracts syntax.
That is not a coincidence, because my example was strongly influenced by the Code Contracts library.
There are two reasons why I have opted to use custom contracts instead of a library. For one thing, I wanted to show you the bare bones, because that looks more convincing. Core of the contracts implementation is, as you could see, no longer than ten lines of code. The second reason is that in previous demonstrations part of the audience was complaining that I am pursuing a lost cause, predicting slow and painful death to Code Contracts. I am very fond of that library, it is very smart and also complete, but current level of support truly doesn’t fuel optimistic feelings.

Q: How does this presentation apply to PostSharp?

A: PostSharp tool supports code contracts as an aspect. You can add attributes to method arguments and describe preconditions that must be satisfied (e.g. that an argument must be non-null). It also supports custom extensions so that you can widen the use of aspects provided by the tool.
The theory which I have demonstrated is more general than any tool (except Code Contracts) currently supports, and that stands for PostSharp as well. I have insisted on unconstrained version of the theory so that you can see the direction in which that is going. Tools are getting better with every year anyway.

Q: How to extend code in a way that client code will know that method does not return null or does not accept null as an argument for instance?

A: Expectations made by the method are called preconditions; promises made by the method are called postconditions. Failing to meet a precondition indicates a bug in the caller; failing to meet the postcondition indicates a bug in the called code. So much about terminology.
Preconditions and postconditions are part of documentation. You may wish to write unit tests which would document them in an executable way, but there is currently no way to rely on, say, language or Visual Studio about that.
There was an attempt to design a Visual Studio extension which would read Code Contracts and expose them as part of IntelliSense. That extension was unstable and I had to remove it from my copy of Visual Studio after trying it for some time. There are other similar attempts, but none which would make an impression.
There were requests to Microsoft to include contracts in Roslyn compiler, but the team has rejected that. It remains to wait for someone to develop an extension which would incorporate contracts validation into the build, I suppose.

Q: Are these given precondition contracts all we need, or do you use (many) different ones not shown here?

A: As in previous question, we also have postconditions – promises made by the method. For example, method should never return null, and then it asserts that the return value is non-null before exiting. Such postcondition tells callers that they don’t have to guard against null before accessing the result of our method – a useful hint indeed.
But generally, even if you decide not to use any tools, preconditions that I have shown in this demonstration are pretty much everything you might need. As any great idea, Design by Contract is very simple.
There is, however, one subtlety. Preconditions are inherited, so that derived classes are satisfying the Liskov Substitution Principle out of the box. It is forbidden to add more preconditions in the derived class. Now, that sounds easy when you have base and derived classes. The real problem is that all this stands for interface inheritance as well, and that is what makes Design by Contract messy in .NET.
Code Contracts library came with a powerful (and complicated) solution to contracts inheritance problem. You may refer to their documentation for details.

Q: Where can I get more instructions on using contracts?

A: The authoritative source of information on Design by Contract is Bertrand Meyer’s book Object-Oriented Software Construction. That is where Mr. Meyer has introduced and explained DbC theory in such terms that there is virtually nothing more to be added.

Q: Your idea of recovery is not technically sound... How this "separate" concern can work in multi-threaded environment?

A: Multithreading is another concern. It is not advisable to enforce thread safety on any given piece of code. It is better to implement thread safety as a separate class which wraps a non-safe component. In that way, code is much simpler and usually less error prone.

When things are put that way, it turns that contracts will remain in the component which doesn’t deal with threads and therefore it is 100% sound.
Take TPL as an example – threading was incorporated in Tasks and Task Managers, leaving logic intact. If you take a look at the way Code Contracts library is already handling async/await constructs, you will see that there is nothing missing in their solution.

Q: How practical it is to remove precondition from production code? What should your method returns in production if someone violate your preconditions for method?

A: Sometimes people decide to remove contracts checking from production code just for performance reasons. Note that contract clauses can also be viewed as part of a larger testing picture.
You can consider rigorous proofs as one level (which you run once – on paper), automated tests as another level (which you run sometimes), and then contract checks as the third safety valve (which you run every time the code executes). Now, it’s obvious that you can drop contract checks if you are pretty sure that automated tests have done the good job, or even that you have a formal proof that contract check will never fail.
In about one month from now a new course of mine will be published at Pluralsight – titled Writing Highly Maintainable Unit Tests. In that course I am explaining in great depth relation between formal proofs, unit tests and code contracts. For those of you having Pluralsight subscription, it might be useful to watch that course once it goes live.

Q: If we have checks/contracts on debug or staging, how would we not want that on production? Ex: checking to see if the students exists would have to be checked on production as well right?

A: This relates to previous question, where I have argued that code contracts are only one level of safety, though the most rigid one. If your code is tested well, then you don’t even have to put explicit contract checks into your code. However, I don’t think that any production code is tested enough to truly remove contract checks, because contract violation would then pass unnoticed and it could possibly damage data.
Therefore the conclusion. It pays to consider removing some of the costly contract checks. For example, remove quantifier which has O(N) complexity from methods with sub-O(N) complexity – like methods that have O(logN) or O(1) complexity. Leaving contract checks there would make the code observably slower. You probably don’t have to remove an O(N) contract check from a method which already has O(N) complexity or higher – like O(NlogN) or O(N^2). Contract check would then reduce performance by at most a constant factor, which we can survive.

Q: Wouldn't Debug.Assert be removed from Release build even without the #if DEBUG compiler directive?A: That is true in my example. I have included the conditional build just to show you the concept. But don’t forget that there is the Release version of assertions in .NET. Some people opt to assert in Release build as well. That makes sense in very sensitive code, where erroneous execution might cause unacceptable consequences.

Q: Is there any situation in which non-private custom Exceptions should be used?A: Exceptions remain valid solution in all exceptional situations. If you are writing a library, you would probably opt to throw a custom exception back to the caller, than to put a burden to the caller to have to use certain code contracts library (including your own).
However, inside your library, you could still be fine if you decide to institute contracts as the design strategy. That will at least save you from your own bugs, not related to any other code that might call your functions.
Other legitimate cases are already covered by the .NET Framework and other libraries and frameworks. Consider network exceptions as an example. Network communication is a typical example of the process which is full of exceptional cases, and that is where exceptions can be of great value.
Note, however, that there is one funny side of exceptions, which can give us a hint about when exceptions are a valid option. Although they are representing exceptional events, we always expect exceptions. We expect network exceptions when working with remote services. We expect database exceptions, like concurrent edit, deadlocks or timeouts. We expect IO exceptions when working with files. If you have a situation in which you actually do not expect anything exceptional to happen, than you will probably be better off if you avoid introducing an exception.

Q: Is it correct to say that catching or throwing exceptions in between the execution of a function is an anti-pattern?

A: Using exceptions to procure information or to alter control flow is definitely the anti-pattern. Just consider this case. You have caught a custom exception and you are ready to do what it says. Now – how do you know that the exception was thrown by the entity you expected? Exceptions can jump over activation frames. You are certainly not going to inspect call stack from the exception object to discover which function has thrown it.
This analysis can go much deeper than this. Maybe it is enough to think of catching specific exceptions as breaking encapsulation of the called code and knowing too much about its implementation. That is rigid and fragile and it breaks principles of OO programming - which is not the problem in itself, but then you won’t have any benefits of OO like polymorphic execution.

Q: Since preconditions have been rephrased as declarative code, can we use attributes to define contracts? Any frameworks for doing this?

A: PostSharp tool is defining contracts through use of attributes. However, keep in mind that attributes must be compile-time constant, and therefore you cannot pass just any expression as an attribute-based contract.
However, it is possible to cope with that (in theory). You could use static attribute to somehow point to another method which contains more elaborate contract verification code.

Q: Briefly, what was the purpose of the private ContractException?

A: Primary fear from throwing exceptions when precondition/postcondition is violated is that somebody might catch that exception and forget to rethrow it. In that way, operation might continue to run, even though we have just found sufficient reason to terminate it.
That is the reason why in Debug mode many developers opt to assert, i.e. to kill entire process, rather than throw an exception. But then, in production, killing the process is not the most user friendly behavior we could come up with, and for that reason we may decide to throw exceptions instead.
But then, we don’t want to throw an exception which can be explicitly listed in the catch block. We don’t want anyone to catch that exception for any reason. In order to catch a private exception, you must catch its base System.Exception instead. And it makes sense to expect that nobody will ever catch System.Exception deep inside code. That is the justification behind private exception class.

Q: If you want to access a resource such as database and you split it to two function: One to check whether there is a value, and another to fetch the value. This will use expensive resource twice, so maybe here return nullable value is ok?

A: Database access is not subject to Design by Contract. Database is to our code just another outer system and we are dealing with it with all precautions we would make in any other case. You have to catch exceptions coming out from the database because you have no idea what might go wrong there (like deadlocks or timeouts, or even plain failures such as corrupt index).

Then the question how to deal with a nonexistent value where it was expected becomes easier. You just query the database as it is. Then turn concrete data into concrete objects. And then those objects would be subject to Design by Contract. If an object requires a value, and you got nothing from the database, then don’t call the method and take a recovery course instead. Otherwise, if you try to invoke the method with null reference, just because database returned no rows, the called object would preserve right to explode.


About the speaker, Zoran Horvat

Matt Warren

After fifteen years in development and after leading a dozen of development teams, Zoran has turned to training, publishing and recording video courses for Pluralsight, eager to share practical experience with fellow programmers. Zoran is currently working as CEO and principal consultant at Coding Helmet Consultancy, a startup he has established to streamline in-house training and production of video courses. Zoran's blog.