Binding a Dependency Property of a View to its ViewModel

UPDATE 07/30/2014:
Please be sure to check out the second part to this at Binding a Dependency Property of a View to its ViewModel, part Deux which contains a working sample solution of the code here.

I like MVVM in concept and I had prepared a long, off-topic rant about MVVM because of a bit of trouble I’m having with it at the moment.  I deleted it, however.  Maybe I’ll make it an on-topic post at some point in the future.  Regardless, one of the issues I had was I needed to make a user control that could not only be the primary control of a view but I needed it to be a child control of another view.  There are a lot of complex operations that the view model controls in terms of handling states and progress bars.  It made sense, therefore, when I needed almost the exact same operations but with four different classes that inherit from the same model to use the same view.

To do this I needed a way to define a “ViewMode” of the user control.  For the default view where it would be the full version of the control the mode would be “Full” and for where I was using it as a child control the mode would be “Compact”.    Given that I think one of the things we should strive for is re-use it seemed like this should be an easy problem.  After some googling around though the general consensus seemed to be that you should just incorporate this into your new view model.  This just seems stupid to me.

Not about incorporating it into the view model.  That much is obvious but that there wasn’t some easy, obvious solution on how to bind a dependency property to a property in the view model.  Fortunately my StackOverflow foo seemed to be working with me and I found the right answer.

You have to manually bind your dependency property to the property on your view model.  It should have been obvious and I’m not sure why I hit on so many wrong answers but here is my solution:

Add the dependency property to MyView that will bind to the view model

public ViewMode ViewMode
{
	get { return (ViewMode)GetValue(ViewModeProperty); }
	set { SetValue(ViewModeProperty, value); }
}

public static readonly DependencyProperty ViewModeProperty =
	DependencyProperty.Register("ViewMode", typeof(ViewMode), typeof(MyView), new PropertyMetadata(ViewMode.Full));

I’ve defined an enum “ViewMode” that has two values, “Full” and “Compact” and I utilize it here.

Then in the ctor of MyView I have

public MyView()
{
	InitializeComponent();

	//http://stackoverflow.com/questions/15132538/twoway-bind-views-dependencyproperty-to-viewmodels-property
	string propertyInViewModel = "ViewMode";
	var bindingViewMode = new Binding(propertyInViewModel) { Mode = BindingMode.TwoWay };
	this.SetBinding(ViewModeProperty, bindingViewMode);
}

This manually sets the binding to a property “ViewMode” that is in my view model. So “ViewMode” exists in both the view and the view model and the manual binding will keep everything in sync.

In my XAML where I use the control as a stand-alone view the XAML looks like

<views:MyView Grid.Row="1" Margin="50" />

and in my XAML where I use the control as a child control the XAML looks like

<views:MyView Grid.Row="0" Grid.Column="0" ViewMode="Compact" />

MMVVVMVMI have also added some converters to help that bind the visibility of controls to the “ViewMode” of the view model. Now I have to point out that what I need to show and/or hide based on the ViewMode was fairly minimalistic. It might make more sense to have different control but in my case it made more sense to use the same control.

This is great and allows us to customize the view based on the ViewMode, but it doesn’t keep MyParentViewModel of the parent control in sync with MyViewModel of the child control when it’s being used as a child control. To do this we need to add another dependency property in MyView and bind it like we did the ViewMode. Then in MyParentView we have to bind that property to the property of MyParentViewModel in XAML.  The kind of crappy part is there is some manual work you have to do to make this work right.  Not only that but the binding works out to be fairly ugly.

The view model of “MyViewModel” looks like:

class MyViewModel
	ViewMode ViewMode
	ObjectGroup ActiveObject

The view model of “MyParentViewModel” looks like:

class MyParentViewModel
	ObjectGroup ActiveObjectOne
	ObjectGroup ActiveObjectTwo
	ObjectGroup ActiveObjectThree
	ObjectGroup ActiveObjectFour

In “MyView” I add the following dependency property:

public ObjectGroup ActiveObject
{
	get { return (ObjectGroup)GetValue(ActiveObjectProperty); }
	set { SetValue(ActiveObject, value); }
}

public static readonly DependencyProperty ActiveObjectProperty =
	DependencyProperty.Register("ActiveObject", typeof(ObjectGroup), typeof(MyView), new FrameworkPropertyMetadata(null, OnActiveObjectChanged));

private static void OnActiveObjectChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
	((MyViewModel)((MyView)d).DataContext).ActiveObject = (ObjectGroup)e.NewValue;
}

which is incredibly ugly. The problem is that when I do the binding on the dependency it directly calls SetValue and ignores my setter. As such I have to set things up with the property changed call-back to make everything tie together correctly.

Unfortunately I still need to add the manual binding to my view

propertyInViewModel = "ActiveObjectGroup";
var bindingActiveObjectGroup = new Binding(propertyInViewModel) { Mode = BindingMode.TwoWay };
this.SetBinding(ActiveObjectGroupProperty, bindingActiveObjectGroup);

Okay, so now everything works correctly right? Nope. The problem is that the binding on MyView sees the local data context, not the binding I want to give the control from MyParentView. As such I need to play with the binding to make sure we’re all on the same page.

The XAML basically ends up looking like

<UserControl x:Class="MyParentView">
	<UserControl.DataContext>
		<viewModels:MyParentViewModel />
	</UserControl.DataContext>
	<Grid>
		<Grid.RowDefinitions>
			<RowDefinition />
			<RowDefinition />
			<RowDefinition />
			<RowDefinition />
    		</Grid.RowDefinitions>
		<views:MyView Grid.Row="0"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectOne, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
		<views:MyView Grid.Row="1"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectTwo, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
		<views:MyView Grid.Row="2"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectThree, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
		<views:MyView Grid.Row="3"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectFour, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
	</Grid>
</UserControl>

MMVVVMVM2What we’re doing here is changing the default “ActiveObject” in the child control from the one created by its view model to the one created by the parent view model. This way everything is in sync due to the bindings we created in the constructor of “MyView”.

