Latest Event Updates

Agile Methodology – Agile under a Firm Fixed-Price Contract (FFP)

Posted on Updated on

IAgile Firm Fixed Pricen our first post on using Agile to develop better software and reduce risk, we discussed Agile in a general sense, talked about its origins, and covered the basic underlying principles.

Project Managers and development teams in today’s business world are becoming more and more familiar with Firm Fixed-Price contracts (FFP). They struggle to adhere to the philosophies of Agile while being confronted with customers and functional managers who want specific features and functionality and want accurate estimates up-front. Many of these customers already have (or believe they have) knowledge of Agile, but want to capitalize on the risk transference that FFP gives them. Having worked in such environments for several years, I have learned just how interesting these situations can be for Project Managers and development teams, and how the development path can be affected as a result.

A large part of the solution is to think outside of the box a little and consider Agile’s strong points and how they actually help us contend with perceived challenges of FFP contracts. Before we can consider ways to make Agile work under FFP, we first have to understand exactly what Agile is, understand the types of constraints inherent to any development project, and gain some insight into why organizations favor Firm Fixed-Price contracts.

An Agile development team can definitely succeed under FFP! Let’s get that out of the way. As we discuss project constraints and the motivations of customers and contractors/service providers we will see just how to make it work.

Why Does Agile Work in the First Place?

Ignoring the concept of FFP for a moment, why would an organization benefit from Agile in the first place? Let’s start by reviewing the 4 key points of the Agile Manifesto and discussing each a little bit. We originally discussed these in our first Agile post, but let’s take a slightly different approach here. Agile favors:

  • Individuals and interactions over processes and tools – people define functionality and people build software. People decide on and implement processes and people choose and implement tools. Pretty simple, right? By placing emphasis on the people and their interaction we also place emphasis on productivity, quality assurance, accountability, and knowledge transfer not just at project completion but throughout the development process.
  • Working software over comprehensive documentation – although documentation is important, a working product is more important. When we say “comprehensive documentation” what does that mean? In the days of waterfall, it meant massive mounds of functional and technical documentation and quite often the technical documentation was not too far from a regurgitation of the code itself! What good is that? Though I avidly support the provision of adequate functional documentation to support the normal operation of the software and to provide training/reference information (based on the customer’s needs and specifications of course), Agile forces us to take a look at exactly what we are producing, how we are producing it, and its true value, and we produce what is needed concurrently with development. From the standpoint of technical documentation as an example, if we write our code properly and provide the documentation and commentary throughout to adequately allow a developer who comes behind us to understand what is being done, there is just no need to reproduce this information again.
  • Customer collaboration over contract negotiation – regardless of whether or not a customer demands an FFP contract, it is highly unusual to NOT want a reasonably accurate estimate of the total cost of the product development and all services to be provided. That’s just good business! It would be irresponsible of a service provider to not exercise due diligence in providing such an estimate anyway. That is good business for the service provider. But with Agile, the “us versus them” environment that can be created with contract negotiation is counterproductive. Through close collaboration, effective communication, and expectation management, a service provider can do a pretty good job of ensuring that the functionality that is truly needed is properly developed and that the customer is completely up-to-date on all functionality developed. Furthermore, the service provider can ease the customer’s fears and apprehension by building trust through day-to-day communication and frequent impromptu reviews and demonstrations. As they see functionality being produced, they tend to relax a bit and allow themselves to become even more involved.
  • Responding to change over following a plan – with Agile, change is expected. When we say change, we do not mean chaos! Uncontrolled, frequent change is not feasible and though change is welcomed, it has to be handled in an orderly manner.

Now, from our original post on Agile, let’s also review the principles behind the points discussed above.

  • Satisfy the customer through early and continuous delivery of working software
  • Change is welcomed, even late in the development process
  • Working software is delivered frequently, typically at intervals from two weeks to two months
  • Developers work directly with functional personnel/SMEs on a daily basis
  • Projects are built around motivated, capable people and they are given an environment that allows them to succeed
  • Face-to-face communication is critical
  • The primary measure of progress is working software
  • The development pace must be sustainable
  • Continuous attention to technical excellence and good design enhance agility
  • Simplicity is essential
  • The best architectures and designs emerge from effective, self-organizing teams
  • The team routinely reflects on past performance and seeks ways to do things better

Project Constraints – Time, Cost, and Scope

Agile - Time, Cost, and Scope Every project has the following constraints: time, cost, and scope. When a customer drafts a Firm Fixed-Price contract, they generally attempt to lock all three. How do they do this? It’s pretty simple:

  • Scope is locked by the production of a comprehensive requirements specification. The customer does this in an attempt to ensure that no requirement is missed and to give the service provider a detailed view of who they are and what they expect their software to be and to do.
  • Cost is locked because in their minds the requirements are detailed, explicit, and comprehensive so it should be easier for the provider to give a very accurate estimate up front. Furthermore, by creating the requirements specification, the customer generally also uses their business knowledge to formulate their own idea of how much it should cost to build the software.
  • Time is locked directly and indirectly from the first two constraints. Quite often, customers define their expected period of performance (POP) based on their estimate(s) from scope and cost.

Project Managers and developers understand this triangle of constraints and how the adjustment of one can affect the values of the others. So let’s start by looking at Agile under FFP from this standpoint.

Exploring the Customer’s Motivation for a Firm Fixed-Price Contract

Let’s think for a moment about the prospect of building a house. It’s an exciting topic to discuss, and just the thought of it gets my creative juices flowing! But as quickly as my creativity springs into action, my risk management facilities do too. My first thoughts deal with ensuring I hire a reputable, ethical, and licensed contractor. Obviously this isn’t something that I want to entrust to someone who will screw me in the end or whose work is shoddy. I am going to want to do my homework, call around and get references, look closely at past performance, consider quality of work, and many other things. Who wouldn’t do that?

I am also going to set myself a budget and communicate that budget to my contractor. I am then going to work with him to determine whether my desired plan, square footage, materials, landscaping, etc. are going to allow me to com in at or below my budget. I am going to want him to sign a contract that sets the maximum cost to me. Oh, wow! Guess what I just did? I hired a contractor under a Firm Fixed-Price contract! How dare me to do something like that! 😉

See, it’s not a bad idea, but just hold this thought and we will revisit it later in the post. Well, my motivation for wanting to ensure that the contractor I hire can deliver the product I want at or below my pre-defined cost limit is very logical and sensible. After all, I am not made of money and have a limited budget! That’s perfectly fine.

Before we begin discussing ways to execute Agile under FFP, we first have to take a look at the reasons why customers are preferring FFP contracts more and more these days. At a high level, the reasons are:

  • Internal politics and forces within the organization
  • Lack of trust in the potential contractor or service provider
  • Lack of understanding of development processes and methodologies
  • Belief that they know the true scope of the project better than anybody

So let’s continue our discussion of Agile under a Firm Fixed-Price contract with this in mind. The desire to lock a contractor into a set cost is not evil. From the customer’s standpoint, there is a limited budget, the consideration of ROI, political influences (both internal and external), trends in the business’ marketplace that are necessitating the software, and the list goes on and on. These are all very sensible and real considerations.

Internal Politics and Organizational Forces

Though we like to think of companies, departments, and teams within departments as cohesive, cooperative, supporting groups of people, in reality this more often than not is far from the truth. Whenever groups of people work “together” on a daily basis, there are dynamics that come into play that influence people’s behavior and decision-making. There is very often competition among managers, distrust, and empire building at work. Egos play a very large role in shaping the true function and nature of companies, departments, and teams. That is just the way it is. One fantastic way to tarnish your reputation as a manager is to be held accountable for a botched or failed development project.

We won’t dive too deeply into this discussion in this post, but I do plan to cover it in more detail in a later post because there are indeed forces at work within companies that may not be readily apparent on the surface but that become evident as we become more intimate with the organization and learn the dynamics and relationships among stakeholders. We should be mindful of that before we ever meet with a potential customer!

Lack of Trust in the Potential Contractor or Service Provider

Let’s face it, there will initially be a level of distrust of the contractor or service provider. That’s just human nature. If we go back to our example of building our house, we can immediately relate. Because of this, organizations feel compelled to exercise due diligence in fully understanding their own requirements before they ever seek a contractor to build a product. In the process, they uncover additional requirements, often debate the need for these requirements, and over the course of days, weeks, or months spend a great deal of time and money just understanding their own processes and needs. The end result of this effort is usually a comprehensive requirements specification.

Armed with this, they can, with a clear conscience seek contractors and bids because they now fully understand what they need and will be able to offer a unified front to all potential bidders that shows understanding of their needs and knowledgeable SMEs who can interface with these potential bidders. All in all, it sounds like a pretty good idea from the customer’s perspective.

Lack of Understanding of Development Processes and Methodologies

Although most organizations have good intentions in drafting requirements specifications for an FFP contract, the truth is that many of them just don’t truly understand how software development processes work and how the discovery, design, development, delivery, and quality assurance activities should really be carried out. When the comprehensive requirements specifications are created and finalized, they often contain all of the features and functionality that the customer believes to be the most important and the most crucial to the value of the software to be developed. They believe that by being as detailed as possible, the need for change later in the process is eliminated and therefore this document provides the true blueprint for what they need. Because of the belief that change will not be needed, they believe also that the provision of an estimate from the contractor should be easy and straightforward.

Belief that They Know the True Scope of the Project Better than Anybody Else (We Know What We Want!)

