Archives for : C#

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

SOLID – Getting Started and Source Material

This next series will follow the principles of SOLID, “five basic principles of object-oriented programming and design.”

The concepts as collated into SOLID was organized by a gentleman named Robert C. Martin who has what may be one of my favorite quotes in software engineering:

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

Why is this one of my favorites? I’ll get to that in the future (when I get to patterns).

I will be referring to Robert C. Martin through out these posts as Uncle Bob. This isn’t intended to imply any familiarization between myself and Uncle Bob, nor any familial relationship. In fact, quite the opposite, I’ve never met Uncle Bob. But Uncle Bob self identifies as “Uncle Bob” using it for his old blog, as a twitter handle (@UncleBobMartin), and for his email. I figure he wants us to call him Uncle Bob, so why not?

Here are the references I’ll be utilizing on the posts covering each of the SOLID principles (ripped almost literally from Uncle Bob’s own post on object oriented design):

Design Principles and Design Patterns Uncle Bob’s initial paper discussing SOLID without naming it as such. Covers all the SOLID principles except “The Single Responsibility” principle.
SRP The Single Responsibility Principle A class should have one, and only one, reason to change.
OCP The Open Closed Principle You should be able to extend a classes behavior, without modifying it.
LSP The Liskov Substitution Principle Derived classes must be substitutable for their base classes.
ISP The Interface Segregation Principle Make fine grained interfaces that are client specific.
DIP The Dependency Inversion Principle Depend on abstractions, not on concretions.

Needless to say, the vast majority of the content for this series will be based on Uncle Bob’s writings. I will try to make it clear the content that belongs to Uncle Bob and content that belongs to me and cite appropriately as I’ve done for posts in the past when I reference someone else’s work. This series is a case of “dwarfs standing on the shoulders of giants” taking Uncle Bob’s work and extending it to encapsulate my own experience with each of these topics.

So coming next week will be the first SOLID principle, “The Single Responsibility Principle”.

Thanks,
Brian

The Task Parallel Library Sampler – Part 14: Wrap-up / Future posts

This has been a fun journey and hopefully you’ve learned a bit about MVVM and the TPL. I do have plans for future posts in this series that will center around the TPL.Dataflow namespace. It’s an area of the TPL I don’t seem written about a lot and I think there are probably a few posts that would benefit you.

My next series of posts, however, is on the SOLID principles of good object-oriented programming and design. Often when it comes to concepts like design patterns and MVVM we can’t see the forest from the trees and we get lost in the concepts. The awesome thing about SOLID is that it is so straight-forward that all of us should have a thorough understanding of it.

After SOLID, I have a series planned on design patterns. I won’t cover all the design patterns but will hit on quite a few of them. I also have a post planned on the patterns you don’t really care about if you apply fundamental .net development concepts and practices as the patterns are incorporated into those practices. This will relate to patterns like lazy initialization, object/thread pool, factory method and dependency injection, observer, locking and scheduling, all of which I have hit on in some form or another in assorted posts here while not necessarily calling them out as such patterns.

I always welcome your feedback and allow anonymous comments so feel free to comment on anything. Spam and off-topic/inappropriate comments are and always will be removed.

Full series of posts:
Part One: Starting with MVVM
Part Two: The MVVM solution structure and basic framework
Part Three: Base Classes
Part 4: Sampler View, View Model and Model
Part 5: Running and working with the TPL samples
Part 6: Parallel.For Sample
Part 7: Using Parallel.For effectively
Part 8: Adding a New Sample, Matrices Multiplication
Part 9: Basic Exception handling with the AggregateException
Part 10: Loop control of the Parallel.For and .ForEach
Part 11: Cancelling Threads with the CancellationTokenSource – The MVVM
Part 12: Cancelling Threads with the CancellationTokenSource – The Code
Part 13: Async/Await

Thanks,
Brian