When I bind like I do above the ObjectGroup instances from MyParentViewModel end up being the same as the instance of ObjectGroup in the MyViewModel.

The cool thing about all this is that I can create a new instance of MyParentViewModel as needed and it will set everything up as it should.

And that’s it. Maybe this is one of those answers that is so obvious no one felt the need to write about it. Or maybe everyone’s found the same answer I did. Or maybe this is the wrong approach. After all, it’s not very “MVVM-like”, having to manually create the bindings and then having to manually set the ActiveObject in the dependency property. If you know of a better way to do this let me know.

Thanks,
Brian

Abstract_factory.svg

Abstract Factory

If you follow good design principles and good dev practices and utilize the APIs and SDKS Microsoft has made available within the .NET Framework, you don’t need to know anything about patterns.

There, I said it. You don’t need to know anything about patterns.

Now why would I think this? Well, a few years ago I interviewed for company here in Tucson and had one of the best interviews I’ve ever had. But there was some confusion and the position was in Mountain View, and I’m in Tucson. And I had to decline the position. I was incredibly disappointed. The company was great, but most of all the people I had met were great. It was the best of all worlds.

So a couple of months later another position opened up at the same company with another development group. I applied and was asked to come in for an interview. Unlike my previous interview, which was just an hour or so and had felt more like a bunch of engineers hanging out shooting the breeze, this interview as far more formal.

In the first of the five interviews for the day, all three of the software engineers has sheets of papers with questions. After introducing themselves they started on the questions read right from the sheet of paper. Eventually they got to a question on patterns which was pretty simple, “What do you know about design patterns?” I said, “Well, I know about them cursorily as I read about them in a few of the blogs I follow, and I know that are established solutions to common problems, but I can’t think of any patterns off the top of my head.” The person that asked the question looked flummoxed. I’d like to think it was because up until this question I had been answering pretty well.

But I couldn’t answer a question on patterns.

Template_Method_pattern_in_LePUS3

The second and third interviews proceeded in the same manner. They would show up, ask me questions randomly off of the sheets of paper, things seemed to go pretty well until they got to the patterns question. They all asked the patterns question, I always answered the same way and I always got the same flummoxed look. I finished up the last two interviews, with the department head and hiring manager and went home. I was contacted a couple weeks later saying they weren’t interested in hiring me. The only thing that I could point to as a problem was the questions about patterns.

Fine, I need to know patterns. And so I get the ultimate design patterns book, “Design Patterns: Elements of Reusable Object-Oriented Software” by a group of software engineers know colloquially as the Gang of Four. In fact, in Uncle Bob’s papers on SOLID he quotes from the gang of four several times calling them the GoF. Wonderful! I’ve been a success software engineer up until now and knowing all about these patterns is going to make me even better. Right?

The design patterns in this book are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.
Design Patterns: Elements of Reusable Object-Oriented Software, Section 1.1, What is a design pattern?,
Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

Okay, so the first chapter is all about what a design pattern is, and how you would select the patterns and when to use them. There’s also a description on MVC in SmallTalk. I mean, I use MVVM regularly as a part of my every day development cycle in UI development, which is an extension of MVC, so I guess it’s kind of cool (for archival purposes?). There is also a brief description of a each of the design patterns in this first chapter.

And there is where it hits me.  You don’t need to know design patterns.  Chances are if you don’t know anything about them and you’re developing in .NET you are already using design patterns and don’t even know it.

So let’s see what the hell I’m talking about:

Creational:

Structural:

Behavioral:

Well, I’ll be a monkey’s uncle, the majority of patterns presented by the gang of four I already use in some form. Additionally, both composite and facade patterns, as well as the state pattern, I’ve used as solutions when architecting applications without understanding them to be design patterns, as such. They simply seemed like the obvious answer.

So I’ve decided after reading all about design patterns I don’t need to know about them. Read them yourself. Buy Design Patterns: Elements of Reusable Object-Oriented Software and you’ll see you don’t need to know them. Read the links above and once you understand them you’ll see you too don’t need to know them.

I mean, come on. If I was a horrible software engineer I wouldn’t have accomplished what I have and wouldn’t hold the position I do now. Knowing design patterns won’t make a bad software engineer good. So conversely, not knowing the patterns won’t make a good software engineer bad, right? Didn’t Uncle Bob say something like this?

Following the rules on the paint can won’t teach you how to paint.

This is an important point. Principles will not turn a bad programmer into a good programmer. Principles have to be applied with judgement. If they are applied by rote it is just as bad as if they are not applied at all.

Having said that, if you want to paint well, I suggest you learn the rules on the paint can. You may not agree with them all. You may not always apply the ones you do agree with. But you’d better know them. Knowledge of the principles and patterns gives you the justification to decide when and where to apply them. If you don’t know them, your decisions are much more arbitrary.

Getting a SOLID start, Robert C. Martin

So I guess Uncle Bob didn’t quite say what I said. He said you should know the principles and patterns. They’re another tool in your toolbox. So why would I think I don’t need to know anything about patterns? How have I gotten to where I am without knowing patterns?

It’s Andy’s fault

I blame Andy. See, I worked under Andy at my last company. Not in .NET but in Java. Andy grokked patterns. He could instantly recognize a scenario and apply the right pattern. It was fluid. Code flowed together. Problems solved. With Andy it was about the application of theory. He was one of the most prolific software engineers I’ve ever known. But here is what will really blow your mind, it was quality, clean, well-designed code. He was a truly incredible engineer that I learned an incredible amount from.

500px-FactoryMethod.svg

Factory Method

I learned design patterns but without understanding them as design patterns. Under Andy I learned that given problem X do solution Y but understand there will be constraint Z. I learned this by working in Andy’s code, extending it, fixing bugs (yes, even the best occasionally have bugs), being a dwarf standing on the shoulders of a giant. And then writing my own code under Andy’s review, having him point out problems and solutions.  Okay, so maybe it’s not really his fault.