Functional managers and personnel have in-depth knowledge of the business processes and tasks that are required to carry out the day-to-day operations of the activities within their purview. This is invaluable to the development team during discovery and development. When it comes to creating requirements specifications though, this business process knowledge combined with lack of understanding of how development processes work can cause the customer to focus on defining scope based on their perception of what is  needed.

Building our House – An Evolutionary and Agile Process?

As I promised, we are now going to return to our example of building a house 🙂 So, I am now back in the driver’s seat and I am contacting potential contractors and discussing my wants and needs with them. Let’s assume that I find a contractor and when I meet with him I show him the blueprints that I have already paid an architect to create, and I give him an exact list of materials for everything within the house. I have already picked out external siding, roofing material, tile for the kitchen, bathroom, carpet for the living room, den, and bedrooms. In summary, I am a great customer and I just know what I want!

Based on my requirements, I have determined that the job should take 16 weeks and my budget is exactly $225,000. Great! I know where I stand and what I want! So I hire the contractor, he gets started, and is doing a great job! Then, as construction progresses and I see what the kitchen layout really looks like and how the tile I selected goes with the cabinetry, I realize that I don’t really like it! So I tell the contractor that he needs to stop laying that tile, and that I want to change the design. I also realize that I don’t really like the cabinets and want them taken out. He tells me that he can do that, but it will cost me $1,000 in labor to pull up the tile that is already down, and since they are several days into the tile laying, probably another $3,000 to put the new tile down, not to mention that I have to return what is left of the original tile to the tile store and buy the new tile. The cabinets have to be taken down, repackaged, and returned to the store and I now have to purchase new cabinets. He tells me that it will take a couple of days to remove the old cabinets and repackage them at an additional cost of about $1,000. This epiphany of mine could cost me an additional $15,000 and blow my schedule by more than a week!

Because I built my requirements specification based on what I honestly thought I wanted but didn’t account for added cost of changing my mind, I have now begun to blow my budget. The price he quoted me was based on my exact specifications, and we both agreed that those reflected what I wanted. Let’s not forget that my time estimate of 16 weeks is now blown as well.

So now let’s rewind to the beginning of my project and start over…

Imagine now that I hire a contractor who understands Agile principles. That’s right! Agile can be applied to processes other than software development 🙂 He reviews my specifications in detail, and when we meet the next time he tells me that he acknowledges that my budget is $225,000, and that I really want to see the house completed in about 16 weeks. But then we discuss my detailed requirements, and though he definitely believes that based on the blueprint he can build the house within my budget, he asks if I would be in favor of taking an Agile approach to ensure that I get the best value and that I become involved in the construction process on a routine basis. He tells me that we will take my general requirements as a starting point, but that we will manage the construction process in such a way that we identify the absolute must-haves first, then give ourselves the ability to adjust and make changes as we progress.

The more I think about it, the more I like this approach. If we get to a point where we realize that one of my requirements turns out to not be the best choice, we can make a change. After all, I did my homework and talked with several of his prior customers and all of them raved about his work and his methodology. At this point, I am feeling really good about things!

So we agree on the basic floor plan and we both sign the contract and he begins work. The foundation is poured, plumbing set in place, and the walls begin going up. On a daily basis, I go out to the site in the afternoon and look at what has been done that day and he and I discuss what he plans for the next day. Occasionally, I see things about which I am not sure, and he and I discuss the options. As they begin framing the internal walls, I have a chance to see the house everyday, and I am able to visualize the finished product and because I see things progress on a routine basis, there is always opportunity to make slight modifications without hugely affecting the timeline. Obviously, the contractor guides me as I decide upon changes and no change or decision for change is made in a vacuum.

The important point here is that he and I agreed to the cost and the time. Those just should not change. What we left slightly fluid is the scope. Now this may sound as if we just left this constraint undecided, but that would not be a true statement. We did agree on what the finished product should be, but because we are using an Agile approach, there is flexibility to make slight modifications as construction progresses. Early in the process, I communicated to him the things that are non-negotiable, the features and options that I just have to have. But because I am actively involved, at times I may realize that some of my must haves either really don’t make sense or that maybe I just didn’t think something through adequately.

This approach actually maximizes my value and allows the contractor and his crew to work at a somewhat pre-planned pace. The scope is somewhat flexible, but the time and budget/cost are fixed. We can still say that this is a firm fixed-price contract because it is. But we have implemented an Agile approach to allow us to get the most out of the things that truly matter, and because I am actively involved, I can set the focus on a daily basis if needed. It’s a win win for everybody! And even if there is some need to slightly extend the 16-week time constraint, I am more focused on the cost, so this isn’t a big deal.

Initial Discussions with the Customer – Fix the Time and Cost, Not the Scope

If we take our home building example and put ourselves in the contractor’s place, we are now faced with executing Agile under a firm fixed-price contract.

To give the customer the most bang for the buck, we should be willing to spend some time with them truly understanding their needs. Even though they have developed their comprehensive requirements specifications based on what they know, we may have an opportunity to present the value of Agile to them and attempt to convince the to work with us to define the true must haves, then allow the Agile process to let us give them the best value possible, with their continuous involvement.

The challenge here is to convince them that we can fix the time and cost, but we should approach the scope from an Agile perspective. This job requires salesmanship and confidence. Of course, past performance is never a bad thing and if we can provide them with satisfied customers from past projects who are willing to give us a great reference, we may harness enough leverage to sway them in our direction. If we can successfully convince them that their requirements are indeed valid but that we should rely upon user stories to help us use our professional business analysis and process engineering skills to guide them to the optimal solution, we have gained valuable credibility up front!

This is sometimes a delicate process and unless we have the right people to present the optimal approach (while not deviating from the fixed time and cost constraints) this may not be a feasible endeavor for us. I have known service providers to walk away from potential engagements because they realized that the customer was too set in their ways or that the customer refused to alter their stance.

Now, don’t misunderstand me. Walking away should be a last resort. We should first assess every RFP/RFQ that comes our way, and objectively evaluate the potential customer and project. If we go after projects that are either not a good fit for us or that we believe to be setting us up for failure from the beginning, we should opt to not pursue.

Again, I do not advocate just walking away from potential business. I have, however been doing this long enough to know that you should never set yourself up for failure. If we believe the customer’s requirements to be unreasonable and there is no sign of a change of heart on their side, we can never ignore the fact that not pursuing the project is always an option!

What if we Must Fix all Three Constraints?

So what happens if we pursue a potential customer, and are unsuccessful in convincing them to allow us to apply Agile in such a way that the scope is not necessarily set before the project begins, but we know the project is something that we can successfully develop and deliver?

Well then we can still use an “Agilistic” approach within our development model, involve the customer in the way that we would normally, but we have to make them understand that change will be something that is going to happen, due to the nature of development projects. As a result, they have to accept the risk that some requirements that have been pre-defined in the requirements specification may drop off completely if change does indeed come into play during development and the change affects the critical path with no option for extension.

I have seen this before. We could for example use Scrum and build our Product Backlog from the customer’s requirements specification. The main point of consternation for the Agile team though is the fact that we aren’t truly doing Agile, but a watered down version of it. Though we can say “we use Scrum”, the truth is that our endpoint is immovable. If we have to push tasks back into another sprint/iteration, those tasks still have to get done at some point, and barring the need for contract extension due to introduction of change by the customer, our development team may find themselves working overtime. Since this is an FFP contract, we are not going to be additionally compensated, so we just have to “suck it up” and get it done! That’s the painful truth and it happens all the time.

Promote the Agile Mindset Anyway!

But guess what? All is not lost here! As we progress through the development effort, we include the customer and enlist their active involvement. As the team conducts sprint planning meetings, we can invite stakeholders to observe. We can even invite them to our Daily Scrum meetings to observe the process and learn. We certainly sell the benefits of Agile in the Sprint Review meetings where we present completed functionality to them. A key point here is that by involving them continuously, conducting desk reviews routinely, and doing mini-demos throughout each sprint, nothing they see in the Sprint Review meeting will be a surprise! Wow, they already know what they are going to see. This minimizes the chance of change anyway, and if an issue is spotted during a sprint and change is truly warranted, every stakeholder is involved immediately and a decision can be made and documented.

Why is anything in the previous paragraph important? Because of one golden point: though we may have been locked into time, cost, and scope for this project, if we can educate the customer about the true benefits of Agile on a daily basis, we stand a better chance of swaying their thinking for the future!

But Very Few Organizations Fully Use Agile anyway! What’s the Big Deal?

The truth is that in reality, most teams don’t truly implement “pure” Agile anyway. I’m sure that we all know that, but it has to be said. Whose fault is this? That’s a little complicated, and it is not my intent to cast blame. I do however think there is a need to have an open dialog about this subject.

If you are of a pure Agilist mindset, this is a source of pain! If you are someone who believes the end justifies the means, then you don’t really lose any sleep over the discussion. I am a mix of the two. I truly want to be able to enjoy the full benefits of a purely Agile environment, but at the end of the day I also know that due to the nature of what we do, there will be times when we just can’t get what we want.

It is ultimately the contractor’s responsibility to effectively sell the methodology to each and every customer. As they do this and successfully deliver quality software and provide great value for the customer, they gain credibility in the form of past performance. But they have to start somewhere!

I think ultimately, it all goes back to fixed budgets, inherent distrust in potential contractors, and organizational dynamics.

