NDepend

Improve your .NET code quality with NDepend

Continuing Our Clean Architecture Example in C Sharp

Continuing Our Clean Architecture Example in C#

After a somewhat long delay, it’s time to finally continue our series on clean architecture. This is the second post in the inner series in which we show you a quick implementation of said architecture and the third post in the overall series. In case you haven’t read the previous posts, please do so by using the links in the series layout below:

Without further ado, let’s continue our implementation.

Wrapping Up the First Use Case

If you recall the previous post, you’ll remember that we created the class for the first use case. But we haven’t fully implemented it yet since we’ve pretty much stubbed out all of the classes and methods that the use case was supposed to use. Now, let’s go back and provide real implementations for all the supporting classes in order for our use case to work properly.

If we go now and just try to build the app in its current form, it won’t work. And that’s because our code lacks a lot of references. For instance, we’ve just added the file for the “Task” entity, but we haven’t properly referenced the “Domain” project from the “UseCases” project. Remember that “Domain” doesn’t reference—actually, it isn’t even aware of—any other project. That way, our application will remain faithful to the dependency inversion principle, the “D” in SOLID.

With that out of the way, let’s finish the first use case. In the previous post, a commenter pointed out that I didn’t write my tests first. That is, to my shame, correct. In order to atone for that, I’ll finish the implementation of “AddTask” in true TDD fashion, starting with failing tests by making them pass and then refactoring if needed.

I’ll start out by creating a new project that will store my unit tests for the “UseCases” project. I’ll call it “UsesCases.Test,” like in the image below:

Now, instead of deleting the default class as I did in the previous post, I’ll just rename it and use it to store my tests for the first use case.

Next, it’s time to install NUnit and make the test project reference the production one. I’ll leave that out for the sake of brevity. If you don’t know the drill, there are resources out there that cover this.

We’re now ready to go. Time to create our first test. Many people start out by covering the happy paths first. I tend to do the opposite and begin with the degenerate cases. S, we’ll start by covering the scenario where someone tries to add a task with an empty title.

Our test method will be called “Creation_RequestWIthEmptyTitle_Fails,” following Roy Osherove’s naming convention for tests. The complete code for the test is what follows:

It shouldn’t come as a big surprise that this doesn’t compile. For starters, we’re referencing two classes that don’t even exist: “StoppedClock” and “FakeTaskRepository.” These classes are supposed to be test doubles (more specifically fakes) that we’ll provide the constructor of AddTask. We won’t be implementing the real classes for a while. And this is a good thing because we are able to delay the implementation of infrastructure concerns like the database access layer.

But even so, we need to implement at least our fakes, right? Let’s do it then, in the quickest and easiest possible way. And by that I mean let’s make use of Visual Studio’s conveniences. I’ll just hover with the cursor over the names of the non-existing classes, wait for the lightbulb icon to show up, and click on that handy message that lets me generate a class in a new file.

We’ll do this for both “StoppedClock” and “FakeTaskRepository.” It’s important to notice here that while the interfaces live in the “UseCases” namespace, the implementation itself will reside in the test project. That makes sense when you consider that these implementations only exist for the sole purpose of enabling unit tests. There’s no reason for them to be available in the production assembly.

Anyway, now we must go to the files VS generated for us and make the classes actually implement the interfaces they’re supposed to implement. The code for “StoppedClock” ended up looking like this:

Its implementation matches its name, right? It’s literally a stopped clock since it always gives the same date and time. What about the code for the fake repository? Here it goes:

Our fake repository does literally nothing! Well, since the contract for “ITaskRepository” defines that Save doesn’t return anything, doing nothing will suffice for now.

After a little bit of work, the code for our test method looks like this:

It’s finally compiling. But does the test itself pass? Well, bad news then.

And why is it failing? Because the “Fail” method in the “AddRequestResult” still throws a “NonImplementedException” instead of, you know, doing some real work. Besides, the same thing is true for the “Success” method.

Let’s fix this. And by “this,” I mean the “Fail” method. Since that’s the method, that’s causing our test to fail. We’re not even touching “Success,” at least for now. The complete code for the class now looks like this:

As promised, we haven’t touched “Success.” Does the test pass now? Nope, not yet.