I took what I had learned under Andy and starting applying it to doing development in .NET, recognizing parts of the framework that fit to a given pattern and applying it as the correct solution. When I use events in WinForms dev do I need to know that it is the Observer pattern? When I use a DataContractSerializer to write out files for serialized objects do I need to know that this is the Memento pattern? When I use a command in MVVM do I need to know it’s part of the Command pattern?

But ultimately this is the flaw to my argument.

  • It presupposes that we all work in .NET environment.
  • That we’re all developers who work in such a limited scope.
  • That we don’t need to think outside of the tray of ideas Microsoft has provided.
  • That Microsoft has provided for all problems.

Microsoft has applied design patterns to arrive at solutions that try and make our jobs easier but it doesn’t solve all my problems. As a software engineer I should be expected to be able to apply those ideas to any language and environment. Limiting myself to just the .NET environment does a disservice to myself. I am not merely a code monkey. I do more than just write code. I engineer systems. To do so I must understand design principles and patterns and I must be able to apply design principles and patterns in such a manner that makes the use and extension of that code easy to work with and maintain and that strives for a minimum of deficits.

So to bring this full circle, I had a bad interview, boo hoo. In the first interview it was more about how I would solve different scenarios and I gave solutions that I would later understand to be patterns. In the second interview it was a bad format with bad questions. I was blessed with a mentor who guided my early career in such a manner that I was taught sound design principles and patterns. Unfortunately we are not all blessed. And that is why you need to know design patterns.

Good design principles and patterns aren’t nearly as rampant as one would hope.

Start being part of the solution, understand, use and apply design principles and patterns.  Make your life easier.  Which by extension makes my life easier.

Thanks,
Brian

Image credits:
Abstract Factory
Template Method
Factory Method

Expanding on breakpoints

Originally I had a few posts planned to go over all the functionality of breakpoints. I’m surprised by how many of my fellow developers don’t understand the full range of abilities that breakpoints in Visual Studio provide. We all use breakpoints and most use conditional breakpoints but few seem to know about all the capabilities. I say, “originally I had a few points planned”, because while researching material for the post I ran across a series from Microsoft that goes over all the functionality of breakpoints. I don’t think I can expand further on what Microsoft has already written.

So without further ado, I would recommend you read,

To me I think the two must underutilized abilities of breakpoints are Function Breakpoints and Tracepoints.

Function breakpoints is really just putting a whole bunch of breakpoints across all of your code. For instance, referring you back to my series on the TPL and MVVM, I ended up with a bunch of samples all of which override “Run”. Say I wanted to step through all of the run methods to make sure everything is running as I expect? Well,

  1. just select the “New” dropdown in the breakpoint window
  2. select “Break at Function”
  3. enter “Run” as the function
  4. click “OK”
  5. click “All”
  6. click “OK”

and now breakpoints have been created on all the functions that matched that name. Of course a checkbox list is presented so I could individually select points in code rather than select all.

But say I was working on a bunch of UI stuff where there was an expected sequence of events to happen? And say that within that sequence, if I were to put in a regular breakpoint it would throw off the sequence so it no longer worked? Like if I was looking for or comparing mouse points or if the mouse was over another control, or had been moused out of a control? That is the perfect time for Tracepoints. Tracepoints output values to the debug window but optionally won’t actually stop (thus a tracepoint rather then a breakpoint). It’s kind of like putting in “Debug.WriteLine” but a whole lot cleaner, and it won’t accidentally get checked in.

Got any tips on breakpoints not mentioned in the posts above? Let me know.

Thanks,
Brian

SOLID – The Summary

Here is the list of all the posts in my series on SOLID.

SOLID – Getting Started and Source Material
SOLID – (SRP) The Single Responsibility Principle
SOLID – (SRP) Ignoring the rules on the paint can
SOLID – (OCP) The Open-Closed Principle
SOLID – (LSP) The Liskov Substitution Principle
SOLID – (ISP) The Interface Segregation Principle
SOLID – (DIP) The Dependency Inversion Principle

Going through this series has been fun. By far and way my favorite principle has to be the LSP. I think it’s because not only does it require an understanding of good OOD but also requires that you understand how your chosen language can affect different aspects of that OOD. As always I would encourage you to read the source material from Uncle Bob as there are some aspects he goes further in detail.

On a related side-note, given how derivative these posts were I did seek and get approval from Uncle Bob for this series where he said, “I am flattered. Please feel free to derive from my work so long as you provide appropriate citings.”

I originally had a new series on patterns scheduled but I think I’m going to make an executive decision and move those aside for a couple of posts on break-points.

Thanks,
Brian

SOLID – (DIP) The Dependency Inversion Principle

Previous post in this series:
SOLID – (ISP) The Interface Segregation Principle

A. HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS

B. ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS.

The Dependency Inversion Principle, Robert C. Martin

The DIP is part and parcel with the OCP and LSP. Let’s start with a simple bit of source code based on Uncle Bob’s work.

Example 1: Copy Program (based on Figure 1 and Listing 2 of source material)

public class ReadKeyboard
{
	public string Read()
	{
		return Console.ReadLine();
	}
}

public enum OutputDevice { Printer, File }

public class CopyToDevice
{
	public void Copy(OutputDevice Device)
	{
		ReadKeyboard rk = new ReadKeyboard();
		while (true)
		{
			string result = rk.Read();
			if (result == string.Empty)
				break;
			if (Device == OutputDevice.File)
				WriteToFile(result);
			else if (Device == OutputDevice.Printer)
				WriteToPrinter(result);
		}
	}

	private void WriteToPrinter(string result)
	{
		/* throw new NotImplementedException(); */
	}

	private void WriteToFile(string result)
	{
		/* throw new NotImplementedException(); */
	}
}

It should be obvious now that this violates the OCP. Our CopyToDevice is dependent on ReadKeyboard and only gets input from the keyboard. Not only that but anytime we want to support a new output device we have to change CopyToDevice to support it. If our high level module, CopyToDevice, were to utilize abstractions rather then being dependent on the low level modules (i.e. ReadKeyboard, OutputDevice) then we wouldn’t have to worry about violating the OCP. Of course to do this the low level modules would have to implement abstractions that we could use in the high level, which therefore proves point A in the definition of the DIP.

