Agile Principles, Patterns, and Practices in C#

Robert C. Martin, Micah Martin

Mentioned 35

Comprehensive, pragmatic tutorial on Agile development for C# programmers from one of the founding fathers of Agile programming.

More on Amazon.com

Mentioned in questions and answers.

MVVM is most commonly used with WPF because it is perfectly suited for it. But what about Windows Forms? Is there an established and commonly used approach / design pattern like this for Windows Forms too? One that works explicitly well with Windows Forms? Is there a book or an article that describes this well? Maybe MVP or MVC based?

I have tried MVP and it seems to work great with windows forms too. This book has an example of windows forms with MVP pattern (sample payroll application). The application is not that complex but will give you an idea about how to go about creating it.

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

You can get the source code at Source Code

EDIT:

There are two variations of the MVP pattern (a) Passive view and (b) supervising controller

For complex databinding scenarios I prefer to go with the Supervising controller pattern. In supervising controller pattern the databinding responsibility rest with the view. So,for treeview/datagrid this should be in the respective views, only view agnostic logic should moved on to the presenter.

I'll recommend having a look at the following MVP framework MVC# - An MVP framework

Don't go by the name (it's an MVP framework).

Simple winforms MVP video Winforms - MVP

An example of dealing with dropdown list MVP - DropDownList

Simple treeview binding example (poor man's binding). You can add any treeview specific logic in BindTree().

Below is the code snippet.... not tested, directly keyed in from thought....

public interface IYourView
{
   void BindTree(Model model);
}

public class YourView : System.Windows.Forms, IYourView
{
   private Presenter presenter;

   public YourView()
   {
      presenter = new YourPresenter(this);
   }

   public override OnLoad()
   {
         presenter.OnLoad();
   }

   public void BindTree(Model model)
   {
       // Binding logic goes here....
   }
}

public class YourPresenter
{
   private IYourView view;

   public YourPresenter(IYourView view)
   { 
       this.view = view;
   }

   public void OnLoad()
   {
       // Get data from service.... or whatever soruce
       Model model = service.GetData(...);
       view.BindTree(model);
   }
}

What are the differences between Strategy design pattern and State design pattern?

I was going through quite a few articles on the web but could not make out the difference clearly.

Can someone please explain in layman's terms?

Both patterns delegate to a base class that has several derivative, but it's only in the State pattern that these derivative classes hold a reference back to context class.

Another way to look at it is that the Strategy pattern is a simpler version of the State pattern; a sub-pattern, if you like. It really depends if you want the derived states to hold references back to the context or not (i.e: do you want them to call methods on the context).

For more info: Robert C Martin (& Micah Martin) answer this in their book, "Agile Principles, Patterns and Practices in C#". (http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258)

Can somebody please explain in layman's terms?

Design patterns are not really "layman" concepts, but I'll try to make it as clear as possible. Any design pattern can be considered in three dimensions:

  1. The problem the pattern solves;
  2. The static structure of the pattern (class diagram);
  3. The dynamics of the pattern (sequence diagrams).

Let's compare State and Strategy.

Problem the pattern solves

State is used in one of two cases [GoF book p. 306]:

  • An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
  • Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.

If you want to make sure you indeed have the problem the State pattern solves, you should be able to model the states of the object using a finite state machine. You can find an applied example here.

Each state transition is a method in the State interface. This implies that for a design, you have to be pretty certain about state transitions before you apply this pattern. Otherwise, if you add or remove transitions, it will require changing the interface and all the classes that implement it.

I personally haven't found this pattern that useful. You can always implement finite state machines using a lookup table (it's not an OO way, but it works pretty well).

Strategy is used for the following [GoF book p. 316]:

  • many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.
  • you need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms [HO87].
  • an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
  • a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

The last case of where to apply Strategy is related to a refactoring known as Replace conditional with polymorphism.

Summary: State and Strategy solve very different problems. If your problem can't be modeled with a finite state machine, then likely State pattern isn't appropriate. If your problem isn't about encapsulating variants of a complex algorithm, then Strategy doesn't apply.

Static structure of the pattern

State has the following UML class structure:

PlantUML class diagram of State Pattern

Strategy has the following UML class structure:

PlantUML class diagram of Strategy Pattern

Summary: in terms of the static structure, these two patterns are mostly identical. In fact, pattern-detecting tools such as this one consider that "the structure of the [...] patterns is identical, prohibiting their distinction by an automatic process (e.g., without referring to conceptual information)."

There can be a major difference, however, if ConcreteStates decide themselves the state transitions (see the "might determine" associations in the diagram above). This results in coupling between concrete states. For example (see the next section), state A determines the transition to state B. If the Context class decides the transition to the next concrete state, these dependencies go away.

Dynamics of the pattern

As mentioned in the Problem section above, State implies that behavior changes at run-time depending on some state of an object. Therefore, the notion of state transitioning applies, as discussed with the relation of the finite state machine. [GoF] mentions that transitions can either be defined in the ConcreteState subclasses, or in a centralized location (such as a table-based location).

Let's assume a simple finite state machine:

PlantUML state transition diagram with two states and one transition

Assuming the subclasses decide the state transition (by returning the next state object), the dynamic looks something like this:

PlantUML sequence diagram for state transitions

To show the dynamics of Strategy, it's useful to borrow a real example.

PlantUML sequence diagram for strategy transitions

Summary: Each pattern uses a polymorphic call to do something depending on the context. In the State pattern, the polymorphic call (transition) often causes a change in the next state. In the Strategy pattern, the polymorphic call does not typically change the context (e.g., paying by credit card once doesn't imply you'll pay by PayPal the next time). Again, the State pattern's dynamics are determined by its corresponding fininte state machine, which (to me) is essential to correct application of this pattern.

I'm a confused newbie and hobbyist programmer trying to get a grip on this, so forgive me if my question is a little off or doesn't make much sense.

I see a lot of questions on SO revolving around the use of design patterns, and I'm wondering if anyone has a good resources for learning about, and implementing design patterns? I understand the general idea, and know how/when to use a couple of them(Singletons, Factory methods) but I know I'm missing out.