Advertisements

Scrum Methodology – Agile Software Methodologies

Posted on

Introduction

In our last post, we discussed Agile, its origins, basic concepts, and how it fits into the organization. While we often speak of Agile generically, we have to discuss the development methodologies that share the common philosophical beliefs of Agile.

Scrum

Scrum is the most prevalent of the Agile methodologies used in software development today, and rightfully so. With Scrum, development is executed via a series of short efforts called sprints. A sprint typically lasts from two to four weeks. The actual duration of each sprint is determined by the customer and the development team, but a sprint should not be too long. We’ll talk more that sprints later.

Scrum Terms and Concepts

Before we begin our discussion of Scrum, we first need to discuss some important terms and concepts associated with Scrum.

  • Scrum Team – the Scrum team is generally made up of less than 10 developers, business analysts, testers, etc. but can be larger if the product necessitates it. The team is totally self-sufficient and able to execute sprints effectively. In Scrum, roles such as architect, engineer, developer, etc typically go out the window in lieu of a sense of a team effort and an “all-for-one and one-for-all” mindset.
  • Scrum Master – the Scrum Master is a team member or manager whose primary responsibility is making the team as productive as possible. The Scrum master should be very well-versed in Scrum concepts and ideals and should insulate the team from outside influences and remove impediments that stand in the way of progress.
  • Daily Scrum – one of the key concepts of Scrum is the daily scrum. This is a quick, stand-up meeting of the development team. The purpose of the daily scrum is to keep the team on track on a daily basis by discussing the following three things for each team member: (1) what did you do yesterday? (2) what are you going to do today, and (3) do you have any impediments? The Scrum Master leads the daily scrum and ensures that the meeting is productive and stays on track.
  • Product Backlog – the Product Backlog is the all-inclusive list of every feature and component of every application that makes up the project as a whole.
  • Sprint Backlog – the Sprint Backlog is created from the Product Backlog each sprint during the Sprint Planning meeting. It is made up of all the tasks to be completed within a specified sprint.
  • Sprint Planning – the Sprint Planning meeting takes place before each sprint and is attended by the Scrum team members. The purpose of the Sprint Planning meeting is to define the work to be done by each person on the team for that sprint. Once this work has been defined and assigned, work items are moved from the Product Backlog to the Sprint Backlog.
  • Sprint Retrospective – one of the most effective ways to ensure continuous improvement within a Scrum team is to learn from mistakes. The Sprint Retrospective meeting, which takes place and the end of a sprint allows the team members to discuss the happenings of the prior sprint and identify things that could have been done better.
  • Sprint Review – the Sprint Review meeting is attended by the Scrum team and as many stakeholders as is necessary to demonstrate the new functionality and discuss its suitability to the needs of the business. The Sprint Review is kind of a show-and-tell where the team gets to present to the customer. This has always been my favorite part of a sprint! 🙂
  • Product Owner – the Product Owner is the project’s primary stakeholder and is usually a member of functional management within the organization.

Scrum in Practice

Now that we know the key terms associated with Scrum, let’s talk about how the Scrum development process actually works!

The necessary members of the team meet with the customer before work ever begins and identify to whatever extent possible the overall needs of the customer. These needs are not necessarily going to be truly complete and remember that Agile methodologies love change! But we do want to at least have a good understanding of what needs to be done to satisfy the customer’s needs and ensure that the results are in alignment with these needs.

Once we have identified the needs, we build the Product Backlog. As we discussed in the previous section, the Product Backlog is the full, all-inclusive list of the features needed. The business analysts, who are Scrum team members as well then do their best to decompose those needs into quantifiable requirements. A good requirement is a requirement that is testable, so it is imperative that the requirements are developed in such a way that the developers are able to understand them and further decompose specific tasks necessary to develop the requirement in its entirety.

Once we know (to the best of our ability) the Product Backlog, we can decide roughly how many sprints are needed to develop the functionality and assess the actual duration of each sprint. Based on the complexity of the features and the dynamics of the team, we may say that a three-week sprint is optimal, but sprints are typically from two to four weeks in length. Once we identify this duration, we generally want to stick to it and not deviate.

Before we begin a sprint, the Scrum team holds a Sprint Planning meeting. In this meeting, they review the Product Backlog and each developer decides just how much he/she can take on and complete and often high-level estimates are given based on the concept of shirt sizes (S, M, L, XL, XXL, etc). Other approaches are used, but the point of the Sprint Planning meeting is to determine and vote upon just how long the team thinks each item should take to develop and test. The Sprint Planning meeting may last from an hour to an entire day, but the outcome is the movement of work items from the Product Backlog to the Sprint Backlog and assignment of specific tasks to individuals.

When the sprint begins, the Scrum team works to develop and test the exact functionality defined in the Sprint Planning meeting. During the sprint, the Daily Scrum is instrumental in keeping each member of the team and the team as a whole on track and it is imperative that each team member knows what is going on around him/her and how the team as a whole is performing toward delivery of the feature(s) or functionality at the end of the sprint. The Daily Scrum should be as short in duration as possible, and most teams prefer to literally stand up during the meeting. Though the Scrum team should have a deep sense of camaraderie and sometimes a need to get off of the subject 🙂 the Scrum Master must keep things on track and make the team stay focused on the purpose of the meeting. During the Daily Scrum, the Scrum Master goes around the room and asks every team member the following questions:

  1. What did you do yesterday?
  2. What are you going to do today?
  3. Are there any impediments preventing you from getting things done?

If there are valid impediments, it is the Scrum Master’s responsibility to remove those impediments through whatever means necessary. Generally, the Scrum Master should be a person with adequate authority and credibility with the customer to be able to communicate with the necessary people to resolve any impediments encountered. This is vitally important to the successful implementation of Scrum!

Remember that as part of Agile, stakeholders are actively involved as often as is possible. It is not uncommon for stakeholders to be physically involved on a daily basis. During the sprint, developers may routinely do desk reviews with a stakeholder or stakeholders to verify proper functionality during development. A desk review is an informal, impromptu discussion/demonstration of a specific function with the customer.

At the end of a sprint, the team formally presents the new functionality to the customer and receives feedback in a Sprint Review meeting. If the sprint has been properly executed and the customer has been actively involved during development, the functionality that the customer sees should bring no surprises. It is not uncommon during Sprint Review meetings for the customer to engage in in-depth discussion about the business needs and it is also fairly common for there to be a realization than maybe some key element is missing. Thus, change is introduced into the mix and this is documented by the Scrum team. This change may likely go into the Product Backlog for inclusion in a future sprint.

Finally, at the end of each sprint, the Scrum team conducts a Sprint Retrospective meeting. This meeting is attended solely by members of the Scrum team and the purpose is to give the team the chance to reflect on anything and everything that can be done to function and perform more effectively going forward.

Agile Methodology – Using Agile to Develop Better Software and Reduce Risk

Posted on Updated on

Introduction

Imagine an enterprise software development project where the customer says “we are going to take a long time to get this done and we don’t expect to see any results for at least two years”. Can you imagine it? Me neither, and the truth is that it will probably never happen 🙂 So what is reality? In the real world of enterprise software development, the key for any development team is to provide maximum value to and work closely with the customer, to be able to build a culture of true ingenuity, and to be able to meet the customer’s changing needs in a way that there is minimal disruption, if any.

In the early days of software development, it was not uncommon for months to pass before any development began, and once development started, it could be months or years before any type of finished product was ready for testing. The requirements definition and gathering process was often very long, and in many cases the development team was isolated from the customer.

Once requirements were complete and development had begun, change was just not something that was easily entertained. Let’s keep in mind that concepts such as Continuous Integration and Configuration Management were unknown and use of source control repositories was not as mainstream as it is now. A change in requirements was just quite difficult to accommodate and was generally frowned upon.

The Agile Methodology

Agile was first introduced in February 2001 via the Agile Manifesto, a document created by a group of developers who met in Snowbird, Utah to discuss the principles behind a way to do lightweight software development. Since then, the Agile Methodology has grown and been widely adopted by software development teams and companies worldwide.

When we discuss Agile Methodologies, we must also mention Scrum, Lean Software Development, Kanban, Dynamic Systems Development Method (DSDM), and Extreme Programming, since these methodologies all share the same philosophy.

Agile - Scrum DSDM, Extreme Programming

In a nutshell, Agile is about communication, teamwork, collaboration, adaptability, iteration, feedback, and of course, agility! The development initiative is broken down into efforts of short duration and change is not only expected, it is embraced by all stakeholders. To successfully implement Agile, an organization must embrace its concepts and philosophies at all levels.

Agile provides a framework with which teams can maintain focus on rapidly delivering working software and providing true business value, even in environments where the technical and functional assets and landscape may vary or change routinely. We can say that Agile allows development teams to provide maximum business value through the delivery of truly valuable, working software that meets the business needs. How do we know that the software truly meets the business needs? Because all of the stakeholders are involved and quality and scope verification take place in short, iterative cycles. Deviations from the true purpose of a feature or piece of functionality can be identified quickly and corrected in an agile manner.

If we go back to the Agile Manifesto, there are 4 key points that it outlines.

It favors:

  • Individuals and interactions over processes and tools
  • Working software over comprehensive documentation
  • Customer collaboration over contract negotiation
  • Responding to change over following a plan