What is causing the failing? Easy. Our class doesn’t override “Equals.” Let’s take care of that.

Now the test finally passes!

Let’s get to the next degenerate case. If some client tries to add a task with a due date already in the past, the operation should also fail. Let’s write the test case for that below:

At the start of the method, I configure my “StoppedClock” to always return the same date and time (March 7th, 2017, at 9 AM, with an offset of minus three hours from UTC) when asked for the current time. Then I proceed to instantiate a fake repository (same as the previous test). At last, I create a request, but this time instead of an empty string, I pass some text. Then, to populate the “DueDate” property, I pass a date that’s one day before the date my clock considers as being “current time.”

What should happen when I run the tests? The two of them pass!

That’s It For Today

That’s it for now. It might not feel like much, but we’ve definitely made progress toward the final solution by writing code in true TDD fashion. We’ve also picked up some good unit testing best practices that are listed below:

  • Explicitly name the system under test variable as “SUT.” I’ve learned this with Mark Seeman aka ploeh.
  • Don’t automatically name our fakes as “Fake[ImplementedInterface].” Sometimes you can come up with a more self-documenting name. For example, “StoppedClock” gives up the main characteristic of this fake. It qualifies its “fakeness,” so to speak.
  • Follow Roy Osherove’s very useful naming convention for tests.

See you all next time!

log4net vs NLog A Comparison of How They Affect Codebases

Log4net vs NLog: A Comparison of How They Affect Codebases

Ah, the old “versus” Google search.  Invariably, you’re in the research stage of some decision when you type this word into a search engine.  Probably not something like Coke vs Pepsi.  Maybe “C# vs Java for enterprise projects” or “angular vs react.”  Or if you landed here, perhaps you’re looking at “log4net vs NLog.”

With a search like this, you expect a certain standard script.  The writer should describe each one anecdotally, perhaps with a history.  Then comes the matrix with a list of features and checks and exes for each one, followed by a sober list of strengths and weaknesses.  Then, with a flourish, I should finish with a soggy conclusion that it really depends on your needs, but I maybe kinda sorta like one better.

I’m not going to do any of that. Continue reading Log4net vs NLog: A Comparison of How They Affect Codebases

Text over the depths of the ocean

Imperative Programming in Depth

Programming languages come in all shapes and sizes: interpreted vs. compiled, weak vs. strong typing, low-level vs. high-level, terse vs. expressive… There are many buckets you can put a programming language into, even though not all are equally meaningful.

One very common way people classify languages is to organize them into paradigms. You can think of a paradigm as a group of languages that share similar characteristics. There are many paradigms currently in use: procedural, functional, and object-oriented. Many of these terms are often misused or confused; there’s also some degree of overlap between different paradigms, which definitely doesn’t make things easier.

Add all of that together and what you get is a landscape that’s not too easy for a beginner to grasp.  In today’s post, we’ll try and fix this situation by giving you a clear picture of the imperative programming paradigm.

Continue reading Imperative Programming in Depth

Separation of Concerns layered over dripping yellow liquid

Separation of Concerns, Explained

Software development is a very young field, particularly when you compare it to, say, medicine or law. Despite this, there’s no shortage of wisdom pearls, which accumulated in the decades that preceded us.

One interesting phenomenon I’ve observed in myself over the years—and I’m sure there’s a name for it—is that some of these sayings sound like they must be right, even if I don’t really understand them the first time I hear them. For instance, in my post about the SOLID principles, I mentioned how the SRP’s definition—”each class should have just one reason to change”—just ticks the right boxes for me in some way that I can’t even pinpoint. 

Unfortunately, just hearing a phrase and acknowledging that it kind of sounds right doesn’t do much to really make you understand the topic, right?

Then why do so many in our industry act like that’s the case? I’ve lost count of how many times I’ve seen experienced developers toss around catchphrases like this as if they’re able to automatically inject the necessary information into beginners’ heads.

In this spirit, I’ve decided to demystify one of these catchphrases that happens to be one of my favorites: “Separation of Concerns.” What does that mean and why should you care? That’s what today’s post is all about.

First of All: What Are Concerns?

Before we get to explain why concerns are best off when they’re separated, we should take a step back and understand what “concern” even means in the context of software development.