(Just in case it matters, my language of preference is C# but I could learn from examples in other languages)

Applying UML and Patterns by Craig Larman. Start from the basic of analysis, design and uses a simple Case scenario. Introduces most of the basic patterns in a simple way.

An introductory book that I found useful and well written is Design Patterns Explained by Alan Shalloway and James Trott (Addison Wesley).

alt text

Do not start from the Gang of Four book, for it is not an introductory book by any means.

The original Design Patterns book is a must-read for all programmers.

It is an excellent book on every level: layout, clarity, insight, depth. It's one of those great books that you first read cover-to-cover, and then use as a reference until you literally know it inside out.

You could start by the Wikipedia page, but treat yourself with the great book too.

Design patterns are great for various reasons:

  1. gives you a starting for solving common problems.
  2. gives developers a vocabulary to talk about certain ways of solving problems in a very compact manner.
  3. when working with developers who know design patterns and you use design patterns in your solutions they will understand the solutions a lot faster.

But when your goal is just to learn design patterns I think you are missing the fundamentals. All design patterns are based on more common principles. High Cohesion, Low Coupling Open Closed Principle, DRY, Liskov Substitution Principle etc. For these fundamentals I would read the following books in this order:

  1. Head First Object-Oriented Analysis and Design (Head First) [ILLUSTRATED] (Paperback)
  2. Applying UML and Patterns (Hardcover)
  3. Agile Principles, Patterns, and Practices in C# (Robert C. Martin Series) (Hardcover)

After that you are ready for the basic gang of four design patterns

  1. Head First Design Patterns (Head First) [ILLUSTRATED] (Paperback)
  2. The BIBLE
  3. A nice website (don't buy anything, it is not worth it) http://dofactory.com/Patterns/Patterns.aspx (some implementations of this site are worth a discussion

The next step:

  1. Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series) (Hardcover)
  2. The POSA books

And always remember : the pattern is not the goal !

Before spending money on books I would recommend Wikipedia's excellent design patterns page. Also for something different Google for "design pattern screencasts" or search for "design patterns" on YouTube. Getting the same information presented differently often helps the penny drop.

The Gang of Four book is the definitive text on the most well known patterns but is not that easy to read and with C++ examples not everyone's favourite.

The Head First Design Patterns text is far more accessible but only contains a subset of the Gang of Four patterns.

The most important thing is to understand where and why a particular pattern is useful. Afterwards search the web for implementation examples in the language of your choice and experiment until you "get it". Understand one pattern before moving on to the next. Everyone understands some patterns better than others (and there are hundreds of lesser known ones).

Just keep plugging away.

Head First Design Patterns

alt text

and the Design Pattern Wikipedia page are the best resources for beginners. FluffyCat is another good, free online resource for design patterns in both Java and PHP.

The Gang of Four book is where to go afterward, but it's fairly advanced, so I'd wait until you have a pretty firm grasp from the other resources.

I'd add that Design Patterns book from the "Gang of four" is a bible for anyone who is seriously interested in design patterns.

It feels like an artifacts of an earlier days, but UML sure does have its use. However, agile processes like Extreme Programming advocates "embracing changes", does that also means I should make less documents and UML models as well? Since they gives the impression of setting something in stone.

Where does UML belongs in an Agile development practice? Other than the preliminary spec documents, should I use it at all?

EDIT: Found this: Potential artifacts for agile modeling

Breeze through Robert Martin's Agile Principles, Patterns and Practices

  • The suggestion is to use UML to communicate designs within the team.. a shared language ; anyone taking a look at the diagram can understand the solution (faster than talking about it) and contribute quicker.
  • If you find the team making the same diagrams over and over again, someone will make a good version and store it on the wiki / source control. Overtime the more useful diagrams will start to collate in that place.
  • Don't spend too much time on it... you don't need too much detail. Models are built in the architectural / construction realms because building a house to validate-test the design is expensive/infeasible. Software is not like that - you could validate your design by just coding it up in the time you make a UML model of your untested design (with all the bells and whistles).

So says UncleBob... I concur.

For a very well thought out and expressed view on this topic read Martin Fowler's "Is Design Dead?" and if that convinces you, buy/borrow and read Scott Ambler's Agile Modelling.

In a nutshell, UML is a useful tool but don't over use it/abuse it; it's for thinking, as well as documenting but the code is the ultimate (though not only) expression of the design - the executable design. To this end, the team should do the architecture and design. Finally, use whatever tools to do it that helps (i.e. whiteboards and pens and digital cameras are great - you don't need a CASE tool)

I know about "class having a single reason to change". Now, what is that exactly? Are there some smells/signs that could tell that class does not have a single responsibility? Or could the real answer hide in YAGNI and only refactor to a single responsibility the first time your class changes?

Martin's Agile Principles, Patterns, and Practices in C# helped me a lot to grasp SRP. He defines SRP as:

A class should have only one reason to change.

So what is driving change?

Martin's answer is:

[...] each responsibility is an axis of change. (p. 116)

and further:

In the context of the SRP, we define a responsibility to be a reason for change. If you can think of more than one motive for changing a class, that class has more than one responsibility (p. 117)

In fact SRP is encapsulating change. If change happens, it should just have a local impact.

Where is YAGNI?

YAGNI can be nicely combined with SRP: When you apply YAGNI, you wait until some change is actually happening. If this happens you should be able to clearly see the responsibilities which are inferred from the reason(s) for change.

This also means that responsibilities can evolve with each new requirement and change. Thinking further SRP and YAGNI will provide you the means to think in flexible designs and architectures.

Lately I am losing my trust in OOP. I have already seen many complaints about common OOP misuses or just simple overuse. I do not mean the common confusion between is-a and has-a relationship. I mean stuff like the problems of ORM when dealing with relational databases, the excessive use of inheritance from C# and also several years of looking at code with the same false encapsulation belief that Scott Meyers mentions in the item 23 of Effective C++

I am interested in learning more about this and non OOP software patterns that can solve certain problems better than their OOP counterparts. I am convinced that out there there are many people giving good advice on how to use this as an advantage with non pure OOP languages such as C++.

Does anyone knows any good reference (author, book, article) to get started?

Please, notice that I am looking for two related but different things:

  • Common misuses of OOP concepts (like item 23)
  • Patterns where OOP is not the best solution (with alternatives)

Well I can recommend you a book Agile Principles, Patterns, and Practices in C#. Examples are in C# of course, but the idea of the book is universal. Not only it covers Agile but also focuses on bad practices and shows in examples how to convert bad code to a good code. It also contains descriptions of many design pattern and shows how to implement them in semi-real example of Payroll application.

We are following Domain Driven Design for the implementation of a large website.

However by putting the behaviour on the domain objects we are ending up with some very large classes.

For example on our WebsiteUser object, we have many many methods - e.g. dealing with passwords, order history, refunds, customer segmentation. All of these methods are directly related to the user. Many of these methods delegate internally to other child object but
this still results in some very large classes.

I'm keen to avoid exposing lots of child objects e.g. user.getOrderHistory().getLatestOrder().

What other strategies can be used to avoid this problems?

The issues you are seeing aren't caused by Domain Driven Design, but rather by a lack of separation of concerns. Domain Driven Design isn't just about placing data and behavior together.

The first thing I would recommend is taking a day or so and reading Domain Driven Design Quickly available as a free download from Info-Q. This will provide an overview of the different types of domain objects: entities, value objects, services, repositories, and factories.

The second thing I would recommend is to go read up on the Single Responsibility Principle.

The third thing I would recommend is that you begin to immerse yourself in Test Driven Development. While learning to design by writing tests first won't necessarily make you designs great, they tend to guide you toward loosely coupled designs and reveal design issues earlier.

In the example you provided, WebsiteUser definitely has way too many responsibilities. In fact, you may not have a need for WebsiteUser at all as users are generally represented by an ISecurityPrincipal.

It's a bit hard to suggest exactly how you should approach your design given the lack of business context, but I would first recommend doing some brain-storming by creating some index cards representing each of the major nouns you have in your system (e.g. Customer, Order, Receipt, Product, etc.). Write down candidate class names at the top, what responsibilities you feel are inherent to the class off to the left, and the classes it will collaborate with to the right. If some behavior doesn't feel like it belongs on any of the objects, it's probably a good service candidate (i.e. AuthenticationService). Spread the cards out on the table with your colleges and discuss. Don't make too much of this though, as this is really only intended as a brainstorming design exercise. It can be a little easier to do this at times than using a whiteboard because you can move things around.

Long term, you should really pick up the book Domain Driven Design by Eric Evans. It's a big read, but well worth your time. I'd also recommend you pick up either Agile Software Development, Principles, Patterns, and Practices or Agile Principles, Patterns, and Practices in C# depending on your language preference.

I have used OO programming languages and techniques years ago (primarily on C++) but in the intervening time haven't done much with OO.

I'm starting to make a small utility in C#. I could simply program it all without using good OO practice, but it would be a good refresher for me to apply OO techniques.

Like database normalization levels, I'm looking for a checklist that will remind me of the various rules of thumb for a 'good' object oriented program - a concise yes/no list that I can read through occasionally during design and implementation to prevent me from thinking and working procedurally. Would be even more useful if it contained the proper OO terms and concepts so that any check item is easily searchable for further information.

What should be on a checklist that would help someone develop good OO software?

Conversely, what 'tests' could be applied that would show software is not OO?

Steve McConnell's Code Complete 2 contains a lot of ready to use checklists for good software construction.

Robert C. Martin's Agile Principles, Patterns, and Practices in C# contains a lot of principles for good OO desgin.

Both will give you a solid foundation to start with.

I apologize for the subjectiveness of this question, but I am a little stuck and I would appreciate some guidance and advice from anyone who's had to deal with this issue before:

I have (what's become) a very large RESTful API project written in C# 2.0 and some of my classes have become monstrous. My main API class is an example of this -- with several dozen members and methods (probably approaching hundreds). As you can imagine, it's becoming a small nightmare, not only to maintain this code but even just navigating the code has become a chore.

I am reasonably new to the SOLID principles, and I am massive fan of design patterns (but I am still at that stage where I can implement them, but not quite enough to know when to use them - in situations where its not so obvious).

I need to break my classes down in size, but I am at a loss of how best to go about doing it. Can my fellow StackOverflow'ers please suggest ways that they have taken existing code monoliths and cut them down to size?

Single Responsibility Principle - A class should have only one reason to change. If you have a monolithic class, then it probably has more than one reason to change. Simply define your one reason to change, and be as granular as reasonable. I would suggest to start "large". Refactor one third of the code out into another class. Once you have that, then start over with your new class. Going straight from one class to 20 is too daunting.

Open/Closed Principle - A class should be open for extension, but closed for change. Where reasonable, mark your members and methods as virtual or abstract. Each item should be relatively small in nature, and give you some base functionality or definition of behavior. However, if you need to change the functionality later, you will be able to add code, rather than change code to introduce new/different functionality.

Liskov Substitution Principle - A class should be substitutable for its base class. The key here, in my opinion, is do to inheritance correctly. If you have a huge case statement, or two pages of if statements that check the derived type of the object, then your violating this principle and need to rethink your approach.

Interface Segregation Principle - In my mind, this principle closely resembles the Single Responsibility principle. It just applies specifically to a high level (or mature) class/interface. One way to use this principle in a large class is to make your class implement an empty interface. Next, change all of the types that use your class to be the type of the interface. This will break your code. However, it will point out exactly how you are consuming your class. If you have three instances that each use their own subset of methods and properties, then you now know that you need three different interfaces. Each interface represents a collective set of functionality, and one reason to change.

Dependency Inversion Principle - The parent / child allegory made me understand this. Think of a parent class. It defines behavior, but isn't concerned with the dirty details. It's dependable. A child class, however, is all about the details, and can't be depended upon because it changes often. You always want to depend upon the parent, responsible classes, and never the other way around. If you have a parent class depending upon a child class, you'll get unexpected behavior when you change something. In my mind, this is the same mindset of SOA. A service contract defines inputs, outputs, and behavior, with no details.

Of course, my opinions and understandings may be incomplete or wrong. I would suggest learning from people who have mastered these principles, like Uncle Bob. A good starting point for me was his book, Agile Principles, Patterns, and Practices in C#. Another good resource was Uncle Bob on Hanselminutes.

Of course, as Joel and Jeff pointed out, these are principles, not rules. They are to be tools to help guide you, not the law of the land.

EDIT:

I just found these SOLID screencasts which look really interesting. Each one is approximately 10-15 minutes long.

There's a classic book by Martin Fowler - Refactoring: Improving the Design of Existing Code.

There he provides a set of design techniques and example of decisions to make your existing codebase more manageable and maintainable (and that what SOLID principals are all about). Even though there are some standard routines in refactoring it is a very custom process and one solution couldn't be applied to all project.

Unit testing is one of the corner pillars for this process to succeed. You do need to cover your existing codebase with enough code coverage so that you'd be sure you don't break stuff while changing it. Actually using modern unit testing framework with mocking support will lead encourage you to better design.

There are tools like ReSharper (my favorite) and CodeRush to assist with tedious code changes. But those are usually trivial mechanical stuff, making design decisions is much more complex process and there's no so much tool support. Using class diagrams and UML helps. That what I would start from, actually. Try to make sense of what is already there and bring some structure to it. Then from there you can make decisions about decomposition and relations between different components and change your code accordingly.

Hope this helps and happy refactoring!

I've read about unit testing and heard a lot of hullabaloo by others touting its usefulness, and would like to see it in action. As such, I've selected this basic class from a simple application that I created. I have no idea how testing would help me, and am hoping one of you will be able to help me see the benefit of it by pointing out what parts of this code can be tested, and what those tests might look like. So, how would I write unit tests for the following code?

public class Hole : INotifyPropertyChanged
{
    #region Field Definitions
    private double _AbsX;
    private double _AbsY;
    private double _CanvasX { get; set; }
    private double _CanvasY { get; set; }
    private bool _Visible;
    private double _HoleDia = 20;
    private HoleTypes _HoleType;
    private int _HoleNumber;
    private double _StrokeThickness = 1;
    private Brush _StrokeColor = new SolidColorBrush(Colors.Black);
    private HolePattern _ParentPattern;
    #endregion

    public enum HoleTypes { Drilled, Tapped, CounterBored, CounterSunk };
    public Ellipse HoleEntity = new Ellipse();
    public Ellipse HoleDecorator = new Ellipse();
    public TextBlock HoleLabel = new TextBlock();

    private static DoubleCollection HiddenLinePattern = 
               new DoubleCollection(new double[] { 5, 5 });

    public int HoleNumber
    {
        get
         {
            return _HoleNumber;
         }
        set
        {
            _HoleNumber = value;
            HoleLabel.Text = value.ToString();
            NotifyPropertyChanged("HoleNumber");
        }
    }
    public double HoleLabelX { get; set; }
    public double HoleLabelY { get; set; }
    public string AbsXDisplay { get; set; }
    public string AbsYDisplay { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    //public event MouseEventHandler MouseActivity;

    // Constructor
    public Hole()
    {
        //_HoleDia = 20.0;
        _Visible = true;
        //this.ParentPattern = WhoIsTheParent;
        HoleEntity.Tag = this;
        HoleEntity.Width = _HoleDia;
        HoleEntity.Height = _HoleDia;

        HoleDecorator.Tag = this;
        HoleDecorator.Width = 0;
        HoleDecorator.Height = 0;


        //HoleLabel.Text = x.ToString();
        HoleLabel.TextAlignment = TextAlignment.Center;
        HoleLabel.Foreground = new SolidColorBrush(Colors.White);
        HoleLabel.FontSize = 12;

        this.StrokeThickness = _StrokeThickness;
        this.StrokeColor = _StrokeColor;
        //HoleEntity.Stroke = Brushes.Black;
        //HoleDecorator.Stroke = HoleEntity.Stroke;
        //HoleDecorator.StrokeThickness = HoleEntity.StrokeThickness;
        //HiddenLinePattern=DoubleCollection(new double[]{5, 5});
    }

    public void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, 
                       new PropertyChangedEventArgs(info));
        }
    }

    #region Properties
    public HolePattern ParentPattern
    {
        get
        {
            return _ParentPattern;
        }
        set
        {
            _ParentPattern = value;
        }
    }

    public bool Visible
    {
        get { return _Visible; }
        set
        {
            _Visible = value;
            HoleEntity.Visibility = value ? 
             Visibility.Visible : 
             Visibility.Collapsed;
            HoleDecorator.Visibility = HoleEntity.Visibility;
            SetCoordDisplayValues();
            NotifyPropertyChanged("Visible");
        }
    }

    public double AbsX
    {
        get { return _AbsX; }
        set
        {
            _AbsX = value;
            SetCoordDisplayValues();
            NotifyPropertyChanged("AbsX");
        }
    }

    public double AbsY
    {
        get { return _AbsY; }
        set
        {
            _AbsY = value;
            SetCoordDisplayValues();
            NotifyPropertyChanged("AbsY");
        }
    }

    private void SetCoordDisplayValues()
    {
        AbsXDisplay = HoleEntity.Visibility == 
        Visibility.Visible ? String.Format("{0:f4}", _AbsX) : "";
        AbsYDisplay = HoleEntity.Visibility == 
        Visibility.Visible ? String.Format("{0:f4}", _AbsY) : "";
        NotifyPropertyChanged("AbsXDisplay");
        NotifyPropertyChanged("AbsYDisplay");
    }

    public double CanvasX
    {
        get { return _CanvasX; }
        set
        {
            if (value == _CanvasX) { return; }
            _CanvasX = value;
            UpdateEntities();
            NotifyPropertyChanged("CanvasX");
        }
    }

    public double CanvasY
    {
        get { return _CanvasY; }
        set
        {
            if (value == _CanvasY) { return; }
            _CanvasY = value;
            UpdateEntities();
            NotifyPropertyChanged("CanvasY");
        }
    }

    public HoleTypes HoleType
    {
        get { return _HoleType; }
        set
        {
            if (value != _HoleType)
            {
                _HoleType = value;
                UpdateHoleType();
                NotifyPropertyChanged("HoleType");
            }
        }
    }

    public double HoleDia
    {
        get { return _HoleDia; }
        set
        {
            if (value != _HoleDia)
            {
                _HoleDia = value;
                HoleEntity.Width = value;
                HoleEntity.Height = value;
                UpdateHoleType(); 
                NotifyPropertyChanged("HoleDia");
            }
        }
    }

    public double StrokeThickness
    {
        get { return _StrokeThickness; }
        //Setting this StrokeThickness will also set Decorator
        set
        {
            _StrokeThickness = value;
            this.HoleEntity.StrokeThickness = value;
            this.HoleDecorator.StrokeThickness = value;
            NotifyPropertyChanged("StrokeThickness");
        }
    }

    public Brush StrokeColor
    {
        get { return _StrokeColor; }
        //Setting this StrokeThickness will also set Decorator
        set
        {
            _StrokeColor = value;
            this.HoleEntity.Stroke = value;
            this.HoleDecorator.Stroke = value;
            NotifyPropertyChanged("StrokeColor");
        }
    }

    #endregion

    #region Methods

    private void UpdateEntities()
    {
        //-- Update Margins for graph positioning
        HoleEntity.Margin = new Thickness
        (CanvasX - HoleDia / 2, CanvasY - HoleDia / 2, 0, 0);
        HoleDecorator.Margin = new Thickness
        (CanvasX - HoleDecorator.Width / 2, 
         CanvasY - HoleDecorator.Width / 2, 0, 0);
        HoleLabel.Margin = new Thickness
        ((CanvasX * 1.0) - HoleLabel.FontSize * .3, 
         (CanvasY * 1.0) - HoleLabel.FontSize * .6, 0, 0);
    }

    private void UpdateHoleType()
    {
        switch (this.HoleType)
        {
            case HoleTypes.Drilled: //Drilled only
                HoleDecorator.Visibility = Visibility.Collapsed;
                break;
            case HoleTypes.Tapped: // Drilled & Tapped
                HoleDecorator.Visibility = (this.Visible == true) ? 
                Visibility.Visible : Visibility.Collapsed;
                HoleDecorator.Width = HoleEntity.Width * 1.2;
                HoleDecorator.Height = HoleDecorator.Width;
                HoleDecorator.StrokeDashArray = 
                LinePatterns.HiddenLinePattern(1);
                break;
            case HoleTypes.CounterBored: // Drilled & CounterBored
                HoleDecorator.Visibility = (this.Visible == true) ? 
                Visibility.Visible : Visibility.Collapsed;
                HoleDecorator.Width = HoleEntity.Width * 1.5;
                HoleDecorator.Height = HoleDecorator.Width;
                HoleDecorator.StrokeDashArray = null;
                break;
            case HoleTypes.CounterSunk: // Drilled & CounterSunk
                HoleDecorator.Visibility = (this.Visible == true) ? 
                Visibility.Visible : Visibility.Collapsed;
                HoleDecorator.Width = HoleEntity.Width * 1.8;
                HoleDecorator.Height = HoleDecorator.Width;
                HoleDecorator.StrokeDashArray = null;
                break;
        }
        UpdateEntities();
    }

    #endregion

}

We must test it, right?

Tests are validation that the code works as you expect it to work. Writing tests for this class right now will not yield you any real benefit (unless you uncover a bug while writing the tests). The real benefit is when you will have to go back and modify this class. You may be using this class in several different places in your application. Without tests, changes to the class may have unforseen reprecussions. With tests, you can change the class and be confident that you aren't breaking something else if all of your tests pass. Of course, the tests need to be well written and cover all of the class's functionality.

So, how to test it?

At the class level, you will need to write unit tests. There are several unit testing frameworks. I prefer NUnit.

What am I testing for?

You are testing that everything behaves as you expect it to behave. If you give a method X, then you expect Y to be returned. In Gord's answer, he suggested testing that your event actually fires off. This would be a good test.

The book, Agile Principles, Patterns, and Practices in C# by Uncle Bob has really helped me understand what and how to test.

Tests will help, if you need to make changes.

According to Feathers (Feathers, Working Effectively with Legacy Code, p. 3) there are four reasons for changes:

  • Adding a feature
  • Fixing a bug
  • Improving design
  • Optimizing resource usage

When there is the need for change, you want to be confident that you don't break anything. To be more precise: You don't want to break any behavior (Hunt, Thomas, Pragmatic Unit Testing in C# with NUnit, p. 31).

With unit testing in place you can do changes with much more confidence, because they would (provided they are programmed properly) capture changes in behavior. That's the benefit of unit tests.

It would be difficult to make unit tests for the class you gave as an example, because unit tests also requires a certain structure of the code under test. One reason I see is that the class is doing too much. Any unit tests you will apply on that class will be quite brittle. Minor change may make your unit tests blow up and you will end up wasting much time with fixing problems in your test code instead of your production code.

To reap the benefits of unit tests requires to change the production code. Just applying unit tests principles, without considering this will not give you the positive unit testing experience.

How to get the positive unit testing experience? Be openminded for it and learn.

I would recommend you Working Effectively with Legacy Code for an existing code basis (as that piece of code you gave above). For an easy kick start into unit testing try Pragmatic Unit Testing in C# with NUnit. The real eye opener for me was xUnit Test Patterns: Refactoring Test Code.

Good luck in you journey!

I would like to get book(s) that will really give me a complete view of modern ASP.NET development using C#, TDD, ASP.NET MVC, DDD and Design Patterns such as the Repository pattern. I'm very competent with C# and ASP.NET MVC, but want to fill in the gaps.

If you've had a good experience with a book or two that covers these topics could you please share them?

Try Applying Domain Driven Design and Patterns By Jimmy Nillson. It covers DDD and it's patterns in .NET

Guess the scope of topics you have asked is vast to be covered in a single book

Try this One Agile Principles, Patterns, and Practices in C# By Martin and Martin

Book talks mostly about Design Principles, Design Patters, UML Diagrams, Documentation, Refactoring. It doesn't cover ASP.NET and MVC though. YOu need to refer some other books for those.

I'm currently interested in how to architecture good .NET applications and I'm reading or have currently read some of the following books:

Those two Microsoft books really explain how to design .NET applications with high testability using Inversion Of Control and such.

And to be clear, yes they all use design patterns common in TDD, DDD, Dependency Injection, ans so on...

For your needs I would recommend starting with:

Like the title says; it's basically a book on how to to DDD and TDD in a .NET environment.

Here are a few that I would recommend:

A co-worker of mine is taking an Introduction to Object Oriented Programming class and was asked a discussion question by his professor:

Why are many developers opposed to using the "protected" modifer on/within classes?

When the question was brought up at lunch, my co-workers and I couldn't think of reasons why someone might be opposed to using the protected modifier on a class. Setting the premise of the question aside (which assumes that many developers are in fact opposed to the protected modifier; are they?), we tried to figure out why.

Personally, the only times that I've used the protected access modifier on a class is when I've written code that I might want to supplement in a test environment. For example, I might write a base class with no debugging information and then create a new class for testing, inheriting from the base class and overwriting its methods to add in debug output code before/after the base method calls. I suppose I could just as easily use a design that involves interfaces and dependency injection to accomplish the same goal, but my only experience with protected has been for testing purposes. In this case, the only reason to avoid protected is because you can accomplish the same thing in better ways.

Why might developers be opposed to using the protected modifier in their OOP design?

NOTE: Because the professor is asking a general OOP question not specific to any one language, I'm not sure if answers might be weighted differently because of different implementations of protected in C#, Java, etc..

Overuse of protected could potentially lead to violation of Liskov Substitution Principle (L in SOLID) - PDF link. The principle states that classes should be written in a way that any subclass can be substituted for its base class. Robert C. Martin has a good discussion about that in Agile Principles, Patterns, and Practices in C#. The crux of the argument is that a subtype is only a subtype when it's substitutable for its base class, not simply having IS-A relationship.

So, by exposing too much functionality through protected methods, you could possibly allow the subclass to relax the invariants too much and make the subclass not a true subtype.

This is far from being black and white and one could not issue a blanket rule stating whether or not protected should/shouldn't be used. There are cases where it's genuinely necessary and there are cases where it's not. Using judgement in individual case is required.

what book would you recommend to improve one's c# style of writing? I know Code Complete has a few tips on style and organizing code but it's not specific to c#.

I would also recommend Clean Code by Robert Martin. Yes, it's not C#-specific, and yes, it will improve one's C# style of writing. It might be a good idea to continue with Agile Software Development, Principles, Patterns, and Practices book by the same author.

And here is 1 hour video from uncle Bob at Øredev conference Clean Code III: Functions

PS: Shameless plug. I developed a site which answers exactly this question: "Which book is of higher importance in given area?". I get the data from Amazon, and draw a network of books. The more links one book has the higher its importance. Thanks to this site I also found "Agile Principles, Patterns, and Practices in C#", again by Robert Martin, but I prefer the original book.

CLR Via C# by Jeffrey Richter contains all the 2.0 patterns you need to follow in order to produce good code. Helped me immensely.

Effective C# by Bill Wagner, as well as the sequel, More Effective C#.

Elements of C# Style is a good primer.

While it may not go into as much detail as other books that are available but I've definetly got my moneys worth from it - highly recommended.

C# Concisely very thorough

The project I'm working on has just hit 4200 lines in the main C# file, which is causing Intellisense to take a few seconds (sometimes up to 6 or so) to respond, during which Visual Studio locks up. I'm wondering how everyone else splits their files and whether there's a consensus.

I tried to look for some guides and found Google's C++ guide but I couldn't see anything about semantics such as function sizes and file sizes, maybe it's there - I haven't looked at it for a while.

So how do you split your files? Do you group your methods by the functions they serve? By types (event handlers, private/public)? And at what size limit do you split functions?

Edit: To clarify, the application in question handles data - so it's interface is a big-ass grid, and everything revolves around the grid. It has a few dialogs forms for management but it's all about the data. The reason why it's so big as there is a lot of error checking, event handling, and also the grid set up as master-detail with 3 more grid for each row (but these load on master row expanded). I hope this helps to clarify what I'm on about.

In the classic book "Structured Programming" Dijkstra once wrote a section entitled: "On our inability to do much." His point was simple. Humans aren't very smart. We can't juggle more than a few concepts in our minds at one time.

It is very important to keep your classes and methods small. When a method gets above a dozen lines or so, it should be broken apart. When a class gets above a couple of hundred lines, it should be broken apart. This is the only way to keep code well organized and manageable. I've been programming for nearly 40 years, and with every year that has gone by, I realize just how important the word "small" is when writing software.

As to how you do this, this is a very large topic that has been written about many different times. It's all about dependency management, information hiding, and object-oriented design in general. Here is a reading list.

All over our codebase we have this repeated pattern where there's an interface with one method. Is this a real design pattern? If so what is it and what would the benefits be?

Here are a few examples:

    public interface IRunnable
    {       
        void Run();     
    }

    public interface IAction
    {
        void Perform();
    }

    public interface ICommand
    {
        void Execute(ActionArgs _actionargs);
    }

I've seen this referenced as the Command pattern.

I first learned about it reading Uncle Bob's Agile Principles, Patterns, and Practices in C#.

I believe its elegance is its simplicity. I've used it when I wrote a file processing service. The service performed all of the administration of reading / deleting files. When a file needed to be processed, it's respective plugin was loaded. Each plugin implemented a Process method, and did whatever was needed to process that type of file. (Mainly, parse the contents and insert into a database.)

Everytime I had to process a new file type with a new layout, all I had to do was create a new Plugin that implemented Process.

This worked for me because I needed a simple solution. If you need to take in more than one parameter, this probably is not the pattern to use.

Are there other example projects like the Northwind Starters kit around that show you 'best practices' (layers, unit tests, mocking data, o/r mapping tools, ...) in architecture of ASP.NET development?

Or links to good and clear resources or documentation? (MSDN is a good reference but no good as tutorial)

  • are there example projects around addressing Visual Studio2008 and/or the AdventureWorks database?

thx, Lieven Cardoen

Microsoft has a whole slew of sample projects, white papers, etc. covering best practices on a variety of topics. Many of these are focused on ASP.NET but you'll probably want to go right to the MS Best Practices center. They also published a book covering the topic but it is quite old and I wouldn't recommend it any longer.

Of course, you may want to go right to the source for an overall approach to coding best practices and for that I'd recommend Martin and Martin's Agile Principles, Patterns and Practices in C#. I'm just finishing up Robert Martin's Clean Code and, while a fair amount is obvious, it is well written, has tons of examples and has helped push me to be more "craftsmanlike" in my approach to coding.

The last thing is that I consider good Unit Testing to be one of the bedrock "best practices" for any developer. I recommend Pragmatic Unit Testing by Hunt and Thomas there.

That should get you going!

I would recommend the book Building a Web 2.0 Portal with ASP.NET 3.5 by Omar Al Zabir.
His blog on ASP.NET Ajax and .NET 3.5 is also very valuable.

I've used the self-shunt unit testing pattern a few times over the years. As I was explaining it to someone recently they argued that it violated the SRP. The argument is that the test class can now be changed for one of two reasons: when the test changes, or when the method signature on the interface that the test is implementing changes. After thinking about it for a while, it seems like this is a correct assessment, but I wanted to get other peoples' opinions. Thoughts?

Reference: http://www.objectmentor.com/resources/articles/SelfShunPtrn.pdf

My take on this is that the test class technically violates the SRP, but it doesn't violate the spirit of SRP. The alternative to self-shunting is to have a mock class separate from the test class.

With the separate mock class you might think that it's all self contained and satisfies the SRP, however the semantic coupling to the mock class's attributes is still there. So, really, we didn't achieve any meaningful separation.

Taking the example out of the PDF:

public class ScannerTest extends TestCase implements Display
{
  public ScannerTest (String name) {
    super (name);
  }
  public void testScan () {
    // pass self as a display
    Scanner scanner = new Scanner (this);
    // scan calls displayItem on its display
    scanner.scan ();
    assertEquals (new Item (“Cornflakes”), lastItem);
  }
  // impl. of Display.displayItem ()
  void displayItem (Item item) {
    lastItem = item;
  }
  private Item lastItem;
}

Now we make a Mock:

public class DisplayMock implements Display
{
  // impl. of Display.displayItem ()
  void displayItem (Item item) {
    lastItem = item;
  }

  public Item getItem() {
     return lastItem;
  }
  private Item lastItem;
}

public class ScannerTest extends TestCase
{
  public ScannerTest (String name) {
    super (name);
  }
  public void testScan () {
    // pass self as a display
    DisplayMock dispMock = new DisplayMock();
    Scanner scanner = new Scanner (dispMock );
    // scan calls displayItem on its display
    scanner.scan ();
    assertEquals (new Item (“Cornflakes”), dispMock.GetItem());
  }
}

In practical terms (IMHO) the higher coupling of TestClass to DisplayMock is a greater evil than the violation of the SRP for TestClass. Besides, with the use mocking frameworks, this problem goes away completely.

EDIT I have just encountered a brief mention of self-shunt pattern in Robert C. Martin's excellent book Agile Principles, Patterns, and Practices in C#. Here is the snippet out of the book:

alt text

So, the guy who coined the SRP (which is talked about in great detail in the same book) has no qualms using self-shunt pattern. In light of that, I'd say you are pretty safe from the OOP (Objected Orientated Police) when using this pattern.

Currently code contracts do not allow preconditions on members in derived classes where the member already has a precondition set in the base class(I actually currently get a warning and not an error). I do not understand the logic behind this. I understand that it has to do with Liskov's substitution rule stating that a derived class should always be able to be used in places where the parent is expected. Of course "used" means work as expected. This seems okay to me for interfaces as the different types implementing an interface don't add state and hence can oblige the contract exactly. However, when you inherit from a base class, you are doing so to add state and special functionality and more often than not the overriding method would have extra requirements. Why can't preconditions be ANDed together just like post conditions and object invariants?

Take a look below:

class Speaker
{
    public bool IsPlugged { get; set; }
    protected virtual void Beep()
    {
        Contract.Requires(IsPlugged);
        Console.WriteLine("Beep");
    }
}

class WirelessSpeaker : Speaker
{
    public bool TransmitterIsOn { get; set; }
    protected override void Beep()
    {
        Contract.Requires(TransmitterIsOn);
        base.Beep();
    }
}

You may argue that this class hierarchy breaks Liskov's rule because the wireless speaker may not be able to beep when passed to methods that expect a Speaker. But isn't that why we use code contracts? to make sure that the requirements are met?

Bryan Watts is right. The classes presented by the OP violates the Liskov Substitution Principle. And you shouldn't use exceptions to control program flow—that's a code smell too. Exceptions are meant for, well, exceptions—exceptional conditions that will not allow your object to behave in an expected manner which could lead to corruption of your object's state and/or future behavior.

You need to ensure that you understand the totality of the Liskov Substitution Principle (LSP). LSP is not about ensuring that interfaces can be used interchangeably.

When an object inherits from another object, it's inheriting all of it's parent's behavior. True, you can override that behavior, but you must be careful in doing so. Let's use your example of a Speaker and a WirelessSpeaker and see how it all falls apart.

public class Speaker
{
    public bool IsPlugged { get; set; }

    public virtual void Beep()
    {
        if (!IsPlugged)
        {
            throw
            new InvalidOperationException("Speaker is not plugged in!");
        }

        Console.WriteLine("Beep.");
    }
}

public class WirelessSpeaker : Speaker
{
    public bool TransmitterIsOn { get; set }

    public override void Beep()
    {
        if (!TransmitterIsOn)
        {
            throw
            new InvalidOperationException("Wireless Speaker transmitter is not on!");
        }

        Console.WriteLine("Beep.");
    }
}

public class IBeepSpeakers
{
    private readonly Speaker _speaker;

    public IBeepSpeakers(Speaker speaker)
    {
        Contract.Requires(speaker != null);
        Contract.Ensures(_speaker != null && _speaker == speaker);
        _speaker = speaker;

        // Since we know we act on speakers, and since we know
        // a speaker needs to be plugged in to beep it, make sure
        // the speaker is plugged in.
        _speaker.IsPlugged = true;
    }

    pubic void BeepTheSpeaker()
    {
        _speaker.Beep();
    }
}

public static class MySpeakerConsoleApp
{
    public static void Main(string[] args)
    {
        BeepWiredSpeaker();

        try
        {
            BeepWirelessSpeaker_Version1();
        }
        catch (InvalidOperationException e)
        {
            Console.WriteLine($"ERROR: e.Message");
        }

        BeepWirelessSpeaker_Version2();
    }

    // We pass in an actual speaker object.
    // This method works as expected.
    public static BeepWiredSpeaker()
    {
        Speaker s = new Speaker();
        IBeepSpeakers wiredSpeakerBeeper = new IBeepSpeakers(s);
        wiredSpeakerBeeper.BeepTheSpeaker();
    }

    public static BeepWirelessSpeaker_Version1()
    {
        // This is a valid assignment.
        Speaker s = new WirelessSpeaker();

        IBeepSpeakers wirelessSpeakerBeeper = new IBeepSpeakers(s);

        // This call will fail!
        // In WirelessSpeaker, we _OVERRODE_ the Beep method to check
        // that TransmitterIsOn is true. But, IBeepSpeakers doesn't
        // know anything _specifically_ about WirelessSpeaker speakers,
        // so it can't set this property!
        // Therefore, an InvalidOperationException will be  thrown.
        wirelessSpeakerBeeper.BeepTheSpeaker();
    }

    public static BeepWirelessSpeaker_Version2()
    {
        Speaker s = new WirelessSpeaker();
        // I'm using a cast, to show here that IBeepSpeakers is really
        // operating on a Speaker object. But, this is one way we can
        // make IBeepSpeakers work, even though it thinks it's dealing
        // only with Speaker objects.
        //
        // Since we set TransmitterIsOn to true, the overridden
        // Beep method will now execute correctly.
        //
        // But, it should be clear that IBeepSpeakers cannot act on both
        // Speakers and WirelessSpeakers in _exactly_ the same way and
        // have confidence that an exception will not be thrown.
        ((WirelessSpeaker)s).TransmitterIsOn = true;

        IBeepSpeakers wirelessSpeakerBeeper = new IBeepSpeaker(s);

        // Beep the speaker. This will work because TransmitterIsOn is true.
        wirelessSpeakerBeeper.BeepTheSpeaker();
}    

This is how your code broke the Liskov Substitution Principle. As Robert & Micah Martin astutely point out in Agile Principles, Patterns and Practices in C# on pp. 142-143:

LSP makes it clear that in OOD, the IS-A relationship pertains to behavior that can be reasonably assumed and that clients depend on....[W]hen using an object through its base class interface, the user knows only the preconditions and postconditions of the base class. Thus, derived objects must not expect such users to obey preconditions that are stronger than those required by the base class. That is, users must accept anything that the base class could accept. Also, derived classes must conform to all the postconditions of the base [class].

By essentially having the precondition TransmitterIsOn == true for the Beep method of the WirelessSpeaker, you created a stronger precondition than what existed on the base Speaker class. For WirelessSpeakers, both IsPlugged and TransmitterIsOn must be true in order for Beep to behave as expected (when viewed from the perspective of a Speaker), even though a Speaker in and of itself has no notion of TransmitterIsOn.

Also, you violated another SOLID principle, the Interface Segregation Principle:

Clients should not be forced to depend on methods they do not use.

In this case, a WirelessSpeaker does not need to be plugged in. (I'm assuming we're talking about the audio input connection here, as opposed to an electrical connection.) Therefore, the WirelessSpeaker should not have any property called IsPlugged, yet, because it inherits from Speaker, it does. This is an indication that your object model does not line up with how you intend to use your objects. Again, notice that most of this discussion is centered around the behavior of your objects, and not their relationship to one another.

Moreover, the violation of both LSP and ISP both signal that there's probably been a violation of the Open/Closed Principle, too:

Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

So, at this point it should be clear, now, that we do not use Code Contracts only to ensure that certain preconditions are met when calling methods on objects. No, Code Contracts are used to state guarantees (hence the word contract) about the behavior and state of your objects based on the stated preconditions.

So, for your speaker class, what you're saying is: If the speaker is plugged in, then the speaker can beep. Ok, so far, so good; that's simple enough. Now, what about the WirelessSpeaker class?

Well, WirelessSpeaker inherits from Speaker. Therefore, WirelessSpeaker also has an IsPlugged Boolean property. Furthermore, because it inherits from Speaker, then in order for the WirelessSpeaker to beep, it must also have its IsPlugged property set to true. "But wait," you say, I have overridden the implementation of Beep such that WirelessSpeaker's transmitter must be on. Yes, this is true. But it also must be plugged in! Because WirelessSpeaker not only inherits the Beep method, but also the behavior of its parent class! Since the parent class can be "plugged in", so too, can WirelessSpeaker! And I doubt that this is what you intended when you originally thought of this object hierarchy.

So, how would you fix this? Well, you need to come up with a model better aligned to the behaviors of the objects in question. What do we know about these objects, and their behavior?

  1. They're both a kind of speaker.
    • So, potentially, a wireless speaker could be a specialization of a speaker. Or conversely, a speaker may be a generalization of a wireless speaker.
    • In the current object model (as much as you've posted), there's not much behavior or state that is shared between these two objects.
    • Since there's not much common state or behavior between the two objects, one might argue there shouldn't be an inheritance hierarchy here. I'm going to play devil's advocate with you and maintain the inthertiance hierarchy.
  2. They both beep.
    • However, the conditions under which each type of speaker beeps is different.
    • Therefore, these speakers cannot directly inherit one from the other, otherwise, they would share behavior that is not appropriate to them. This resolves the ISP problem.

Ok, so the one piece of shared behavior these speakers have is they beep. So, let's abstract that behavior out into an abstract base class:

public abstract class SpeakerBase
{
    protected SpeakerBase() { }

    public void Beep()
    {
        if (CanBeep())
        {
            Console.WriteLine("Beep.");
        }
    }

    public abstract bool CanBeep();
}

Great! Now we have an abstract base class that represents speakers. This abstract class will allow a speaker to beep, if and only if the CanBeep() method returns true. And this method is abstract, so any class inheriting this class must provide their own logic to this method. By creating this abstract base class, we have enabled any class that has a dependency on the SpeakerBase class to emit a beep from the speaker if and only if CanBeep() returns true. This also resolves the LSP violation! Anywhere a SpeakerBase can be used and called upon to beep, either a Speaker or a WirelessSpeaker can be substituted and we can be sure of the behavior: if the speaker can beep, it will.

Now all that's left is to derive each of our speaker types from SpeakerBase:

public class Speaker : SpeakerBase
{
    public bool IsPlugged { get; set; }

    public override bool CanBeep() => IsPlugged;
}

public class WirelessSpeaker : SpeakerBase
{
    public bool IsTransmiterOn { get; set; }

    public override bool CanBeep() => IsTransmitterOn;
}

So, now we have a Speaker that can only beep when it's plugged in. We also have a WirelessSpeaker that can only beep if it's transmitter is turned on. Furthermore, following the Dependency Inversion Principle:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

What this means is that consumers of speakers should not depend directly on either Speaker or WirelessSpeaker, but should depend on SpeakerBase instead. This way, no matter what kind of speaker comes along, if it inherits from SpeakerBase, we know that we can beep the speaker if the conditions warrant for the sub-type of speaker referenced by the abstract type in the dependent class. This also means that IBeepSpeakers no longer knows how to put a speaker in the state such that it can beep, as there is no common behavior among speaker types that IBeepSpeakers could use to make such a determination. So that behavior must be passed in as a dependency to IBeepSpeakers. (This is an optional dependency; you could just let the class take in a SpeakerBase and call Beep(), and, if the SpeakerBase object is in the correct state, it'll beep, otherwise it won't.)

public class IBeepSpeakers
{
    private readonly SpeakerBase _speaker;
    private readonly Action<SpeakerBase> _enableBeeping;

    public IBeepSpeakers(SpeakerBase speaker, Action<SpeakerBase> enableBeeping)
    {
        Contract.Requires(speaker != null);
        Contract.Requires(enableBeeping != null);
        Contract.Ensures(
            _speaker != null && 
            _speaker == speaker);
        Contract.Ensures(
            _enableBeeping != null && 
            _enableBeeping == enableBeeping);

        _speaker = speaker;
        _enableBeeping = enableBeeping;
    }

    pubic void BeepTheSpeaker()
    {
        if (!_speaker.CanBeep())
        {
           _enableBeeping(_speaker);
        }
        _speaker.Beep();
    }
}

public static class MySpeakerConsoleApp
{
    public static void Main(string[] args)
    {
        BeepWiredSpeaker();

        // No more try...catch needed. This can't possibly fail!
        BeepWirelessSpeaker();
    }

    public static BeepWiredSpeaker()
    {
        Speaker s = new Speaker();
        IBeepSpeakers wiredSpeakerBeeper =
            new IBeepSpeakers(s, s => ((Speaker)s).IsPlugged = true);
        wiredSpeakerBeeper.BeepTheSpeaker();
    }

    public static BeepWirelessSpeaker()
    {
        WirelessSpeaker w = new WirelessSpeaker();
        IBeepSpeakers wirelessSpeakerBeeper =
            new IBeepSpeakers(w, s => ((WiredSpeaker)s).IsTransmitterOn = true);
        wirelessSpeakerBeeper.BeepTheSpeaker();
    }
}

As you can see, we actually didn't need Code Contracts at all to tell us whether or not the speaker should beep. No, rather we let the state of the object itself determine whether it can beep.

Possible Duplicate:
Inversion of Control < Dependency Injection

Could anyone please help me to understand DI and IOC with simple C# example please? As I understand IOC is the inversion of control flow (which means nothing to me) and DI means injecting interfaces via properties or constructors. Not sure how these two are related.

Thank you.

I highly recommend you to read Dependency Injection in .NET book, it in details describes all aspects with comprehensive code examples. For the inversion of control you should refer to another book by Robert Martin: Agile Principles, Patterns, and Practices in C#. It in details describes SOLID principles with examples and understandable explanations. These two books really helped me to understand these principles.

Ideas on how to develop software that is capable of adapting to meet changing business requirements? Any patterns, architectures, etc. Possibly some anecdotal examples would be great. This is more of a survey than a concrete questions. Thanks

You will want to learn more about the entire Agile Development movement. Agile is just what it says: able to quickly adapt.

I work on GUI and deal with complex objects that is objects have other objects and those object might have other objects.

These objects are manipulated (often almost at the same time) by various views, view models, services, nhibernate, and you name it - doing in simple things like, save/update/delete/validate and etc.

In most cases things like NotifyPropertyChanged is enough, but not always. Sometimes i resolve to calling EventAggregator BUT when object graph is big and especially collection of such objects - it gets so messy i keep loosing ends and not sure what is exact state of a particular object and often not sure if that is still same object or some loose copy of it;

So my question is what is best approach / methodology to manage object states and avoid "state explosion"?

I advise you to take note of a book Agile Principles, Patterns, and Practices in C# by Robert C. Martin and Micah Martin, there are many good examples where it is shown how to design a system by UML, and other similar methods. Specifically, it is shown why you should refactor your code, that can be stored in abstract classes and what is not. You can immediately see an example with a coffee maker Mark IV, where he developed a truly independent interface.

According to my feelings, the main principle of MVVM - is the independence of the data from its representations. I like trying to make separate modules, which implement separate logic, not knowing about the data. For example, SQL module, SMTP module, etc, which simply contain some methods like ConnectToDb() or SendEmail(), the main logic is in ViewModel, she combines these Work-modules with the data model.

Useful to draw a diagram before designing the system, but do not get involved too. The main thing is to see the main parts in the paper, and that the others would understand it as well as you know (or architect).

What .net/c# focused books are there that teach how to develop applications using SOLID principles, unit testing, IoC, etc?

I've watched a few videos on the SOLID principles, but I'd love to learn more about it and in detail on how to go about designing larger scale applications etc.

First of all, it is this book:

http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258/ref=sr_1_5?ie=UTF8&qid=1308502374&sr=8-5

Robert Martin - it is a person who introduced SOLID principles.

And I am looking forward to read this book about DI in .Net:

http://www.amazon.com/gp/product/1935182501/ref=ox_sc_act_title_3?ie=UTF8&m=ATVPDKIKX0DER

About unit testing here is very good book: http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274

i have something like this in my project, the project it's kinda finished already (it's working) i just want know if it is ok with the SOLID principles

static public class Tools
{
    static public GetProduct(this id){...}

    static public GetProductCategory(this id){...}

    static public GetUser(this id){...}

    // I also have here methods like IsStringNull ...
    // IsNull IsFalse, lots of stuff, everything static
}

and the usage is like this

var UserThatCreatedCategoryForThisProduct = 
      prodId.GetProduct().CategoryId.GetProductCategory().Creator.GetUser();

i know that is obvious that it's violates the SRP, but this class is static and it contains static methods that are independent one from each other, and it's kind off the same if i would create a static class for each method

Based on your examples, there's definitely an ISP and a SRP and probably a Law of Demeter (not SOLID but...) violation going on at the very least.

IMNSHO You're far better off reading articles on SOLID (or buying Agile Principles, Patterns, and Practices in C# by Robert C. Martin and Micah Martin which is excellent throughout and one of the most useful books I've read in recent years) than asking for piecemeal advice on the interwebs for this type of thing.

If you want a shortcut (you don't though - the books and PDFs have examples that explain things very well!), these Hanselminutes podcasts with Uncle Bob are very good:

edit: Nabbed the SRP from Jon Limjap and ppiotrowicz

I need to create an architecture diagram for an existing system. I want to show the "big picture" as well as small details.

What makes more sense:

  • Create one diagram for the big picture, and a separate diagram for each smaller component.
  • Create one diagram with all details. I guess this requires correct tooling to be able to show a simple big picture view as well as a detailed drill down (zoom). What tools work for that?

In general, in most areas of development it is generally a bad idea to mix levels of abstraction. In many ways, OO is a way of organising levels of abstraction while encapsulation is a way of enforcing it.

In my opinion, this also applies to design. So I think you should create your diagrams at the level of abstraction that is appropriate. If you are not sure what hardware will be use and what 3rd party SW will be used then you may need a seperate deployment diagram. If Software layout is a no-brainer then you may want to start sketching out ideas using class diagrams or sequence diagrams.

I think it is appropriate to the apply the 7+-2 rule - in that developers can only succesfully keep 7 (+-2) concepts in their mind at one time - having an all encompasing diagram with all levels of abstraction would break that rule!!!

Having said that, only spend time on creating diagram if it is going to be beneficial to the team and drives the project forward. If the best way to proceed is understood by the team, then diagramming that understanding isn't really going to add any value. However, if you are unsure of the next step, then diagramming can be a useful way of communicating ideas between the team - only adding enough detail so that the idea is clear. But don't be afraid to throw diagrams away too!

In my opinion the following book provides the best demonstration of the level and detail of diagramming that is useful for a project:

http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258

as the question says, i wish to learn OOP in c#. I am aware of the basics of OOP such as what does class means, what is object, and all 6-7 features of OOP. What i dont understand that how to make use this in real application? I get stuck when it comes to using all these features during development (coding).

I have code in VB.NET and now would be doing in C#. I have use VS 2005 and now using VS 2008.

Please suggest me some very good resource to learn (& especially i could implement it also) OOP in C#

thanks

Personally, I found the classic Design Patterns book quite an eye-opener when it comes to object-oriented design. From that, all else follows :)

It predates C# with about 5 years, so you will have to look at C++ and SmallTalk code instead, but learning OO is really not about the language, but rather the mindset.

Many people find that Head First Design Patterns is a more digestible alternative, but I have only flipped through it myself (it looks pretty good, though).

Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

Applying Domain-Driven Design and Patterns is the first complete, practical guide to leveraging patterns, domain-driven design, and test-driven development in .NET environments. Drawing on seminal work by Martin Fowler and Eric Evans, Jimmy Nilsson shows how to customize real-world architectures for any .NET application. You'll learn how to prepare domain models for application infrastructure; support business rules; provide persistence support; plan for the presentation layer and UI testing; and design for service orientation or aspect orientation.

Although not the book's only focus, I found Agile Principles, Patterns, and Practices in C# really useful for OOD/OOP. It covers SOLID design principles in an accessible and very readable way. Similar content is also available at the author's (Robert C. Martin) web site, Object Mentor.

Agile Principles, Patterns, and Practices in C# cover

I have a DLL, say A, which implements general algorithms to solve mathematical equations. I have another DLL, say B, which implements mathematical equations DLL B uses DLL A in order to solve it’s equations but DLL B must be able to execute a given equation from DLL A (DLL A implements some numerical, proximity methods and “tries” different values on a given equation as its steps towards desired mathematical solution) Now, DLL A must “know” DLL B and vise versa.

Is this a “bad” design? Can I think about such a code as amateurish cose? What would you do (please remember that DLL A implements general algorithm that are used by different other DLLs which implements mathematical equations)?

Thanks David

This problem (circular dependency of implementations between packages) is exactly why the Dependency Inversion Principle (DIP) was created. Charles Bailey provided a solution that employs DIP to break the dependency. Instead of coupling two concrete classes directly to each other (classes or functions, it doesn't make much difference for applying DIP), couple them to an abstraction.

In this case, we have an interface that defines a "mathematical function" and that is consumed by the solver DLL. We also have an interface that defines "solver algorithms" and that is consumed by the function DLL. We have the concrete classes/functions depend on the abstractions. In C++ terms, these would be interfaces and when calling a method in the function DLL, the solver would pass itself to the function as a pointer to the "solver interface". The function calls methods on the solver interface to call back into the solver at the appropriate points. Similar, the solver has a class that takes a pointer to the mathematical function interface and it calls back into the function at the appropriate time.

Bob Martin's book Agile Principles, Patterns and Practices in C# covers these object-oriented design principles, including DIP. He has concrete examples that show these principles in practice. Although the book uses C# (the first edition used Java), the same principles and practices apply to C++.

I'm new to using an Ioc, and am wondering how, if at all, I should be injecting Microsoft classes. Specifically, I am using DirectorySearcher. Can I inject this? I don't think so.

So I made a wrapper class for DirectorySearcher, and created a factory method. So I could inject my wrapper class where I needed it, and call the factory 'Create' method. Is this the way to handle this type of situation? Or do I need a whole Factory class?

public class Directory
{
    public Directory() { }
    public static Directory Create(string userName, string password, string ldapPath)
    {
        var entry = new DirectoryEntry(path, userName, password, AuthenticationTypes.Secure);
        var searcher = new DirectorySearcher(entry);
        return new Directory() { Searcher = searcher }; 
    }
}

My concern is that my wrapper is tightly coupled to DirectorySearcher. To test, I really need to access my live AD.

According to Agile Principles, Patterns, and Practices:

clients [...] own the abstract interfaces

What it means is that you should define the interface in a way it makes sense for the consumer; not the target. Others call this concept ports and adapters, where the port is the abstraction that is used by the application and the adapter is the implementation of that interface that translates the calls to the external system (LDAP in your case).

So although you can create an 'adapter' that allows you to create an directory using LDAP, your implementation is leaking implementation details, such as the fact that you need certain credentials and the fact that you need to supply an ldapPath. These are violations of the Dependency Inversion Principle, because:

Abstractions should not depend on details.

So instead, try to find out what the abstraction is for your application. You might want to define the abstraction on a much higher level. For instance, it's highly unlikely that creating the directory is actually the use case that the user wants to perform. Instead, the use case might be something like creating a new user account and to accomplish that, one of the steps in that use case is to create a directory.

So think about what your application needs, and prevent specifying any details in that. But to be honest, this can be really hard. It took me quite some practice to be able to do that, and I still get my abstractions wrong the first time most of the time. The trick is to be able to accept that you were wrong and improve the design. One step at a time.

So how your design should really look like, I don't know. I have no idea what you are trying to accomplish and even if I knew, I would probably still give you the wrong advice. But one thing I know, creating a factory is usually not the solution. It just moves the problem. Don't get me wrong, the factory is still a valid design pattern, but you won't need them that often if you are applying the SOLID principles and Dependency Injection correctly.

I see an usage of IDataReader instead of DbDataReader in many examples (and usage of other ADO.NET interfaces instead of their corresponding classes).

I know that IDataReader is an interface and DbDataReader is a class, and so on and so forth... My question is not about how interfaces differ from classes.

IDataReader describes an interface of generic data reader.

DbDataReader is also generic (but an abstract class).

Their usage examples seem to be equivalent.

Why to use generic data reader interface instead of using generic data reader class? Which cases require an usage of interface only? Which cases require an usage of class only?

A typical example:

DbCommand cmd = conn.CreateCommand();
.....................
using (IDataReader reader = cmd.ExecuteReader())
{
    grid.DataSource = reader;
    grid.DataBind();
}

The answer is to achieve abstraction in dependencies. Usually we try to use generic interfaces so that classes using that interfaces are independent of actual implementation.

Consider if your class is consuming IDataReader and one day you need to come up with another implementation of IDataReader which may reads data from files, just say as example, then all you need to do is to create another implementation of IDataReader and initialize your instance variable with that.

Plus there are other good practices out there such as Dependency Injection, Unit Testing and those are achievable when you code abstracted and interface oriented

Spend some time going through good coding practices such as reading this book

I am creating a Web API that would call a service layer, and I am trying to learn Dependency Injection, ( i am hoping to use ninject), but I am unsure on how to create dependency on the service layer.

This is what the web api would call.

enter image description here

Here the issues, when calling IPersonService, the person would have a gender defined, it would have a name, a role, and ethnicity. I am using constructor injection and unsure if I should call the GenderService or should I call the business layer ( in this case defined by Core).

enter image description here

Should I be calling the service like the picture above, or below

enter image description here

This is what my person service look like

namespace Service.Services
{
    public class PersonService : IPersonService
    {
        private IPersonCore personCore = null;
        private INameService nameService = null;
        private IRoleService roleService = null;
        private IGenderService genderService = null;
        private IEthnicityService ethnicityService = null;
        private IPrefixService prefixService = null;
        private Person currUser;

        public PersonService(IPersonCore _personcore, INameService _namecore, IRoleService _roleservice, IGenderService _genderservice, IEthnicityService _ethnicityservice, IPrefixService _prefixservice )
        {
            this.personCore = _personcore;
            this.nameService = _namecore;
            this.roleService = _roleservice;
            this.genderService = _genderservice;
            this.ethnicityService = _ethnicityservice;
            this.prefixService = _prefixservice;
        }

        public IEnumerable<Person> GetAllPerson()
        {
            if (isAuthorized())
            {
                return this.personCore.GetPersons();
            }
            return null;
        }

        public Person GetPersonByID(int id)
        {
            if (isAuthorized())
            {
                return this.personCore.GetPersonByID(id);
            }
            return null;
        }

        public Person GetPersonByEmail(string email)
        {
            if (isAuthorized())
            {
                return this.personCore.GetPersonByEmail(email);
            }
            return null;
        }

        public IEnumerable<Person> GetPersonByName(string first, string last, string middle)
        {
            if(isAuthorized())
            { 
                Name newname = this.nameService.CreateName(first, last, middle);
                return this.personCore.GetPersonByName(newname);
            }
            return null;
        }

        public IEnumerable<Person> GetPersonWithRoles(IEnumerable<Roles> r)
        {
        }

        public IEnumerable<Person> GetPersonWithDOB(DateTime d)
        {
            if (isAuthorized())
            {
                return this.personCore.GetPersonWithDOB(d);
            }
            return null;
        }

        public Person SetPersonRole(int id, Roles r)
        {
        }

        public Person SetGender(int id, Gender g)
        {
        }

        public Person SetEthnicity(int id, Ethnicity e)
        {
        }

        public Person SetPrefix(int id, Prefix p)
        {
        }

        public Person CreatePerson(Person p)
        {
            if (isAuthorized())
            {
                return personCore.AddPerson(p);
            }
            return null;
        }

        public Person UpdatePerson(Person p)
        {
            if (isAuthorized())
            {
                return personCore.UpdatePerson(p);
            }
            return null;
        }

        public Person ActivatePerson(int id)
        {
            if (isAuthorized())
            {
                return personCore.ActivatePerson(id);
            }
            return null;
        }

        public Person DeactivatePerson(int id)
        {
            if (isAuthorized())
            {
                return personCore.DeactivatePerson(id);
            }
            return null;
        }

        public bool DeletePerson(int id)
        {
            if (isAuthorized())
            {
                return personCore.DeletePerson(id);
            }
            return false;
        }

        protected bool isAuthorized()
        {
            //Probably move to common
            return true;
        }
    }
}

When calling from the Web API my issue with it, is its sound like a lot of dependency for finding something about a certain person.

The PersonService class contains many dependencies, because you are violating the Single Responsibility Principle. This class has many responsibilities and you'll end up changing this class every time you are adding a new feature (which is a Open/Closed Principle violation). Besides, the isAuthorized method is a cross-cutting concern, which this class should have no notion of.

On top of that, you are injecting the current logged in user into the PersonService. This is runtime data, and constructing application components using runtime data is an anti-pattern.

There are many ways to fix this, but it all comes down to understanding the SOLID principles. Doing so however might be a daunting task, especially if you're just starting with DI and software design. There are many books you can read about this, such as the amazing work from Robert C. Martin and books about Dependency Injection like Mark Seemann's Dependency Injection in .NET.

Designs that helped me out a lot the last few years are message based architectures, where use cases are described by messages, and implementations are described by generic abstractions (read this and this). These designs have proven to be very flexible and maintainable, since they allow adding cross-cutting concerns transparently and allow adding new features without changing any existing code. Such design also allows reducing your Web API layer to a simple piece of infrastructure that doesn't require changing when new features are being added. You can read about this concept here (note: that article is about WCF, but the concept for Web API is the same) and here is a Github repository that shows how to implement this both in WCF and Web API.

I wish you the best of luck in your quest to software mastery.

I am handling a project which needs restructuring set of projects belonging to a website. Also it has tightly coupled dependency between web application and the dependent project referenced. Kindly help me with some ideas and tools on how the calls could be re factored to more maintainable code.

The main aspect is that there are calls to apply promotion (promotion class has more than 4 different methods available) consumed from various functions, which could not be stream lined easily.

Kindly help me here with best practices.

Sorry guys- i could not share much code due ot restriction, but hope the below helps

My project uses N-Hibernate for data access Project A- web project - aspx and ascx with code behind Project B- Contains class definition consumed by project C (data operation class) Project C - Business logic with saving to database methods (customer, order, promotion etc.)

The problem is with project C - which i am not sure if it does too many things or needs to be broken down.But there are already many other sub projects.

Project C supports like saving details to DB based on parameters some of the class methods in this calls the promotion based on some condition, I would like to make things more robust - sample code below

Project -C Class - OrderLogic

public void UpdateOrderItem(....)
{
....
....
...
}
Order order = itm.Order;
promoOrderSyncher.AddOrderItemToRawOrderAndRunPromosOnOrder(itm, ref order);
orderItemRepository.SaveOrUpdate(itm); 

So just like the above class the promotion is called from may other places, i would like to streamline this calls to promotion class file. So i am looking for some concepts.

I strongly suggest not to start restructuring your application without a strong knowledge of SOLID principles and dependency injection. I did this mistake and now I have an application full of service locator (anti)pattern implementations that are not making my life simpler than before.

I suggest you to read at least the following books befor starting:

http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258 (for SOLID principles)

http://www.manning.com/seemann/ (for .NET dependency injection)

http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052

A possible strategy is not refactoring just for the sake of it, but consider refactoring only the parts that are touched more than others. If something is working and nobody is going to change it there's no need to refactor it, it can be a loss of time.

Good luck!

While refactoring some old legacy code, I've tried to apply as much as possible the Single Responsibility Principle, so I ended up with many classes that have just one purpose. That's fine, but the problem comes when I tried to write unit tests for these new classes. Some classes are really hard to test, because the tests are hard to set up. I need to create like 4-5 mocks/stubs to write a single test case, and if I want to have all my code covered, I need to write several test cases so it's just a pain in the ass.

Having tests hard to set up (because it depends on many other classes) is a code smell? How do you solve this?

Here's what Uncle Bob says about SRP:

A class should have one, and only one, reason to change.

Note that it did not say "a class does one thing and only one thing." In other words, it's perfectly valid for a class to have more than one responsibility if all but one of those responsibilities are invariant or if they'll all change together.

In his Agile Patterns, Principles, and Practices book, Uncle Bob says:

In the context of SRP, we define a responsibility to be a reason for change (117).

And:

If, on the other hand, the application is not changing in ways that cause [multiple] responsibilities to change at different times, there is no need to separate them. Indeed, separating them would smell of needless complexity. (118)

That said, a class that has too many collaborators is a smell and should be examined carefully.

I truly hope this question doesn't get deleted since I really do need help from the programming pros out there...

I've been programming for quite a while (my main platform being .Net), and am about 85% self-taught - Usually from the school of hard-knocks. For example, I had to learn the hard way why it was better to put your configuration parameters in an .ini file (that was easier for my users to change) rather than hard-code them into my main app and now to use the app.config rather than even a config file sometimes. Or what a unit-test was and why it proved to be so important. Or why smaller routines / bits of code are better 90% of the time than one, long worker process...

Basically, because I was thrown into the programming arena without even being shown .Net, I taught myself the things I needed to know, but believe I missed MANY of the fundamentals that any beginner would probably be taught in an intro class.

I still have A LOT more to learn and was hoping to be pointed in the right direction towards a book / web-resource / course / set of videos to really teach the best programming practices / how to set things up in the best way possible (in my case, specifically, for .Net). I know this may seem subjective and every programmer will do things differently, but if there are any good books / resources out there that have helped you learn the important fundamentals / tricks (for example, self-documenting code / design patterns / ) that most good programmers should know, please share!!!

My main platform is .Net.

Thanks!!!!

Possible Duplicate:
What is Inversion of Control?

I always hear Inversion of Control described in vague terms and almost always through example than a formal definition

On the one hand I hear it described in terms of objects programming to abstractions and giving up having control over explicitly instantiating a new object and it's object graph vs requesting objects that have their dependencies created injected into them runtime conditions

Then I hear it explained in terms of programming against frameworks where the programmer forfeits the flow of control in favor of coding to extension points (eg events and callbacks)

What exactly is being inverted in both cases and what do they have in common that they're equivalent examples of IoC. I've found it surprisingly difficult to find a commonly accepted definition

This is certainly a reasonable explanation:

http://en.wikipedia.org/wiki/Inversion_of_control

I own this book: I'd recommend it for good coverage of many design principles, including IoC:

Agile Principles, Patterns and Practices in C#: Martin Fowler, Micah Fowler

You might also find these links helpful:

Two pithy "explanations":

  • IoC is sometimes known as the "Hollywood Principle": Don't call us, we'll call you

  • IoC = Marriage; IOC Container = Wife