The key principles behind these points are outlined below (read these carefully):

  • Satisfy the customer through early and continuous delivery of working software
  • Change is welcomed, even late in the development process
  • Working software is delivered frequently, typically at intervals from two weeks to two months
  • Developers work directly with functional personnel/SMEs on a daily basis
  • Projects are built around motivated, capable people and they are given an environment that allows them to succeed
  • Face-to-face communication is critical
  • The primary measure of progress is working software
  • The development pace must be sustainable
  • Continuous attention to technical excellence and good design enhance agility
  • Simplicity is essential
  • The best architectures and designs emerge from effective, self-organizing teams
  • The team routinely reflects on past performance and seeks ways to do things better

If Agile is properly implemented, with buy-in from stakeholders at all levels of the organization, productivity and competitive advantage are maximized and cost is minimized. Of course Agile is not necessarily about reducing cost, but when properly implemented and managed that is a side effect that is very nice.

Let’s discuss the key points above in greater detail.

Favor Individuals and Interactions over Processes and Tools

The greatest processes and tools in the world are worthless without the right people effectively communicating and interacting. Regardless of the size or maturity of the organization, we should start with people then decide the appropriate processes and tools to make our Agile development more effective.

Favor Working Software over Comprehensive Documentation

In the days of waterfall development, I can remember the latter stages of larger projects being consumed with the creation of mounds of documentation! I remember working with teams of technical writers as they produced both functional and technical documentation for software deliverables. With Agile, any documentation that is created is usually created while development takes place. The rapid develop/release approach facilitates concurrency among developers, business analysts, and writers, and in an Agile environment the business analysts often produce the documentation.

Regardless of the use of Agile or not, it is rare that a customer not require some type of documentation and there is nothing wrong with that. But, in an organization that is truly Agile-oriented, working software is always the primary, core deliverable.

Favor Customer Collaboration over Contract Negotiation

Let’s face it, as long as development teams provide services for customers, there will always be contractual obligations. But when we use the term “contract negotiation” we imply an us versus them mentality and this is detrimental to the Agile process! For the Agile process to be effective, we need contractual vehicles that are flexible and that are developed and written to effectively handle change.

It is not uncommon to work with a client via a Firm Fixed Price (FFP) contract. From the customer’s perspective, FFP is preferable because it transfers risk to the service provider. In this case, Agile is still a valid development methodology IF the customer understands and truly embraces Agile concepts. The difficulty sometimes comes into play when the customer insists on defining functionality up front, forces the service provider to sign a contract whose estimates are based on these initial requirements, then tries to introduce scope creep as the project progresses. I sometimes refer to this as “agile under waterfall”, but Agile is still a good fit for such an endeavor. Obviously, a FFP contract is not the preferred vehicle under which to execute Agile, but it is still attainable if all stakeholders are well-versed in and embrace Agile concepts.

Favor Responding to Change over Following a Plan

Although detailed project plans and fancy Gantt charts are impressive, they are not useful with Agile. You read that right! Agile is based on release schedules where the prescribed functionality may be defined, but it is understood that it may change. Project progress within Agile is based on burndowns. Regardless of the actual functionality delivered, progress is still made over time. The total estimate may change due to newly-identified requirements or scope changes from the customer.

Agile and Risk Management

Prior to the emergence of Agile, a large number of software development projects failed or were cancelled with little or no working functionality in place. Teams often spent months or years working on a project with nothing tangible to show for their efforts. In many cases, projects were developed and delivered only to find that they did not meet the true needs of the business! Imagine after months or years of work and possibly millions of dollars of investment to discover that your needs haven’t even been met!

From the Project Management Institute’s (PMI) standpoint, Risk Management is a key knowledge area and something that is very high on the Project Manager’s priority list. All project managers should understand risk. It is just an inherent dynamic within any project and one that has to be understood, and either avoided or mitigated. So, what is risk? By its formal definition, risk is something that can or may occur and that could cause unexpected or unanticipated outcomes. Project managers know that risk is not always something negative. Opportunities are risks as well. But risk is something that, positive or negative, has to be identified, quantified, and managed. The situation, environment, project, people, etc determine when, where, and how risks are managed.

Agile reduces risk through through stakeholder involvement and rapid, iterative development and release. This means that evaluation of scope verification take place routinely, which effectively reduces risk.

Organizational Threats to Agile

The greatest single threat to Agile is management! More specifically, functional management with unrealistic expectations. In some organizations, Agile is nothing more than a buzzword because the stakeholders have not been educated in its fundamental concepts.

Earlier in this post, I mentioned the need for Agile to be understood and embraced by every stakeholder, from the top down. Without this understanding and support, it will likely fail or at the very least leave managers with a bad taste due to the fact that the development Project Manager tells them “we can certainly modify our approach and give you functionality X but requirement W is going to have to be pushed back to a future iteration.” In the case of FFP, requirement W may just have to drop off entirely!

With Agile, change is welcomed, even late in the development process, but in the case of FFP, it is possible that certain changes can significantly affect the project end date and thus necessitate contract extension.

Conclusion

So, Agile is a software development methodology that fosters rapid delivery of valuable, working software in an iterative manner. It values people and communication over processes and tools. It prefers working software over comprehensive documentation. It favors active and dynamic involvement of the customer and proper, effective identification of the true needs of the business over contract negotiation. It advocates the ability to nimbly respond to change, even late in the development process to following a detailed, pre-defined plan.

It can be argued whether or not it negates the need to perform Risk Management, but it is safe to say that with constant and active involvement of the customer and self-organizing, professional, competent, and productive development teams with a true dedication to the customer’s mission and a clear understanding of the customer’s needs, it can be enormously successful and a win-win for both the customer and the development team.

I will reiterate this final point because it is so hugely important – Agile MUST be understood and embraced by every member of the organization, from the CEO to the day-to-day tactical and functional personnel. Without this complete organizational buy-in and effective communication and interaction between all involved stakeholders, it will not be successful.

In the next post, we will discuss Scrum in detail.

Dependency Inversion Principle in C# – SOLID Design Principles – Part 5

Posted on Updated on

Overview

In our introduction to the SOLID Design Principles, we mentioned the Dependency Inversion Principle as one of the five principles specified. In this post we are going to discuss this design principle. Though a discussion of Dependency Injection and Inversion of Control are warranted here, we will save those topics for another post. I want to discuss the Dependency Inversion principle as simply and directly as possible.

Dependency Inversion Principle – Introduction

The Dependency Inversion Principle is a software design principle that provides us a guideline for how to establish loose coupling with dependencies from higher-level objects to lower-level objects being based on abstractions and these abstractions being owned by the higher-level objects.

The definition reads as follows:

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

These two items state that when building software, classes should be loosely-coupled based on abstractions (interfaces) and the details of the implementation should be encapsulated within the concrete classes that contain the logic. From top-down perspective, higher-level classes have only loose dependencies with lower-level classes.

What does that mean?

Dependency Inversion is about reversing the standard and conventional direction of dependencies from higher-level objects to lower-level objects by ensuring that the interfaces that dictate the functionality of the lower-level objects (i.e. the contracts that mandate what the lower-level objects must do) are owned by the higher-level objects. After all, if we consider our software holistically, the higher-level orchestrating objects are more valuable than the lower-level objects because they are the objects whose functionality we are most likely going to have the desire or need to extend.

Because the interfaces (contracts) that define what but not how the lower-level objects function are owned by the higher-level consumers, the higher-level objects do not rely upon how a lower-level object provides its functionality. Instead, they define what they need the lower-level objects to do and the lower-level objects provide the functionality/behavior demanded.

What Problems Are Solved with Dependency Inversion?

Poorly written software that is difficult to maintain and that has too many “hard” dependencies is a nightmare! How many times have we seen objects with numerous dependencies that cause us to shy away from trying to make changes? In my career I have seen more than I would care to remember!

When proper design principles are not considered early in the process, we often end up with code that is a tangled web of dependencies and when we are forced to make changes we often encounter unforeseen breakages that occur because of these dependencies.

When we implement the Dependency Inversion Principle, we reduce the coupling between “pieces” of code. When we build dependencies based upon interfaces (contracts), we introduce greater stability over time and we reduce the “hard” dependencies from concrete class to concrete class. Thus we reduce the possibility of introducing instability over the course of time. By coding to interfaces, we force our implementing classes to honor their agreements while the objects that consume them have no need to know how they honor them.

When we build software components that are reusable and consumable and that have external dependencies, we can find great value in the Dependency Inversion Principle’s objectives.

A word of caution – we cannot just program to interfaces and say that we have implemented Dependency Inversion! I will admit that this is a great idea in and of itself but by itself it does not give us Dependency Inversion. To truly realize the benefits, we have to ensure that the interfaces we use are owned and controlled by the higher-level objects. In other words, the top-level consumers own the contracts that must be honored by the lower-level providers.

So, using interfaces alone is NOT Dependency Inversion! Using interfaces to define what is needed by higher-level objects and writing lower-level objects to provide those needs by honoring the needs of the consumers in a way that the consumers have no reason to know anything about how the lower-level objects do what they do is moving in the right direction.

It is reasonable to say that classes are always going to have dependencies on other classes. You just can’t have properly-built object-oriented software without having dependencies between classes. But when changes are needed, it is very advantageous to make sure that changes have minimal impact on the overall functionality of the classes with dependencies on the classes changed. When we have tight coupling between classes, it is difficult to do this.