The current Wikipedia definition says this:

In computer science, a concern is a particular set of information that has an effect on the code of a computer program.

Frankly, I think that’s quite vague and not particularly useful. So instead, let’s try to come up with some examples. Think about a boring line-of-business application, such as a payroll application. What are its concerns?

  • Interaction with the user.
  • Generation of charts, graphs, and reports of different kinds.
  • Calculation of employee’s salaries, benefits, severance packages and so on.
  • Persistence of all the relevant data into some persistence storage.

In short, each one of the areas that an application covers and does something is a concern.

Concerns in the Software World: Why Keep’ Em Apart?

Suppose you and your team successfully release an application. You’re getting great feedback and all is nice in the world.

Then, like they always do, a requirement for a new feature comes in. And for the sake of the argument, this is a feature you absolutely have to do. You can’t refuse it (let’s say the competitor’s product already has it).

What would the potential risks be when you add this feature? We could cite a lot of them, but it all boils down to two things in the end really. First, it’s possible that the feature could be very hard to write because you’d have to write a lot of code in a lot of different places. You also run the risk of breaking current features that paying customers already depend on.

Keeping your concerns separated will decrease the above risks. If all the code related to a certain concern is kept together (for example, in the same layer) it becomes easier to change it. You don’t have to make a myriad of changes scattered throughout the code base. You don’t have to “look for” where a certain task is implemented since the code is organized according to its concerns.

Finally, you don’t risk breaking code unrelated to what you’ve implemented since this other code doesn’t even reside in the same place in the application.

Let’s get back to our boring payroll example. Think about the concerns we’ve identified for it. Would it make sense that a request to support Oracle Database beyond the current PostgreSQL could cause the app to miscalculate salaries? Or could a change in the location of a GUI element make a SQL query stop working? By keeping each concern as separated as possible, we can prevent those things from happening.

Let’s now see an example of what it looks like when concerns are not separated.

Desperation of Concerns—A Quick Example

Let’s write a toy app based on Roy Osherove’s String Calculator Kata. It’s going to be a very simple WinForms app with just one text field and one button. The user should input integer numbers separated by a comma and then click the button. The application will then calculate and display the sum of the inputted numbers. Only non-negative integers are allowed, though. If the input string contains any character that is not a non-negative integer, then the sum is aborted and an error message should be displayed along with the list of offending characters.

The following images depict a successful and an unsuccessful sum, respectively:

It isn’t that hard to write code for the application you can see above. The following listing shows the code for the “Add” button:

As you can see, the developer hasn’t kept concerns separated! We have error-handling, business logic, and UI code all in one big mess. How can we make things better? Why should we? It’s not hard to imagine that a new requirement could come in and ask to deploy the application as a console app. How could we do that without duplicating a lot of code? It should be very easy to do if concerns were separated. If all the string calculator logic itself was contained in an isolated location, it’d be a matter of adding a new project—a console app—to our solution and writing a few lines of code.

And how could we make this example a little bit better? First, I’ll add a new project to the solution. This new project will be of the type “Class Library.” Then, I’ll add a new class to this project, which I’ll name “StringCalculator.” The code in the class should be as follows:

All you need to do now is to edit the form’s code in order to use the new class. I’ll leave that as an exercise for the reader.

Write Software As If Your Users Were Blind. Teach As If You’re a Beginner.

Recently, I came up with this sentence: “Write software as if your users were blind.” I’ve been using this phrase as a mental framework for thinking about separation of concerns, particularly regarding decoupling logic from presentation. When I spot some code in the application’s domain layer mentioning visual aspects such as color names, I ask myself, “Would this still make sense if the people who’ll use this app were blind?” (And they might as well be, why not?).

If the answer is “no,” then I know I must move that code to the presentation layer, keeping in only the domain layer code related to the concepts themselves.

When teaching someone, you should always be aware of the curse of knowledge. Try to have empathy with your students. Put yourself in their shoes and try to remember when you were a beginner yourself. Don’t just toss catchphrases around; take the time to turn them into valuable lessons that will inform and empower the developers of tomorrow.

In Defense of the SOLID Principles

In Defense of the SOLID Principles