Below is a solution that does not violate the OCP and adheres to the DIP.

Example 2: The OO Copy Program (based on Figure 2 and Listing 3 of source material)

public abstract class Reader
{
	public abstract string Read();
}

public abstract class Writer
{
	public abstract bool Write(string Value);
}

public class KeyboardReader : Reader
{
	public override string Read()
	{
		return Console.ReadLine();
	}
}

public class CopyToDevice
{
	public void Copy(Reader Reader, Writer Writer)
	{
		while (true)
		{
			string result = Reader.Read();
			if (result == string.Empty)
				break;
			Writer.Write(result);
		}
	}
}

I’ve left the higher level Writer as an exercise to the reader. CopyToDevice can work without be dependent on any specific writer or reader and won’t have to be modified anytime new devices are added. As Uncle Bob would say, “There will be no interdependencies to make the program fragile or rigid. And Copy() itself can be used in many different detailed contexts. It is mobile.”

Here is another sample relating to abstracting away the details so that your code doesn’t get locked into rigidity.

Example 3: Naive Button/Lamp Model (based on Figure 5 and Listing 5 of source material)

public class Lamp
{
	public void TurnOn()
	{
		ActivateElectricity();
	}

	public void TurnOff()
	{
		DeactivateElectricity();
	}

	public bool IsActivated { get; private set; }

	private void ActivateElectricity() { throw new NotImplementedException(); }
	private void DeactivateElectricity() { throw new NotImplementedException(); }
}

public class Button
{
	Lamp lamp;
	public Button(Lamp Lamp)
	{
		this.lamp = Lamp;
	}

	public void ChangeDetected()
	{
		if (lamp.IsActivated)
			lamp.TurnOff();
		else
			lamp.TurnOn();
	}
}

What’s interesting to me is that the above isn’t necessarily wrong or bad. Again this gets down to ignoring the rules on the paint can. If you have a very small project with a very small scope and per the requirements you never need to do anything other then what is above then there is nothing wrong with it. But in most cases that won’t happen. The problems here are obvious, we need to abstract away a lot of the details.

Example 4: Naive Button/Lamp Model (based very loosely on Figure 6 and Listing 6 of source material)

public abstract class ButtonClient
{
	public abstract void TurnOn();
	public abstract void TurnOff();
	public abstract void Toggle();
}

public abstract class Button
{
	public ButtonClient ButtonClient { get; private set; }
	public Button(ButtonClient ButtonClient)
	{
		this.ButtonClient = ButtonClient;
	}

	public abstract bool GetState();

	public virtual void ChangeDetected()
	{
		if (GetState())
			ButtonClient.TurnOff();
		else
			ButtonClient.TurnOn();
	}
}

public class Lamp : ButtonClient
{
	public override void TurnOn() { throw new NotImplementedException(); }

	public override void TurnOff() { throw new NotImplementedException(); }

	public override void Toggle()
	{
		if (IsActivated)
			TurnOff();
		else
			TurnOn();
	}

	public bool IsActivated { get; private set; }
}

public class ToggleButton : Button
{
	bool isDown;
	public ToggleButton(ButtonClient ButtonClient)
		: base(ButtonClient)
	{
		this.isDown = false;
	}

	public override bool GetState()
	{
		return isDown;
	}

	public override void ChangeDetected()
	{
		isDown = !isDown;
		this.ButtonClient.Toggle();
	}
}

Here we can see pretty clearly part B of the DIP that the details of the implementations are dependent on the abstractions.

To me, however, this last example is completely broken. It works under the assumption that a Button has a Lamp. And this doesn’t make any sense. Quite clearly a lamp has a button. I think this would be done cleaner with events (the observer pattern). This isn’t just because this is how it is actually done in the UI but because, again, the “has a” definition of objects.

Or maybe I’m over-analyzing this example. There is no doubt in my mind that this last example does a great job in demonstrating part B so maybe I just need to take it at that.

Again, higher level modules should not depend on abstractions and abstractions should not depend on details.

That’s it for the DIP and each of the individual principles. As I like to do, I’ll do a summary post next week with links to each of the posts in this series.

Thanks,
Brian

SOLID – (ISP) The Interface Segregation Principle

Previous post in this series:
SOLID – (LSP) The Liskov Substitution Principle

CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES THAT THEY DO NOT USE.

When clients are forced to depend upon interfaces that they don’t use, then those clients are subject to changes to those interfaces. This results in an inadvertent coupling between all the clients. Said another way, when a client depends upon a class that contains interfaces that the client does not use, but that other clients do use, then the client will be affected by the changes that those clients force upon the class. We would like to avoid such couplings where possible, and so we want to separate the interfaces where possible.

The Interface Segregation Principle, Robert C. Martin