Let’s consider two types that we all know – an Engine and a Starter. We can say that an Engine has a dependency on a Starter as shown in the diagram below.

Dependency Inversion Principle

If we assume here that every Engine has a Starter that’s a pretty reasonable assumption. We can say that when we instantiate an Engine object we must also create a Starter object to start the Engine. With this model, the two are tightly-coupled.

But what if we have to change the starter and replace it with a different one? What if we have to change something in the Starter class? Such a change could potentially break the functionality of the Engine. How can we prevent that?

First, let’s make a statement: an Engine requires a component that is able to start it. It does not specifically require a Starter. With this in mind we can begin to decouple the two. Look at the next design with the understanding that the dotted gray line signifies ownership and control of types:

EngineStarter2

We’ve created an IStarter interface and since the Starter class implements this we are in good shape, right? Not exactly. Yes, the Engine having a dependency on the IStarter interface is an improvement since any class that implements IStarter can be used but we don’t have a hard dependency on Starter. We are moving in the right direction but we’re not there yet!

Let’s think about this from the standpoint of Dependency Inversion. To invert the dependency, the higher-level object must define and control the interface. Think about this: what if the Starter object changed in a way that forced a change to the IStarter interface? That could potentially break the Engine class’s logic because although it only expects a type that implements IStarter, the IStarter interface does not belong to the Engine class and is not defined based on what it needs. Therefore, the perceived loose coupling here is not real because the higher-level object (Engine) does not truly have control over the IStarter interface.

To implement Dependency Inversion, the higher-level modules must have control over the interfaces that they use to define their requirements for lower-level objects. Let’s revisit our logical design this way:

Dependency Inversion Principle

Now we’re getting somewhere! The Engine class owns the IStarter interface and thus controls what the classes that implement IStarter must provide. Nice! With this scenario, a change to a class that implements the IStarter interface that changes the interface is not valid.

So where is the inversion? If we go back to the first Engine/Starter diagram above, we see that changes within that scenario bubble from the bottom up. Changes to lower-level components force changes to higher-level components. With our new design, since the higher-level component owns and controls the interface, any change in the lower-level component that breaks its interface implementation is not valid unless the higher-level object allows it and the IStarter interface is changed as well. If the Engine must be changed in a way that affects the IStarter interface, the forcing of change is top down. In other words, the Starter must be changed as a result of a mandated change by the Engine. Make sense?

Another Example of Dependency Inversion

Let’s look at a simple example to which we can all relate. Think about the electric appliances in your house. They all have voltage requirements. In the U.S. we generally have 110, 220 and in some cases 440-volt power. If you’ve ever noticed, the plugs for each voltage are different.

In the context of Dependency Inversion, we can think of an appliance as a higher-level consumer and of the power supply in our house as a lower-level object that provides functionality needed by the appliance to operate. The appliance defines and owns its defines its needs and publishes those needs via its physical plug “interface”.

Though this sounds overly simple, it is a valid example of Dependency Inversion. So when we have an appliance that requires 220-volt service and we plug it into a 220-volt outlet, we expect for it to just work. We know that the plug is capable of providing 220-volt power because (1) the plug on the wall matches the plug on the appliance, and (2) the receptacle and wiring were put in place by a licensed electrician who knows and understands the electrical codes and the functional requirements of any device that uses 220-volt power. In other words, they power supply honors the “contract” between it and any device or appliance manufactured to use it.

From a software development perspective, we can say that the appliance is the higher-level object, the power cord and plug are the contract that defines what is needed by the higher-level object, and that the power supply itself is the lower-level object that is capable of honoring the needs of the consumer. We know that it can provide the needs of the consumer because in this case the physical characteristics of the receptacle (wall plug) tell us that it “implements the proper interface”. We can even say that the plug/receptacle connection is an abstraction. The appliance has no need to understand how the receptacle provides 220-volt power just that it does.

Refactoring Our Original Engine/Starter Design Sample

Now that we have covered Dependency Inversion and considered a couple of simple examples, let’s now return to the Engine/Starter design to which we’ve been applying SOLID design principles over the past few posts.

To recap this design, way back in the first post on the Single Responsibility Principle (Part 1) we originally started with a simple design that represented an Engine and its dependency on a Starter to provide ignition functionality. Our first design looked like this:

Single Responsibility Principle - SOLID Design Principles - Improved design

Then, in the second post on the Open-Closed Principle (Part 2) we refactored the design to make it open to extension but closed to modification. In the original design, we identified the three types of starters to be electric, pneumatic, and hydraulic. Because the implementation details of each unique type of starter were so different, we moved from a single Starter type to distinct types for each. We then created an interface named IStarter that they all implemented.

Open Closed Principle

Due to the fact that each starter type had internal functionality that was so different, to ensure that our derived (implemented) classes being substitutable for their base types (or interfaces), we segregated our interfaces as we see below. You can refer back to these posts for more information – Liskov Substitution Principle (Part 3) and Interface Segregation Principle (Part 4).

Dependency Inversion Principle - Sample class layout

Our starting code looks like this:

namespace SOLIDDesignPrinciples
{
    #region Base Classes

    public class Component : IComponent
    {
        public string Brand
        {
            get;
            set;
        }

        public string Model
        {
            get;
            set;
        }
    }

    #endregion Base Classes

    #region Interfaces

    public interface IComponent
    {
        string Brand { get; set; }
        string Model { get; set; }
    }

    public interface IStarter : IComponent
    {
        IgnitionResult Start();
    }

    public interface IElectricStarter : IStarter
    {
        Battery Battery { get; set; }
    }

    public interface IPneumaticStarter : IStarter
    {
        AirCompressor Compressor { get; set; }
    }

    public interface IHydraulicStarter : IStarter
    {
        HydraulicPump Pump { get; set; }
    }

    #endregion Interfaces

    #region Starter Types

    public class ElectricStarter : Component, IElectricStarter
    {
        public Battery Battery
        {
            get;
            set;
        }

        public IgnitionResult Start()
        {
            //code here to initiate the electric starter
            return IgnitionResult.Success;
        }
    }

    public class PneumaticStarter : Component, IPneumaticStarter
    {
        public AirCompressor Compressor
        {
            get;
            set;
        }

        public IgnitionResult Start()
        {
            //code here to initiate the pneumatic starter
            return IgnitionResult.Success;
        }
    }

    public class HydraulicStarter : Component, IHydraulicStarter
    {
        public HydraulicPump Pump
        {
            get;
            set;
        }

        public IgnitionResult Start()
        {
            //code here to initiate the hydraulic starter
            return IgnitionResult.Success;
        }
    }

    #endregion Starter Types

    #region Starter Support Components

    public class Battery : Component
    {
        public bool IsCharged
        {
            get
            {
                /*we could write logic here to handle the
                  validation of the battery's charge
                  for now, we will just return true */
                return true;
            }
        }
    }

    public class AirCompressor : Component
    {
    }

    public class HydraulicPump : Component
    {
    }

    #endregion Starter Support Components

    #region Enums

    public enum IgnitionResult
    {
        Success,
        Failure
    }

    #endregion Enums
}

Basically, this code representation of the different types of Starter types required to fulfill the ignition functionality for an Engine type can be summarized as follows:

  • There are three distinct types of Starters – ElectricStarter, PneumaticStarter, and HydraulicStarter.
  • Each Starter type implements the IStarter interface which defines the properties that are common to all Starter types, and each implements its specific interface type. The specific interface type is necessary because each type of starter is unique in its own operational requirement(s).
  • The IStarter interface implements the IComponent interface.
  • Each Starter type inherits the Component base class and each Starter interface implements the IStarter interface.
  • The lower-level components required by the Starter types also inherit Component (since they are components too).

If we include the Engine itself in our dependency chain, we have a clear dependency hierarchy. Let’s look at it from an abstraction standpoint:

  • Engine has a dependency on a Starter, or rather anything that is an IStarter.
  • An IStarter can be an IElectricStarter, IPneumaticStarter, or IHydraulicStarter.
  • An IElectricStarter has a dependency on a Battery.
  • An IPneumaticStarter has a dependency on an AirCompressor.
  • An IHydraulicStarter has a dependency on a HydraulicPump.

Hold on a minute! Weren’t these supposed to all be abstractions? Yes they were, so let’s take a look at the lower-level objects and do some further decomposition.

If we are going to build dependencies based on abstractions all the way down the chain, we need to think a little more about what I will call the second-level objects. In the case of a Battery, in reality there are about five distinct types of automobile batteries! So to provide a proper abstraction from the ElectricStarter to a Battery, we must make this dependency an abstraction too.

If we refer to this resource,  we lean more about our previous statement that there are five distinct types of car batteries – just check it out if you are interested :). To be correct in our design and to make our code as closed to modification as possible, we must define each type as a distinct type within our design. These distinct types will then be set as dependencies of the ElectricStarter abstractly.

To do this, we first make the Battery class an abstract base class.

public abstract class Battery : Component, IBattery
    {
        public bool IsCharged
        {
            get;
            set;
        }

        public abstract void EvaluateCharge();
    }

We made the EvaluateCharge() method abstract to force our derived Battery classes to override its functionality.

We are also going to create specific battery type classes and although the actual logic behind how to validate the battery’s charge may vary significantly based on the type of battery, each type must still offer the EvaluateCharge() functionality. Make sense?

So here are our new classes for each type of battery:

public class WetFloodedBattery : Battery, IBattery
{
    public override void EvaluateCharge()
    {
        //logic here to evaluate the charge
        this.IsCharged = true;
    }
}

public class CalciumCalciumBattery : Battery, IBattery
{
    public override void EvaluateCharge()
    {
        //logic here to evaluate the charge
        this.IsCharged = true;
    }
}

public class VRLABattery : Battery, IBattery
{
    public override void EvaluateCharge()
    {
        //logic here to evaluate the charge
        this.IsCharged = true;
    }
}

public class DeepCycleBattery : Battery, IBattery
{
    public override void EvaluateCharge()
    {
        //logic here to evaluate the charge
        this.IsCharged = true;
    }
}

public class LithiumIonBattery : Battery, IBattery
{
    public override void EvaluateCharge()
    {
        //logic here to evaluate the charge
        this.IsCharged = true;
    }
}

If you look at these classes and say “they’re all the same!”, yes they are. Imagine that the charge validation logic is very different for each distinct type. That logic is not the point of this example, so we are not touching that. For this sample, all of the overridden methods just set the IsCharged property value to true 🙂 We have segregated each distinct type to honor the Single Responsibility Principle and give our classes only one reason to change. You can refer back to that post if you would like.

Next, to keep things simple, we have made our ElectricStarter class generic. When we create a new instance of an ElectricStarter we will have to inject an IBattery type into the constructor. This way we are using Constructor Injection to inject the ElectricStarter’s battery dependency upon creation. We will cover Dependency Injection in another post, so don’t get stuck on what we just said here. Just understand that we are requiring every instance of an ElectricStarter to be supplied with an instance of an IBattery type.

Let’s take a look at our new ElectricStarter class:

public class ElectricStarter<T> : Component, IElectricStarter<T>
    where T : IBattery
{
    public ElectricStarter(T battery)
    {
        this.Battery = battery;
    }

    public T Battery
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        this.Battery.EvaluateCharge();
        if (this.Battery.IsCharged == true)
        {
            return IgnitionResult.Success;
        }
        else
        {
            return IgnitionResult.Failure;
        }
    }
}

We should also note that we have made our IElectricStarter interface generic.

public interface IElectricStarter<T> : IStarter
{
    T Battery { get; set; }
}

So far so good. Now let’s return to our Engine class and make some changes.

First, we will make the Engine.Start() accept the IStarter instance.

public interface IEngine : IComponent
{
    IgnitionResult Start(IStarter starter);
}

#endregion Interfaces

#region Engine

public class Engine : Component, IEngine
{
    public IgnitionResult Start(IStarter starter)
    {
        return starter.Start();
    }
}

#endregion Engine

If we then flip over to the Program.cs class of our sample C# Console application, and add code to instantiate an Engine, a starter, and a battery and run it we will see a successful engine start!

namespace SOLIDPrincipleSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            IEngine engine = new Engine();

            IBattery battery = new LithiumIonBattery();
            IElectricStarter<IBattery> starter = new ElectricStarter<IBattery>(battery);

            IgnitionResult result = engine.Start(starter);

        }
    }
}

So now that we have defined this design, are working with dependencies based on abstractions, and have an Engine that we can start, let’s consider the ownership of the interfaces we have defined from a Dependency Inversion standpoint.

First, remember that the higher-level objects must own the interfaces. If we consider our model from the top down, we start with the Engine.

The Engine depends on a Starter, or more appropriately an IStarter. Since we created interfaces for each of the three types of starters (IElectricStarter, IPneumaticStarter, IHydraulicStarter) the Engine should own and have control over those interfaces.

Each type of Starter has a dependency on some lower-level object. In the case of the ElectricStarter, there is a dependency on a Battery, or should we say an IBattery. As we built our code we discovered that there are actually five different kinds of car batteries and we created classes for each and each class implemented the IBattery interface. Therefore, the ElectricStarter should own the IBattery interface. We could go so far as to say that the Engine could conceivably own it as well and that would not necessarily be wrong, but we want to segregate ownership where it truly belongs.

If you want to create your own C# console application and play with this a little more, the code for the Engine, starters, and all other classes/interfaces is below. You can copy and paste this into a single .cs file if you want and experiment.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SOLIDDesignPrinciples
{
    #region Base Classes

    public class Component : IComponent
    {
        public string Brand
        {
            get;
            set;
        }

        public string Model
        {
            get;
            set;
        }
    }

    public abstract class Battery : Component, IBattery
    {
        public bool IsCharged
        {
            get;
            set;
        }

        public abstract void EvaluateCharge();
    }

    #endregion Base Classes

    #region Interfaces

    public interface IComponent
    {
        string Brand { get; set; }
        string Model { get; set; }
    }

    public interface IStarter : IComponent
    {
        IgnitionResult Start();
    }

    public interface IElectricStarter<T> : IStarter
    {
        T Battery { get; set; }
    }

    public interface IPneumaticStarter : IStarter
    {
        AirCompressor Compressor { get; set; }
    }

    public interface IHydraulicStarter : IStarter
    {
        HydraulicPump Pump { get; set; }
    }

    public interface IBattery : IComponent
    {
        bool IsCharged { get; set; }
        void EvaluateCharge();
    }

    public interface IEngine : IComponent
    {
        IgnitionResult Start(IStarter starter);
    }

    #endregion Interfaces

    #region Engine

    public class Engine : Component, IEngine
    {
        public IgnitionResult Start(IStarter starter)
        {
            return starter.Start();
        }
    }

    #endregion Engine

    #region Starter Types

    public class ElectricStarter<T> : Component, IElectricStarter<T>
        where T : IBattery
    {
        public ElectricStarter(T battery)
        {
            this.Battery = battery;
        }

        public T Battery
        {
            get;
            set;
        }

        public IgnitionResult Start()
        {
            this.Battery.EvaluateCharge();
            if (this.Battery.IsCharged == true)
            {
                return IgnitionResult.Success;
            }
            else
            {
                return IgnitionResult.Failure;
            }
        }
    }

    public class PneumaticStarter : Component, IPneumaticStarter
    {
        public AirCompressor Compressor
        {
            get;
            set;
        }

        public IgnitionResult Start()
        {
            //code here to initiate the pneumatic starter
            return IgnitionResult.Success;
        }
    }

    public class HydraulicStarter : Component, IHydraulicStarter
    {
        public HydraulicPump Pump
        {
            get;
            set;
        }

        public IgnitionResult Start()
        {
            //code here to initiate the hydraulic starter
            return IgnitionResult.Success;
        }
    }

    #endregion Starter Types

    #region Starter Support Components

    public class WetFloodedBattery : Battery, IBattery
    {
        public override void EvaluateCharge()
        {
            //logic here to evaluate the charge
            this.IsCharged = true;
        }
    }

    public class CalciumCalciumBattery : Battery, IBattery
    {
        public override void EvaluateCharge()
        {
            //logic here to evaluate the charge
            this.IsCharged = true;
        }
    }

    public class VRLABattery : Battery, IBattery
    {
        public override void EvaluateCharge()
        {
            //logic here to evaluate the charge
            this.IsCharged = true;
        }
    }

    public class DeepCycleBattery : Battery, IBattery
    {
        public override void EvaluateCharge()
        {
            //logic here to evaluate the charge
            this.IsCharged = true;
        }
    }

    public class LithiumIonBattery : Battery, IBattery
    {
        public override void EvaluateCharge()
        {
            //logic here to evaluate the charge
            this.IsCharged = true;
        }
    }

    public class AirCompressor : Component
    {
    }

    public class HydraulicPump : Component
    {
    }

    #endregion Starter Support Components

    #region Enums

    public enum IgnitionResult
    {
        Success,
        Failure
    }

    #endregion Enums
}

Points to Ponder

One more thing to think about with Dependency Inversion is how abstraction is handled within the various layers of an application or object hierarchy. I have written numerous application frameworks in my time as an architect and developer, and one thing that holds true when writing this type of code is that you find yourself within the various levels writing abstract code with the intent of it being used concretely at some later point in time. It is necessary to rely upon generic abstractions within lower levels and allowing the ultimate consumers/clients to determine the exact implementation details. With Dependency Inversion, we can effectively build objects that perform the necessary tasks without knowing the exact details of each task at the time we write them. This idea may sound a bit counterintuitive at first, but it is something to think about as you explore this topic more deeply.

Additional Links

The SOLID Design Principles
The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)

Single Responsibility Principle in C# – SOLID Design Principles – Part 1

Posted on Updated on

Overview

In our introduction to the SOLID Design Principles, we mentioned the Single Responsibility Principle as one of the five principles specified. In this post we are going to dive into this design principle with a very simple example in C#.

The Single Responsibility Principle states that a class should have only one reason for change. The greater the number of responsibilities, the more reasons a class will have for change. Seems pretty simple, right? When you consider it for what it is, it is pretty simple.

I am most definitely NOT a mechanic, and I do not claim to know a great deal about combustion engines, but I think that a subset of an engine’s functionality is a great way to illustrate the SOLID design principles. The engine in your automobile is a marvel of modern engineering and has been designed to function optimally with each component having minimal dependencies on other components. An engine is maintainable because the various parts/components are easily removed and replaced. This is how our applications should be written.

So let’s consider an automobile engine from the standpoint of the starter mechanism. In case you don’t know, your engine has a component called a starter that is attached to the engine, has electrical connections to allow it to draw power from the battery, and when you engage your ignition switch via a key or pushbutton, the starter is energized. When it is energized, it forces the engine to turn over and the combustion process begins. If you would like to learn more about how a starter works, here is a great article 🙂 Haha. So let’s move on, shall we?