From posts that politely offer their criticisms to others that outright deem them “for dummies,” it seems that bashing the SOLID principles is all the rage nowadays.

The fact that SOLID is being criticized isn’t a bad thing. The problem is that I don’t think the arguments against it are really that good. There’s some valid criticism, but it seems that a large portion of it comes from some misunderstanding of the principles. Some people even read obscure agendas in them.

This post is meant to investigate some of the more common criticisms of the SOLID principles, offering my take on why I believe they’re not quite justified.

SOLID Principles: Some Background

In object-oriented design, the SOLID principles (or simply SOLID) are a group of five design principles meant to make code cleaner, more flexible, and easier to change. The principles were compiled by Robert C. Martin, although he didn’t invent them. In fact, these specific principles are a subset of many principles Martin has been promoting over the years.

The name SOLID is an acronym, made up of the names of five principles. Namely, these principles are

  • the single responsibility principle (SRP),
  • the open-closed principle (OCP),
  • the Liskov substitution principle (LSP),
  • the interface segregation principle (ISP), and
  • the dependency inversion principle (DIP).

Martin himself didn’t come up with the acronym; rather, it was Michael Feathers that suggested it to him, several years after he was already teaching them. I’ll come back to this later because, believe it or not, the name itself is at the center of some criticisms.

Before we get to the meat of the article, I think it’d make sense to do a quick overview of the five principles so those of you who are familiar with them can get a reminder and those who aren’t can get a sense of what we’re talking about.

Continue reading In Defense of the SOLID Principles

Clean Architecture C# — an example

Starting A Clean Architecture Example in C#

It’s time for the second part of our series about clean architecture. As promised in the first post, we’re going to show you a sample application in C#, to demonstrate what a clean architecture implementation might look like.

Even though our sample application will be minimalist, it’s still too much for a single post. We want to keep things light and easy for you, so we’ll have to break this post into two or three parts.

Don’t worry though: at the end, I’ll connect all the dots and things should (hopefully) make sense. And all the generated code will be publicly available for you to download and study on your own. Continue reading Starting A Clean Architecture Example in C#

CQRS Understanding from First Principles

CQRS: Understanding From First Principles

There seems to be no end to the choices you have for architecture when building an application. You don’t want to fall victim to cargo cult programming, so you need to truly understand the options available. Today, we’ll focus on one option, called CQRS.

CQRS leads to a clean architecture that’s easy to maintain. Let’s take a look at the underlying principles of CQRS. This will help you understand what the benefits are and whether you want to use it in your applications. Continue reading CQRS: Understanding From First Principles

An Introduction to Clean Architecture

An Introduction To Clean Architecture

It seems to me that the topic of software architecture has attracted a lot of interest in the last few years. And among many different flavors and styles of software architecture, there’s one that attracts even more interest than the others. I’m talking about the clean architecture, proposed and evangelized by Robert C. Martin, a.k.a. Uncle Bob. (And for the rest of this post, it’s simply referred to as “clean architecture.”)

By employing clean architecture, you can design applications with very low coupling and independent of technical implementation details, such as databases and frameworks. That way, the application becomes easy to maintain and flexible to change. It also becomes intrinsically testable.

We’ll start today’s post not by explaining what clean architecture is right away. We’ll first dive into the problems that high coupling can cause in software projects. Then we’ll proceed to see the more mainstream solution to these problems.

Finally, we’ll explain the flaws with this solution, showing why and how clean architecture can be the piece of the puzzle that was missing for your application to achieve its full potential.

“Desperation” of Concerns

If you have at least a couple years of software development experience under your belt, then I can almost guarantee you’ve heard the term “separation of concerns.” It’s a principle that shows up quite often when talking about software architecture.

One of its incarnations is in the form of advice: “Separate presentation from business logic.” It’s very sound advice and I agree with it wholeheartedly, but the problem is that it’s not so easy or clear how to put it into practice, especially for beginners.

In practice, what ends up happening is that logic business frequently leaks to the application’s UI. And the same can go the other way around: it’s not so rare to find business logic code concerning itself with UI concepts, such as colors, markup languages, font sizes, and what have you.

And things can get even worse when you add data access to the mix. How does one free oneself from this mess?

Continue reading An Introduction To Clean Architecture