Unlike the other posts in this series I’m not going to include any code. It’s a theory only post. Uncle Bob’s material on the ISP, while good at explaining the ISP, has what I consider pretty poor code examples. In his other papers I understand how the examples of bad code could come about. For some reason I just find it hard to wrap my head around the bad code he demonstrates for the ISP. In his explanation of the bad code he even goes on to say, “Although this solution is common, it is not without problems.” But his example is so bad, how could it be common in OOD? Read his paper and tell me if you don’t agree with me. Regardless, know that even if the example is poor, the reasoning and purpose of the ISP is solid. (See what I did there? 🙂

The first thing to note on Uncle Bob’s quote above is that by interfaces Uncle Bob doesn’t mean only “interface” as in the C# keyword whereby we define a contract that the class will adhere to but also any base or abstract classes we extend from. Naturally than, if there is some base class we extend from that extends from another class (ad nauseam) that extends from some abstract class we are getting a lot of functionality but also a lot of overhead with each class. That is not to say that this is invalid but at each extension you have to understand that you are adding to the class and may be violating the SRP, the OCP and the LSP.

What the ISP is trying to correct is the injection of so much functionality into a single class that you end up with impacting the internal code causing the class to have to implement changes that override the original purpose of the class. So now, you may not have only violated the SRP but you risk violating the LSP.

This principle deals with the disadvantages of “fat” interfaces. Classes that have “fat” interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken up into groups of member functions. Each group serves a different set of clients. Thus some clients use one group of member functions and other clients use the other groups.

The ISP acknowledges that there are objects that require non-cohesive interfaces; however it suggest that clients should not know about them as a single class. Instead, clients should know about abstract base classes that have cohesive interfaces. Some languages refer to these abstract base classes as “interfaces”, “protocols” or “signatures”.

The Interface Segregation Principle, Robert C. Martin

What we’re doing is trying to prevent so much downward pressure upon the purpose of a class from the clients that use it we end up making the class worthless because to make any changes to it would completely break any clients using it. Here’s the thing about SOLID, its purpose is to make your job easier. That may not be obvious. There is a lot of concepts here built from Uncle Bob’s experience (concepts that have proven useful in my own experience). What this means is that by extension, if you adhere to these concepts, than if I’m ever on a project your on, my job will be easier. All this is about trying to make our jobs easier.

So how do we prevent downward pressure? Well, the first way is the “Adapter” pattern (aka a wrapper). There is a good example in C# of the adapter pattern on wiki. The purpose there is essentially to modify a class in such a way that we as a client can use it without impacting any other clients that use it. Understand that this is huge. We get any specialization that we need out of the class without having to worry about the LSP and the OCP.

The second way is to simply judiciously apply interfaces. Where we need them, if it makes sense, extend from a class and implement the interface. There is nothing wrong with this. There are perfectly valid instances where we need separate interfaces.

Finally, Uncle Bob recommends the above, but with multiple inheritance, an option not available to us in C#.

If you’re dying for some sort of source code (though I would recommend anyways) read Uncle Bob’s source material this post is based on.

SOLID – (LSP) The Liskov Substitution Principle

Previous post in this series:
SOLID – (OCP) The Open-Closed Principle

FUNCTIONS THAT USE POINTERS OR REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.

The importance of this principle becomes obvious when you consider the consequences of violating it. If there is a function which does not conform to the LSP, then that function uses a pointer or reference to a base class, but must know about all the derivatives of that base class. Such a function violates the Open-Closed principle because it must be modified whenever a new derivative of the base class is created.

The Liskov Substitution Principle, Robert C. Martin

To me a part of the LSP is about understanding the subtleties that result of a language trying to handle OOP. The LSP seems obvious, code should be able to use a base class without any need of knowing about any derived classes. This post will cover a subtle and specific violation of the LSP that happens in C++, C# and other OOP languages. As with other code in this series it derives from Uncle Bob’s source material, porting his C++ to C#.

To get started, let’s begin with the idea of a “Is-A” relationship. In OOD generally we define parent/child relationships with a “Is-A”. For instance, a car is a vehicle. This means that vehicle would be the root or parent object and car would be a child. Uncle Bob’s source material (as noted in the citation above) uses “a square is a rectangle” relationship to show violations of the LSP.

Example 1: Square and Rectangle, a More Subtle Violation (based on source material)

public class Rectangle
{
	public double Width { get; set; }
	public double Height { get; set; }
}

public class Square : Rectangle
{
	public new double Width
	{
		get { return base.Width; }
		set
		{
			base.Width = value;
			base.Height = value;
		}
	}

	public new double Height
	{
		get { return base.Height; }
		set
		{
			base.Width = value;
			base.Height = value;
		}
	}
}

The code above is pretty straight forward. A square is a rectangle, right? Therefore a square should inherit from a rectangle. But a square is a special kind of rectangle. Whereas a rectangle can have any length to it’s width or height, a square must have the same width and height. To ensure that, when setting the height and/or width the square class will make sure that everything is even. But since Width and Height aren’t virtual, we have to use the “new” keyword on the Width/Height in square. Let’s throw together some quick code to test our squares.

Example 1a: Testing squares and rectangles.

public class TestRectangles
{
	public void Test()
	{
		Square s = new Square();
		s.Width = 1; //Height and Width set to 1
		s.Height = 2; //Height and Width set to 2

		ExampleF(s);
	}

	public void ExampleF(Rectangle Rectangle)
	{
		Rectangle.Width = 32;
	}
}

In the beginning of the Test method everything goes as expected. In the ExampleF method is where things fall apart. Setting the width in the ExampleF, even when a square is passed in, will only set the width. In Rectangle, because Width/Height is not marked as virtual, they cannot be inherited. To make sure you understand the consequences of overriding a value that is not marked as virtual, the C# compiler will issue a warning and tell you to use the “new” keyword so you are aware of what you are doing. So extending the base class without having Height/Width as virtual violates the LSP since a square is not really a substitution for a rectangle. The TestRectangles class would have to know that a square is a square to ensure that Width/Height remain the same.

Fortunately this is an easy fix, let’s identify Width/Height as virtual so we can substitute a square anytime we would use a rectangle.

Example 2: Square and Rectangle, The Fix (based on source material)

 public class Rectangle
{
	public virtual double Width { get; set; }
	public virtual double Height { get; set; }
}

public class Square : Rectangle
{
	public override double Width
	{
		get { return base.Width; }
		set
		{
			base.Width = value;
			base.Height = value;
		}
	}

	public override double Height
	{
		get { return base.Height; }
		set
		{
			base.Width = value;
			base.Height = value;
		}
	}
}

There is nothing above that any of us hasn’t run into. We know that it’s really easy to violate the LSP when we “new” properties, so we fix the issue by marking Width/Height as virtual and truly override the properties. But, does this really make sense? Consider if I was a new software engineer and I didn’t really understand the subtleties of the LSP. Let’s add a method to our test class that anyone of us might write.

Example 2a: Testing squares and rectangles

public class TestRectangles
{
	public void Test()
	{
		Square s = new Square();
		s.Width = 1; //Height and Width set to 1
		s.Height = 2; //Height and Width set to 2

		ExampleF(s);
		ExampleG(new Square());
	}

	public void ExampleF(Rectangle Rectangle)
	{
		Rectangle.Width = 32; //Height and Width set to 32
	}

	public void ExampleG(Rectangle Rectangle)
	{
		Rectangle.Width = 5;
		Rectangle.Height = 4;

		Debug.Assert(Rectangle.Width * Rectangle.Height == 20);
	}
}

Here we have added “ExampleG”. The developer of this method made an assumption that I think any of us would. We should be able to set the width and height of a rectangle and get the area expected. But in this case the Assert will throw. So we’re back to a violation of the LSP where an operation that works on a Rectangle will not work on a Square.

Validity is not Intrinsic

This leads us to a very important conclusion. A model, viewed in isolation, can not be meaningfully validated. The validity of a model can only be expressed in terms of its clients. For example, when we examined the final version of the Square and Rectangle class in isolation, we found that they were self consistent and valid. Yet when we looked at them from the viewpoint of a programmer who made reasonable assumptions about the base class, the model broke down.

Thus, when considering whether a particular design is appropriate or not, one must not simply view the solution in isolation. One must view it in terms of the reasonable assumptions that will be made by the users of that design.

The Liskov Substitution Principle, Robert C. Martin

So what is the solution? Uncle Bob discusses that the issue here is that when considering the “Is-A” relationship you need to consider the behavior of the objects. If we’re going to treat child classes as the parent classes we need to understand the behavior of the objects. In the case of our Square, it does not behave like a Rectangle. By the literal definition a square is a rectangle. But for all practicality that doesn’t work.

Now, stepping away from the source material, we can force things to work by utilizing immutability, making it obvious to any users exactly how the object operates.

Example 3: Squares and Rectangles

public class Rectangle
{
	public double Width { get; private set; }
	public double Height { get; private set; }

	public Rectangle(double Width, double Height)
	{
		this.Width = Width;
		this.Height = Height;
	}
}

public class Square : Rectangle
{
	public Square(double Side)
		: base(Side, Side) {}
}

The above code works in that it allows us to treat a Square as a Rectangle. The LSP is held up. The problem here is that we’ve done it by removing any behavior. Remember that the problem with the original code was that a square behaved differently then a rectangle. So why not do this? Well, I have to fall back to the quote from above. Working in isolation were we rigidly apply the rules of OOD can actually lead to cases where we violate them. Through your own understanding and experience of the rules of OOD as well as those around you, you have to know when to ignore the rules on the paint can. In this instance there may very well be a reason to implement the code as it is. I can also come up with with several cases where this rigidity can cause future problems.

Uncle Bob’s source material discusses utilizing “Design By Contract” where we can define pre- and post- conditions that would have fallen apart with our samples above. It also goes into a a real example from Uncle Bob about where he had a problem with the LSP and actually ended up with a rather hackey solution that violates the LSP. As with all these posts covering the SOLID principles, I would encourage you to read the source material to get a bigger-picture understanding of the SOLID principles.

Thanks,
Brian

SOLID – (OCP) The Open-Closed Principle

Previous post in this series:
SOLID – SRP – Ignoring the rules on the paint can

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.

When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have to come to associate with “bad” design. The program becomes fragile, rigid, unpredictable and unreusable. The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works.

The Open-Closed Principle, Robert C. Martin

Again, like all the SOLID principles, this is straight-forward in its definition but more complex in its implementation. Let’s look at each of the areas this relates to so we can get a more through understanding of the issues.

Abstraction

First off we have to abstract any specific implementations away from the base class into the child classes.

Example 1: The “Shape” Abstraction done wrong (based loosely on the source reference)

public enum ShapeType { Circle, Square }
public abstract class Shape
{
	ShapeType _type;
	public ShapeType Type { get { return _type; } }

	protected Shape(ShapeType Type)
	{
		this._type = Type;
	}
}

public class Circle : Shape
{
	double _radius;
	public double Radius { get { return _radius; } }

	Point _center;
	public Point Center { get { return _center; } }

	public Circle(double Radius, Point Center)
		: base(ShapeType.Circle)
	{
		this._radius = Radius;
		this._center = Center;
	}
}

public class Square : Shape
{
	double _side;
	public double Side { get { return _side; } }

	Point _topLeft;
	public Point TopLeft { get { return _topLeft; } }

	public Square(double Side, Point TopLeft)
		: base(ShapeType.Square)
	{
		this._side = Side;
		this._topLeft = TopLeft;
	}
}

public class Canvas
{
	public void DrawAllShapes(List<Shape> Shapes)
	{
		foreach (Shape shape in Shapes)
		{
			switch (shape.Type)
			{
				case ShapeType.Circle:
					DrawCircle((Circle)shape);
					break;
				case ShapeType.Square:
					DrawSquare((Square)shape);
					break;
			}
		}
	}

	void DrawCircle(Circle Circle) { throw new NotImplementedException(); }
	void DrawSquare(Square Square) { throw new NotImplementedException(); }
}

The most obvious problem here is that you can’t extend Shape without making major modifications to Canvas to support other shape types. Not only would you have to make changes to “DrawAllShapes” but you would have to add new methods for each new type to draw it. Remember too that this is a fairly contrived case. In real code you would have switch cases all over the place trying to deal with each ShapeType that would end up being a serious case of spaghetti code. You shouldn’t have to make changes to dependent modules anytime you want to extend an existing class. In the same vein is the ShapeType, where anytime we add a new shape we would have to add a new ShapeType.

Example 2: OOD solution to Square/Circle problem. (based loosely on the source reference)

public abstract class Shape
{
	abstract public void Draw();
}

public class Circle : Shape
{
	double _radius;
	public double Radius { get { return _radius; } }

	Point _center;
	public Point Center { get { return _center; } }

	public Circle(double Radius, Point Center)
	{
		this._radius = Radius;
		this._center = Center;
	}

	public override void Draw() {/* Draw ourself */}
}

public class Square : Shape
{
	double _side;
	public double Side { get { return _side; } }

	Point _topLeft;
	public Point TopLeft { get { return _topLeft; } }

	public Square(double Side, Point TopLeft)
	{
		this._side = Side;
		this._topLeft = TopLeft;
	}

	public override void Draw() {/* Draw ourself */}
}

public class Canvas
{
	public void DrawAllShapes(List<Shape> Shapes)
	{
		foreach (Shape shape in Shapes)
		{
			shape.Draw();
		}
	}
}

We’ve removed the need to define a shape type and abstracted “Draw” away from canvas and into each class. This means that each class can be extended with its own draw method without having to modify DrawAllShapes. There a problem here however. What if you may need to define a property/member variable or method in such a way that is should be done as an abstract in the base class? Well, you suck it up, make changes to your unit tests to cover this new case and modify any and all classes affected by this change assuming you can. When you do this you risk braking functionality any clients are dependent on. Case in point, my sample model from my series on the TPL and MVVM. When I initially wrote my TPL sampler there was no need for a “ImageRequired” property as all samples I had envisioned used an image and there was no reason not to reset and reload the image before each sample was run. The problem arose that reloading the image each time was a resource heavy and IO blocking operation, especially on large files and I quickly came to samples where they didn’t need an image but instead did other operations to show how their functionality worked.

The first solution some developers might think to do is simply modify the top-level call where it resets and reloads the image with a case/switch such that if it is one type of class, reload the image, if it is another then don’t reload it. But this is very bad and actually violates another part of this principle I’ll discuss later. The solution was to add an abstract ImageRequired property to the base model and then go back to each of my models and add in this property so that it could be used without having to modify the code where the image for the samples was reset and reloaded.

Referring back to the source material it goes into further ways of achieving closure that I’ll leave as an exercise to the reader. The primary sample it contains is, “What if we have to draw shapes in a paticular order on our canvas?” and goes into how to achieve this. The end result is that, probably the best way to do this is order the classes based on a “OrderTable” where the classes are ordered by how they should be drawn. This way type is still abstracted away from the classes themselves and dependent modules don’t have to change but can rely on the “OrderTable”. OrderTable is still dependent on the class types but not on the classes themselves and so can operated independently. I know it sounds like a lot of handwaving to try and make this all work for functionality like this but having a single place that defines stuff like this that is independent can make maintenance a lot easier.

Heuristics and Conventions

There are a lot of “Good Dev Practices” that are done just to facilitate the OCP and Uncle Bob mentions a few of the more important ones. I’ll touch briefly on these but I would recommend reading the source material for a more in-depth coverage of each one.

Make all Member Variables Private

This where the argument that member variables should only be accessed via getters/setters comes from. This way the class that implements the member variable has control over it. We don’t want the potential that the meaning of what a variable is changes by the classes that use it external to the class that implements it. The source material provides an example to this end. In .NET this is made rather simple for us by using properties, though using “PropertyName{get;set;}” just exposes the member variable as if it were public. I argued in a post from over 6 years ago that we should strive for immutability. If you look at the classes in the Shape example above you will see that the classes are immutable with private member variables and public getters. It’s important to note as I’ve mentioned that just implementing properties with the default {get;set;} violates this principle as it just exposes the private member variable with no thought to how it is used or accessed.

No Global Variables — Ever

I have seen pretty consistently where the meaning of global variables changes over time. This means that early code uses a global variable in one manner but future code uses it in another manner. Not only that but we run into the problem where one class or module could change the variable in a way that is unexpected from other modules using it. It violates the OCP because by exposing the global we allow for it to be changed over time. This means that code that relies on the global in one manner will have to be changed if the meaning of the global changes over time. Uncle Bob does mention a case for Global Variables. Where the definition of those variables can’t change, like in cout and cin (or in C#, Console.Write() or Console.Read()). These are static global instances where they perform a functionality but we can’t change them.

The most consistent violation of this is the use of the Singleton pattern where there is but a single global reference to a resource (like Console). This is done intentionally with the idea that control over the resource is needed and more important (or more convenient). In the case of a singleton, the object should not be changed and therefore adheres to the OCP. I’ll cover the good and bad of Singleton when I do coverage on patterns.

RTTI is Dangerous

RTTI is run time type identification (RTTI). In C# it is the use of the “is” keyword or using “as” and checking for null.

Example 3: Using RTTI in Example 1 for our Canvas.DrawAllShapes()

public class Canvas
{
	public void DrawAllShapes(List<Shape> Shapes)
	{
		foreach (Shape shape in Shapes)
		{
			if (shape is Circle)
			{
				DrawCircle((Circle)shape);
			}
			else if (shape is Square)
			{
				DrawSquare((Square)shape);
			}
		}
	}
	
	void DrawCircle(Circle Circle) { throw new NotImplementedException(); }
	void DrawSquare(Square Square) { throw new NotImplementedException(); }
}

This is great because we eliminate the dependency on ShapeType. We’ve cleaned up the code a bit and made maintenance easier. So why is this bad? Because you will still have to modify Canvas for any new shapes that need to be added. Example 1 was an example of what not to do for a reason and by using RTTI all we’ve done is make it look like it should be okay to implement things poorly. So when is it okay to use RTTI?

Exmaple 4: Using RTTI in Example 2 where it does not violate the OCP (based loosely on the source reference)

public class Canvas
{
	public void DrawAllShapes(List<Shape> Shapes)
	{
		foreach (Shape shape in Shapes)
		{
			shape.Draw();
		}
	}

	public void DrawSquares(List<Shape> Shapes)
	{
		foreach (Shape shape in Shapes)
		{
			if(shape is Square)
				shape.Draw();
		}
	}
}

Here we’ve added “DrawSquares”. All we’re doing is drawing squares. It makes sense to verify that we have a square before we try and draw it. This doesn’t violate the OCP because even if the new shapes are added we don’t have to go back and modify “DrawSquares”. It will always do just what it says it will do.

That’s it on the OCP. As with all the principles there are times where you have to balance adhering to the rules with other considerations but when in doubt it’s generally better to follow the rules. Up next is the Liskov Substitution Principle.

Thanks,
Brian

SOLID – SRP – Ignoring the rules on the paint can

Previous post in this series:
SOLID – (SRP) The Single Responsibility Principle

Some of my source links in the previous two posts may not have worked in FireFox (but worked fine in IE and Chrome). These links have been fixed. It was an issue with how google was handling the redirects to the source files.

In Uncle Bob’s source material for SRP it mentions one specific example of where it doesn’t make sense to break out the responsibilities.

Here is a modified class based on the source material:

public class ConnectionManager<K, V>
{
	void Connect(K EndPoint);
	void Terminate();
	void Send(V Data);
	V Receive();
}

In the source material the object is of a modem with dial and hangup methods but this is a simplified version of that. You can see here that there are really two responsibilities in this interface. The first is that there is connection management. Connect and Terminate are one set of responsibilities that relate to handling the connection. Send and Receive don’t really have anything to do with handling the connection, they have to do with the data flow to/from the end point.

Here are the interfaces separated (based on source material):

public class ConnectionManager<K, V>
{
	public IConnection<K> Connection { get; set; }
	public IDataChannel<V> DataChannel { get; set; }
}
public interface IConnection<T>
{
	void Connect(T EndPoint);
	void Terminate();
}
public interface IDataChannel<T>
{
	void Send(T Data);
	T Receive();
}

Should these clearly different responsibilities need to be separated? You can read Uncle Bob’s answer in the source material. My answer? It’s a tough situation to define without a context. If this were just dealing with connecting via a single type of modem directly where we can think small I wouldn’t decouple. You end up with what Uncle Bob calls, “Needless Complexity.” A modem connects, sends and receives data back and forth and at some point disconnects. The code should be able to handle this cleanly.

Where the problem arises is that most of the time we aren’t dealing with such simple situations. If we do have a complex situation but we’ve implemented our code as in the first sample we end up with what Uncle Bob calls a, “smell of Rigidity.” For instance, what if we have a scenario where we need to send and receive multiple types? Do we create multiple connections even though the end points are the same? Are we going to have to support multiple DataChannels? In the first example trying to expand on the functionality becomes a pain and I often feel constrained in these cases.

All this comes down to a point I’ve emphasized here before. As stated in “Code Complete” one of the most important things you can do that will reap the most benefit is a thorough requirements analysis. If you fully understand the use cases you can develop for them. Then once you fully understand your requirements you can know if it makes sense to separate responsibilities.

Up next is the Open-Closed Principle (OCP).

Thanks,
Brian

SOLID – (SRP) The Single Responsibility Principle

Previous post in this series:
SOLID – Getting Started and Source Material

I’m sure most of us have taken an Object Oriented Programming (OOP) class in college (or will soon). What is important to understand is that an OOP class will teach you the fundamentals of understanding the principles of developing from an object-centric perspective. Uncle Bob’s SOLID principles takes those concepts from OOP and develops them further into object oriented design (OOD), how each object should be developed so that long term maintenance of software is easier, cleaner and ultimately cheaper.

The SRP is one of the simplest of the principles, and one of the hardest to get right. Conjoining responsibilities is something that we do naturally. Finding and separating those responsibilities from one another is much of what software design is really about. Indeed, the rest of the principles we will discuss come back to this issue in one way or another.

Agile Principles, Patterns, and Practices in C#, Robert C. Martin

SRP is pretty easy right? An object should only have one responsibility. As an example lets look at a Vehicle, the age old example of OOP classes everywhere. What is the responsibility of a vehicle? It is used to transport people and/or things.

What do we need to know about the vehicle so it can accomplish it’s responsibility?

  1. How many people or things it can hold?
  2. Is it capable of transporting those things?
    • Does it have at least one entry to allow for putting things in and out?
    • Does it have the ability to move (i.e. tires or sleds)?
    • Does it have a working means of propulsion?

What don’t we care about?

  1. How big is the engine?
  2. How does the engine work?
  3. What does it look like?
  4. How many tires does it have (if any)?
  5. What kind of tires are they?

As Uncle Bob mentions, we naturally want to conjoin responsibilities. We want to put everything in the vehicle and call it a day. But a vehicle shouldn’t define what an engine is, how it works and what it does. It may define how it uses that engine but the engine it’s self shouldn’t be defined within the vehicle.

That’s an important part to the SRP. It doesn’t say an object can’t contain other objects that facilitate it’s responsibility. An engine isn’t a vehicle and a vehicle isn’t an engine. A vehicle shouldn’t define what an engine is within it’s self. There is nothing wrong, however, with it have a Engine property.

To try and make this a bit clearer:

The Single Responsibility Principle (SRP) says that a class should have one, and only one, reason to change. To say this a different way, the methods of a class should change for the same reasons, they should not be affected by different forces that change at different rates

SRP in Ruby, Robert C. Martin

This (slightly modified) code sample from Microsoft on rectangles gives a good example of this:

<Window x:Class="Wpf_Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow">
    <Canvas>
        <Path Stroke="Black" StrokeThickness="1" Fill="LemonChiffon">
            <Path.Data>
                <RectangleGeometry>
                    <RectangleGeometry.Rect>
                        <Rect X="10" Y="100" Width="150" Height="100" />
                    </RectangleGeometry.Rect>
                </RectangleGeometry>
            </Path.Data>
        </Path>
    </Canvas>
</Window>

All this does is draw a rectangle with the class RectangleGeometry. What is important here is that there is a property, Rect, that defines the the properties of where a rectangle is and how big it is. The struct, Rect, has a bunch of operations that have nothing to do with drawing a rectangle on the canvas, methods like IntersectsWith(Rect) and Union(Rect). Whereas RectangleGeometry has Freeze() and GetRenderBounds() that have to do with drawing the rectangle on the screen but have nothing to do with directly working with rectangles. Thus a RectangleGeometry has a Rect property to take care of these things.

So know we have the instructions on the paint can. But when do not listen to them? That’s up in the next post.

Thanks,
Brian