IMPORTANT: For the sake of simplicity, we are going to assume that for this example, the one hard rule that will not ever change is the fact that there will always be a Starter object and a Battery object associated with an Engine. If we don’t make this assumption and declare it as a “rule”, the scope of our design changes could make the illustration of the concept overly-complicated and I really want to keep it simple here and discuss the principle in the simplest terms possible.

Furthermore we are going to use our design in this post to continue to apply SOLID design principles one by one.

Design #1 – Not so Good

Let’s suppose that we wanted to represent an Engine’s ignition/starter functionality in a few C# classes. If we didn’t understand the Single Responsibility Principle, we might build our classes similarly to this:

Engine Ignition Initial (Invalid) Class Design - Single Responsibility Principle

Based on the design shown above, let’s consider this code:

public class Engine
{
    public IgnitionResult Start(Starter starter, Battery battery)
    {
        //we would put code here to handle the logic for checking
        //whether or not the batter is charged

        //then we check the result of our logic
        if (battery.IsCharged)
        {
            //we could put logic here to handle
            //the actual ignition process
            return IgnitionResult.Success;
        }
        else
        {
            //uh oh! the battery is not charged
            //Failure!
            return IgnitionResult.Failure;
        }
    }
}

public class Starter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }
}

public class Battery
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public bool IsCharged
    {
        get;
        set;
    }
}

public enum IgnitionResult
{
    Success,
    Failure
}

Let’s think about this code as it is written. It makes sense that we would have an Engine class, a Starter class, a Battery class, and an IgnitionResult enum. So far so good. But when we look in the Engine class and read the Start() method, we can see that there may be more than one reason why the Engine class would have to be changed. It is responsible for too many things. Any logic associated with how to start the engine is contained within the Start() method as is the “validation” of determining whether or not the battery is charged.

Consider the following questions:

  1. What if we installed a different type of Battery and the logic associated with verifying its charge state changed?
  2. What if we installed a different type of Starter and the logic associated with how it actually works internally changed?

If either of these things changed we would have to modify our Engine class to accommodate the change(s). The key point here is that the Engine class has more than one responsibility and per the Single Responsibility Principle this is not good.

Design #2 – Better!

Now let’s reconsider our design, remembering that each class should have not more than one reason for change.

First, the logic for actually handling the Starter’s ignition process should be moved to the Starter class and the Starter itself should contain a Start() method which will be invoked by the Engine’s Start() method.

Next, the battery charge validation logic should be moved to the Battery class since the battery itself knows better than anything how to validate its own state. Sounds sensible, right?

Let’s take a look at the improved design:

Single Responsibility Principle - SOLID Design Principles - Improved design

So what did we do? First, we removed anything to do with the “internal workings” of the Starter and the Battery out of the Engine class and into each respective class. Now, based on the assumption we made above that stated in this scenario an Engine will always have exactly one Starter and exactly one Battery, the Engine class has only one reason for change as do the Starter and Battery classes.

Keep in mind that as we get into the other SOLID Design Principles we are going to begin abstracting things so that we will have a truly “pluggable” design but for now we are working directly with concrete Starter and Battery objects. That will change as we move through the other principles and we will begin to see continuous improvement!

We left the Brand and Model properties in the Starter and Battery classes. Obviously we can see that this is not an ideal design, but remember – we are focusing on the Single Responsibility Principle for now! These properties are inconsequential now.

Based on the design shown above, our new code looks like this:

public class Engine
{
    public IgnitionResult Start(Starter starter, Battery battery)
    {
        return starter.Start(battery);
    }
}

public class Starter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start(Battery battery)
    {
        //since the Battery class now contains that actual charge validation
        //logic, the Starter merely checks the value of that property
        //and the Battery takes care of the rest
        if (battery.IsCharged)
        {
            //we can put the ignition logic here
            return IgnitionResult.Success;
        }
        else
        {
            return IgnitionResult.Failure;
        }
    }
}

public class Battery
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public bool IsCharged
    {
        get
        {
            //we can put logic here for the battery
            //to validate its charge and return
            //a result
            return true;
        }
    }
}

public enum IgnitionResult
{
    Success,
    Failure
}

So we have a better design from the standpoint of the Single Responsibility Principle. The goal is to modify all of our classes so that each class has one and only one reason for change. Since the example is very simple, accomplishing this is pretty easy. As designs become more complex, the amount of time to create the correct design can grow tremendously but the time required is very well worth it long-term because it will yield a much more maintainable and effective design overall.

In the next post, we will dive into the Open-Closed Principle. See the links below for all posts related to the SOLID Design Principles.

The SOLID Design Principles
The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)

Open-Closed Principle in C# – SOLID Design Principles – Part 2

Posted on Updated on

Overview

In our introduction to the SOLID Design Principles, we mentioned the Open-Closed Principle as one of the five principles specified. In this post we are going to dive into this design principle and work with a very simple example in C#.

The Open-Closed Principle states that modules should be open for extension but closed for modification. Simply stated, this means that we should not have to change our code every time a requirement or a rule changes. Our code should be extensible enough that we can write it once and not have to change it later just because we have new functionality or a change to a requirement.

If you consider the number of times that code is changed after an application makes its first ‘release’ and you begin to quantify the actual time (and expense) associated with repeated changes to code over the life of the application, the actual development cost is probably not going to surpass the ongoing maintenance costs.

Think about it, when you change existing code, you have to test the changes. We all know that 🙂 But to be complete in your implementation, you also have to perform regression testing to ensure no unforeseen bugs have been introduced either as direct or indirect results of your new changes! In short, we don’t want to introduce breakages as the result of modifications – we want to extend functionality.

But let’s be realistic for a second. To interpret the Open-Closed Principle to say that we can NEVER change our code is a bit over-the-top in my opinion. I can tell you from years of practice that this is simply never going to happen! There will always be code changes as long as there are requirements changes – that’s just the way it is. You can however greatly minimize the actual code changes needed by properly designing applications in the beginning, and the Open-Closed Principal is one of the five SOLID design principles that allow you to do that.

In the last post, we began building a few classes that represent the starter/ignition system of an automobile engine. As is the theme for all posts here, we kept the example scenario very simple and kept the code simple to illustrate the design principle.

We are going to take the code that we wrote in the Single Responsibility Principle post and modify it further to illustrate the Open-Closed Principle. We have removed the Battery class because in the context of this discussion it is really not significant and introduces unnecessary noise.

So let’s get going! For more background on how we arrived at the design below, refer back to the the previous post.

The code looks like this:

public class Engine
{
    public IgnitionResult Start(Starter starter)
    {
        return starter.Start();
    }
}

public class Starter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //logic to initiate start
        return IgnitionResult.Success;
    }
}

public enum IgnitionResult
{
    Success,
    Failure
}

Let’s consider this design, and also consider the two notions described by the Open-Closed Principle. Modules that conform are:

  1. Open for Extension – the behavior can be extended in a variety of ways as the requirements change
  2. Closed for Modification – existing, stable code should not be changed

With these things in mind, let’s discuss what we need to do with our Engine/Starter scenario to allow us to minimize changes going forward.

Open-Closed Principle – C# Example

So to get started, let’s take the code from the last post (shown above) and add a little meat to it! We purposely left the body of the Start() method of the Starter class kind of bare because we weren’t concerned with that when we discussed the Single Responsibility Principle. But now we are very interested in that so let’s add a StarterType enum, a StarterType property to our Starter class, and let’s add some dummy logic within the Start() method to make this all work. Remember, this initial code is NOT going to adhere to the Open-Closed Principle – we are modifying the original code in preparation for this.

Design #1 – Not so Good

First, we will add the StarterType enum:

public enum StarterType
{
    Electric,
    Pneumatic,
    Hydraulic
}

Then we will add a property to the Starter class:

public StarterType StarterType
{
    get;
    set;
}

Finally, we will add some logic to our Starter class’s Start() method that performs some action based on the StarterType specified.

public IgnitionResult Start()
{
    //initiate the starter based on the StarterType
    if (this.StarterType == SOLIDPrincipleSamples.StarterType.Electric)
    {
        //initiate the electric starter
        return IgnitionResult.Success;
    }
    else if (this.StarterType == SOLIDPrincipleSamples.StarterType.Pneumatic)
    {
        //initiate the pneumatic starter
        return IgnitionResult.Success;
    }
    else
    {
        //initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

Okay, we know that we could have one of three types of starters – electric, pneumatic, or hydraulic. Seems reasonable that we would write an if block that checks the type and performs some type of action, right? Well, not really. What if our requirements change and we have to now accommodate another type of starter that we hadn’t anticipated? Well, we will have to change our Starter class, and we really don’t want to do that!

So what can we do?

Design #2 – Much Better

The solution is actually pretty straightforward and it involves thinking in terms of extending NOT modifying! Here’s how we can do that:

First, let’s rethink our Starter class. Instead of having a single concrete Starter class, we will create a concrete class for each type of starter and consider each as a distinct type within our design. To bring all those together, we will create an interface which we will name IStarter. Each of our three starter types will implement this interface and each will contain its specific logic for initiating the engine start functionality.

Our new design looks like this:

Open Closed Principle

So here are our new classes and our new interface:

public class Engine
{
    public IgnitionResult Start(IStarter starter)
    {
        return starter.Start();
    }
}

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    IgnitionResult Start();
}

public class ElectricStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

public enum IgnitionResult
{
    Success,
    Failure
}

So now we have three concrete classes, one for each type of starter, a single interface which is implemented by each of the three concrete starter classes, and our StarterType enum is no longer needed! With this design, if we need to add a new type of Starter, we do NOT have to change our existing code but instead we can add a new class for that type of starter and change the consuming code very slightly to expect the new type where needed. We are not going to dive into a Factory pattern in this post, but that is an effective way to handle the Open-Closed Principle.

So to recap, if we write code that is open for extending but closed to modification we are much better off! The Open-Closed Principle provides us guidance for how to accomplish this. Now keep in mind that this was a simple example, but as I say all the time, simple examples are the best ways to illustrate virtually any development topic.

In the next post, we will dive into the Liskov Substitution Principle. See the links below for all posts related to the SOLID Design Principles.

The SOLID Design Principles
The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)

Liskov Substitution Principle in C# – SOLID Design Principles – Part 3

Posted on Updated on

Overview

In our introduction to the SOLID Design Principles, we mentioned the Liskov Substitution Principle as one of the five principles specified. In this post we are going to dive into this design principle and work with a very simple example in C#.

As you study the SOLID Design Principles, you will notice there is a great deal of overlap among the individual principles. While discussing the Liskov Substitution Principle, we are going to take a quick dive into the Interface Segregation Principle as well, but not overly so as the next post will discuss that more deeply. We will however take a look at how to segregate interfaces in pursuit of not violating the Liskov Substitution Principle.

Formal Definition

The Liskov Substitution Principle states that if for each object m1 of type S there is an object m2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when m1 is substituted for m2 then S is a subtype of T.

Useful Definition

Let’s reword the definition above to actually be understandable. In a nutshell, the Liskov Substitution Principle  includes two main points:

  1. Derived classes should be substitutable for their base classes (or interfaces).
  2. Methods that use references to base classes (or interfaces) have to be able to use methods of the derived classes without knowing about it or knowing the details.

So what in the world does all that mean? It means that our derived classes (or implementing classes) cannot modify or break the functionality dictated by their base classes or implemented interfaces.

Let’s just dive in and take a look at the Engine/Starter class design that we have been using for the first two posts on the SOLID Design Principles.

As of the completion of our post on the Open-Closed Principle, here is our design:

Open Closed Principle

 

We created separate concrete classes for the different types of Starters used to start our Engine and we made each class implement the IStarter interface. This allowed us to migrate our code to be open to extending but closed to modification.

So far so good, right? Well, maybe not!

Let’s look at the code from the last post that matches the class diagram above:

public class Engine
{
    public IgnitionResult Start(IStarter starter)
    {
        return starter.Start();
    }
}

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    IgnitionResult Start();
}

public class ElectricStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

public enum IgnitionResult
{
    Success,
    Failure
}

Design #1 – Not Good At All!

This all works fine in the simple example because we are assuming that all types of Starters are the same. But what if they aren’t? What if, for example an ElectricStarter makes use of a Battery, a PneumaticStarter makes use of an AirCompressor, and a HydraulicStarter requires a HydraulicPump object to function? Well, if we were hell-bent on keeping our IStarter interface we could do something like this:

First we would have to create classes for Battery, AirCompressor, and HydraulicPump. Then we would add properties for each to the IStarter interface. Let’s just do it and see how it looks 😦

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    Battery Battery { get; set; }
    AirCompressor Compressor { get; set; }
    HydraulicPump Pump { get; set; }
    IgnitionResult Start();
}

public class ElectricStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get;
        set;
    }

    public AirCompressor Compressor
    {
        get
        {
            throw new NotImplementedException("An Electric Starter does not use an AirCompressor.");
        }
        set
        {
            throw new NotImplementedException("An Electric Starter does not use an AirCompressor.");
        }
    }

    public HydraulicPump Pump
    {
        get
        {
            throw new NotImplementedException("An Electric Starter does not use a HydraulicPump.");
        }
        set
        {
            throw new NotImplementedException("An Electric Starter does not use an HydraulicPump.");
        }
    }

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get
        {
            throw new NotImplementedException("An PneumaticStarter does not use a Battery.");
        }
        set
        {
            throw new NotImplementedException("An PneumaticStarter does not use an Battery.");
        }
    }

    public AirCompressor Compressor
    {
        get;
        set;
    }

    public HydraulicPump Pump
    {
        get
        {
            throw new NotImplementedException("An PneumaticStarter does not use a HydraulicPump.");
        }
        set
        {
            throw new NotImplementedException("An PneumaticStarter does not use an HydraulicPump.");
        }
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get
        {
            throw new NotImplementedException("A HydraulicStarter does not use a Battery.");
        }
        set
        {
            throw new NotImplementedException("A HydraulicStarter does not use an Battery.");
        }
    }

    public AirCompressor Compressor
    {
        get
        {
            throw new NotImplementedException("A HydraulicStarter does not use an AirCompressor.");
        }
        set
        {
            throw new NotImplementedException("A HydraulicStarter does not use an AirCompressor.");
        }
    }

    public HydraulicPump Pump
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

public class Battery
{
}

public class AirCompressor
{
}

public class HydraulicPump
{
}

public enum IgnitionResult
{
    Success,
    Failure
}

Alright! So we added the properties to our IStarter interface and implemented them in each concrete class, so all is well, right? Not exactly.

Although we aren’t necessarily violating the Open-Closed Principle, we are in violation of the Liskov Substitution Principle and honestly this is just really not a good design! Although we implemented all of the possible properties of our classes in our IStarter interface, the classes that implement our interface are NOT substitutable for it. Why not? Because their behavior is not consistent across the different types of starters. Although the interface is in place, the implementing classes don’t truly implement it when in play.

Consider this: suppose we create an instance of an ElectricStarter and use an instantiated Battery object to set its Battery property? That works pretty well. But now let’s imagine another developer consuming our code and seeing the Compressor property as being a usable public property for the ElectricStarter and trying to either get it or set it. What happens? A NotImplementedException is thrown 🙂 This is not consistent behavior! The interface contains a property for an AirCompressor, a developer consuming our code can reasonably expect that to work, despite the fact that any of us “reasonable” people might look at that and ask “why would an ElectricStarter need an AirCompressor?” 🙂

So you may ask “why not just remove the NotImplementedExceptions in the properties that don’t matter for each class and just go with it?” The answer to that is easy – any time you see properties or methods within derived (or implementing) classes that do not do what their name suggests (or what they should be doing) that is a big red flag or a not-so-good design! As responsible designers/developers, we must handle invalid conditions and operations correctly and deliberately and not place properties or methods in our interfaces or classes that surprise their consumers by what they do or how they behave – make sense? Thus instead of having a property or method that actually does nothing is not a good idea and the presence of such items signals trouble!

The Liskov Substitution Principle is very focused on extrinsic public behavior and the fact that consumers expect predictable and constant behavior for published/implemented interfaces. Our design does NOT provide that!

Design #2 – Much Better

To rectify this flawed design, we need to think about another SOLID design principle – the Interface Segregation Principle. If we think about our IStarter interface as the starting point, we can consider the following things:

  1. The properties/method that are common to ALL starter types are: Brand, Model, and Start().
  2. The properties that are specific to each starter type are: Battery, Compressor, and Pump.

With these things in mind, the first thing that we need to do is to make use of not one interface but four! Take a look at our revised interfaces below:

public interface IStarter
{
    string Brand { get; set; }
    string Model { get; set; }
    IgnitionResult Start();
}

public interface IElectricStarter : IStarter
{
    Battery Battery { get; set; }
}

public interface IPneumaticStarter : IStarter
{
    AirCompressor Compressor { get; set; }
}

public interface IHydraulicStarter : IStarter
{
    HydraulicPump Pump { get; set; }
}

I picked the interface segregation as our starting point because it sets the stage for the changes that need to be made to the concrete classes. This design is far superior from the standpoint of the Liskov Substitution Principle!

So now let’s rewrite our Starter classes to implement their respective interfaces:

public class ElectricStarter : IElectricStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public Battery Battery
    {
        get;
        set;
    }       

    public IgnitionResult Start()
    {
        //code here to initiate the electric starter
        return IgnitionResult.Success;
    }
}

public class PneumaticStarter : IPneumaticStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public AirCompressor Compressor
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the pneumatic starter
        return IgnitionResult.Success;
    }
}

public class HydraulicStarter : IHydraulicStarter
{
    public string Brand
    {
        get;
        set;
    }

    public string Model
    {
        get;
        set;
    }

    public HydraulicPump Pump
    {
        get;
        set;
    }

    public IgnitionResult Start()
    {
        //code here to initiate the hydraulic starter
        return IgnitionResult.Success;
    }
}

We now have a design that makes far more sense. Yes, we went from one interface to four, but this is not a bad thing when we consider the SOLID Design Principles collectively, which is a very good thing to do.

In the next post, we are going to dive more deeply into the Interface Segregation Principle. See the links below for all posts related to the SOLID Design Principles.

The SOLID Design Principles
The Single Responsibility Principle (SRP)
The Open-Closed Principle (OCP)
The Liskov Substitution Principle (LSP)
The Interface Segregation Principle (ISP)
The Dependency Inversion Principle (DIP)