Posts Tagged C#

JetBrains Rider: Removing “private” from C# code

I prefer NOT to see the “private” keyword in C# code. As a quick update to that post, here’s how to set up JetBrains Rider to not add “private” when it creates code, and also to remove it when using its “Reformat and Cleanup Code” feature:

Leave a comment

When did you start writing clean code?

I was asked this question this week: “When did you start writing clean code?”. I hadn’t thought of that before. Pondering on the question, I remembered when I started paying more attention to writing better code. It also made me think when I do not write clean code. Here’s what I came up with…

When did I start writing clean code?

Going back in time some 25 years, I was working with good old Clipper. Some of the files I was working with had thousands and thousands of lines of code. I had to print out pages of code on a dot-matrix printer and then draw lines to connect if-blocks and things like that in order to make some sense out of it.

Eventually, I figured out I could move some blocks of code out to separate functions, so instead of reading 5k lines of code, I’d need to read only 2k. As time went by, that codebase was way easier to understand.

When I do not write clean code

For me, it isn’t possible to write clean code all the time. For example:

  • When I’m implementing some new feature and writing tests first
    • In a case like this, once I have a failing test, I’ll write whatever code it takes to make the test pass. That could mean having one class with a lot of ugly code. I don’t care. Once my test is passing, then I’ll look back at the nasty code and will do my best to make it better, given what I currently have available (my skill with the programming language, my knowledge of the framework or libraries used, my understanding of the requirements, the time I have available, etc.);
  • When I’m new to the programming language, framework, libraries, business domain, project…
    • In cases like this, there’s really so much I can do. In the beginning, things will come out a little (or a lot) ugly. As I learn, things will get better.

I remember moving from FoxPro to C#. As much as I though I was a good FoxPro developer and wrote good code, I just know my C# code was terrible. It took a while to learn how to write better C#.

When I moved from C# to Ruby, things were slightly different: I already knew my Ruby code would look bad initially, so I first learned how to write tests! I didn’t even worry about writing clean tests; I only cared about writing some test so I could “write Ruby code with a C# accent”, and once the tests were passing, I’d get help from somebody who knew a lot of Ruby to show me “The Ruby Way” (or more specifically, the Rails Way) for doing certain things.

Summing up

For me, at the end of the day I just want to make sure I wrote the best code I could, once again, given what I currently have available:

  • My skillset in the programming language, framework, libraries, etc.;
  • My understanding of the business domain;
  • My time available


Leave a comment

SpecFlow: My preference for the step definition style

When using SpecFlow’s dialog to generate step definition skeletons, the default style is “Regular expressions in attributes”:

That produces results like this:

That looks very messy to me. The regular expression text can be read easily, but then the PascalCase method underneath looks like it is too much. I see redudant code. I see dead code. 🙂

I personally like the “Method name – underscores” style better:

That looks a lot cleaner to me. Yes, I am a little biased after having spent several years in Ruby-land, but hey, I had adopted this style in C# before that. While this is not a common format for method names in C#, I don’t really care, as nobody should be calling this methods in the common way anyway, so I rather follow a style that makes the code read better, without junk around that doesn’t add anything to my understanding of the code.

Note: by the way, I do rename those p0 and P0 references!!



The “private” keyword in C#: I get rid of it!

I have a special dislike for walls of characters in code and I try to get rid of it whenever possible, as I mentioned in this other post. The keyword private in C# is another one that bugs me. Take the following code:

What do I see there?

I like this way better:

Every class member is private by default in C#, as it should be. We should always keep public members to a minimum, so I rather be explicit as to what’s NOT private in my classes. By removing the unnecessary private modifier keyword, I clean up my code. The less garbage there is around the code, the easiest it is for anybody to read and understand it.

For ReSharper users out there: you can set the tool so that it’ll remove “private” modifiers when you run Code Cleanup.


Leave a comment

A Good Example of Open-Closed Principle

Back in 2010 I wrote what became my most popular post in this blog: A Good Example of Liskov Substitution Principle, based on a scenario that came up in a project I worked on at the time. I just realized I’ve never blogged about another scenario that came up in the same project as a good example I use for the Open-Closed Principle (OCP), which is described as follows:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”; that is, such an entity can allow its behaviour to be extended without modifying its source code. – Wikipedia

I use a simple application to illustrate the scenario. This is a desktop application. The main menu has one sub-menu for each module (e.g., Orders and Employees). Each module has its own sub-menu to expose related functionality:

Initially, the menu was all implemented in the same place… the main window:

The “code behind” the main window called out services in the different modules:

Any time a new feature was added to a module, the main window had to be changed. With several features across several modules being written actively, the main window was a big bottleneck: many developers were trying to change it at the same time! Implemented that way, the main window violated OCP: to extend the menu (adding modules or features to them), the main window had to be changed.

In order to make the main window OCP-compliant, and therefore, improving the implementation, here are the changes made to app…

The main menu in the main window was defined, since it’s that window’s responsibility to host a menu. However, it is NOT its responsibility to know what items go in the menu. In other words, the menu is empty:

The code behind the main window that used to call services in the modules was removed, and the classes started to use an AppMenuBuilder class, which returned a list of MenuItems to be added to the menu. Each module was represented by a Module class (e.g.: OrderModule, EmployeeModule…). In the real world application these modules were registered and initialized automatically using an IoC container (but that’s beyond the point of this post).:

The AppMenuBuilder class simply registered IModuleMenuBuilder instances, and it used those to figure out what menu items were needed:

Each implementation of IModuleMenuBuilder was responsible for creating the menu items that the module needed, and what to execute when the menu item was invoked. See the OrderMenuBuilder as an example:

The MenuItemFactory offered an easy way to create the MenuItem and hook it up to the action to be executed:

Again, the real world implementation of that factory was slightly different: it implemented an IMenuItemFactory interface, which got injected into each Module class. But again, that part is beyond the point of this post. The idea behind having the MenuItemFactory was so to make it easy to hook other operations to the menu system-wide. For example, let’s say we wanted to log every action invoked by any option on the menu. Here’s a simple logger:

Here’s how the MenuItemFactory would leverage additional actions:

And once again, in the real world application this was a little more robust, where “things to be added to the menu actions” were registered automatically to the IoC container.

After making those changes, the main window became open for extension, but closed for modification: options could be added to the menu and actions could be associated with them, and the main window didn’t have to be changed.


Leave a comment

Baseclass Asking Subclasses for Items

There are many scenarios where a baseclass (often abstract) needs to defer to its subclasses the creation (or retrieval) of items it needs. For example, let’s pretend we have a Pizza class, which defers to its subclasses what ingredients it should have. I’ve seen developers implementing such scenario in ways that look like this:

public abstract class Pizza
    List<string> Ingredients { get; set; }

    protected abstract void AddIngredients(List<string> ingredients);

    public void Make()

public class MeatLovers : Pizza
    protected override void AddIngredients(List<string> ingredients)
        ingredients.Add("Canadian Bacon");

That kind of implementation has the baseclass call a method overridden in the subclass so it can populate the given list. I don’t like it implemented this way because it gives developers the idea that the list can be manipulated. For example, the developer might decide that before adding items to the list, he or she could/should empty the list first (ingredients.Clear()). Well, what if I want all of my pizzas to have cheese (I’m a cheesy guy!)?

I rather ask the subclass for the items, and then have the baseclass deal with adding them to a list, collection, array, or however it sees fit. Something like this:

public abstract class Pizza
    List Ingredients { get; set; }

    protected abstract IEnumerable<string> GetIngredients();

    public void Make()
        Ingredients = GetIngredients().ToList();

public class MeatLovers : Pizza
    protected override IEnumerable<string> GetIngredients()
        yield return "Pepperoni";
        yield return "Sausage";
        yield return "Canadian Bacon";

In simple scenarios, the subclass can simply use yield return for each item. For other cases, it can internally use lists, collections, arrays, or anything else that can ultimately produce an IEnumerable<string>.

With that being said, if the requirements calls for allowing the baseclass to manipulate that list, then I’d go with something similar to the first implementation. However, in most cases, that’s NOT what the requirements ask for, and I’ve had to troubleshoot several bugs where subclasses manipulated lists when they were not really meant to.

Leave a comment

Dynamic Data and Behavior in a Strongly-Typed Codebase

With my previous post I’ve wrapped up an entire series where I talk about creating a dynamic DTO decorator, which started off as a way to leverage C#’s Dynamic Features to get rid of the need to implement INotifyPropertyChanged on every ViewModel and then morphed into decorating the object with some extra behavior (on the previous post, we’ve added support for some visual behavior).

As I mentioned many time in the series, the implementation I showed is a simplified version of something I had in a large Real World application. In this post I want to just mention some other things that were done in that application, to give you an idea on where else we can go with that approach.

Dynamic Entities

There was a requirement where the application shipped with a database structure, but then it could be extended in production, based on each client’s needs. The clients couldn’t create completely arbitrary new data structures; instead, they’d create new tables which added columns to existing ones (a sort of inheritance).

The codebase had entities defined with the properties the application shipped with, but these entities also needed to be extended at the clients to support the columns they added to the tables in the database (they could only do this to very specific tables through the application).

In order to support that behavior, we created a DynamicEntity class, which followed the same approach of implementation as the DynamicDtoDecorator I’ve described on my series. The data access layer was responsible for setting things up so that NHibernate could work with the “dynamic” columns added to the tables. This layer would also dynamically add default values to certain properties on the entity, as specified by the end-users. The users could, for example, set the default value for a new property (new column in a table) by creating a expression such as x.PropertyA + x.PropertyB (where PropertyA may be one that ships with the application, while PropertyB may be a user-defined one).

Dynamic Business Logic

As the DynamicEntity travelled from the data access layer through the business layer, the framework added some special dynamic behavior as specified by users through the application. For example, the users could set range validation for properties on the entity (both for properties that shipped with the app, as well as those created by the client).

Dynamic Behavor for Presentation Layer

As the DynamicEntity reached the Presentation Layer, the framework added dynamic behavior related to presenting the entity to the user, such as handling what the background cell color should be for each property on the entity based on its value, whether a cell should be read-only, etc. Make sure to check out my previous post for an example of this.

From the database to the user interface

The framework provided an interface (IHandleRow, or something like that), which the different layers of the application (data access layer, business layer, presentation layer) could implement to inject the specific dynamic data and/or behavior the application needed on each layer. Since the end-users could override behavior shipped with the application, as well as add behavior to the columns they added, this approach using the C# Dynamic Features has helped tremendously in making an otherwise strongly-typed codebase support the business requirements.

Leave a comment

Fun with C#: Adding visual behavior to dynamic view model

As promised on my previous post, let’s see how we can add a nice little feature that leverages the capabilities of the DynamicDtoDecorator we’ve been creating across several blog posts. The gist of this feature is to add dynamic properties to the view model to help support a “dynamic background color” behavior for the data properties that need it.

As an example, let’s take a screen that has some data grid similar to this:

Now, let’s pretent there’s a requirement where the cell background must be green when a product name is “banana”, and yellow for anything else:

Of course, the background has to change accordingly when the user changes the product name on the screen.

Adding to the example, let’s say that the category cell background color must change based on the category:

And finally, the total cell background must also change… however, it also depends on the category, and it uses different colors:

If you’ve been following my series on “How to get rid of INPC using Dynamic” (starting here), you know my example app here uses a DynamicDtoDecorator that takes a POCO ViewModel, enhances it with INPC behavior, and is then bound to the view. Using that decorator we can tap into WPF’s databinding features to make it easier to expose this visual behavior we want for the data.

The main idea here is the following: the ViewModel already contains the data that we want displayed on the UI. We can then use the decorator to enhance the ViewModel to help the view display that data.

I’ll walk you through how I’ve implemented this type of feature in this sample app. Bear in mind this is a much trim down version from a real world, much larger, app that I’ve worked on a while ago. I’ll point out the main differences between the sample and the real app when appropriate.

In order to support visual aspets for the InvoiceItemViewModel class, I’ve created a class named InvoiceItemVisuals, starting it off like this:

public class InvoiceItemVisuals

I’ve then added a method specifically to define the cell background definitions for an invoice item:

public IEnumerable<cellbackgrounddefinition> GetCellBackgrounds()
    yield return new CellBackgroundDefinition("ProductName",
        new [] { "ProductName" }, 
        vm => vm.ProductName == "Banana",
        new Dictionary
            {true, Brushes.Green},
            {false, Brushes.Yellow}
    yield return new CellBackgroundDefinition("Category",
        new[] { "Category" },
        vm => vm.Category,
        new Dictionary
            {"1", Brushes.LightBlue},
            {"2", Brushes.LightGray},
            {"3", Brushes.LightSalmon}
    yield return new CellBackgroundDefinition("Total",
        new[] { "Category" },
        vm => vm.Category,
        new Dictionary
            {"1", Brushes.Red},
            {"2", Brushes.Pink},
            {"3", Brushes.Purple}


The CellBackgroundDefinition is a generic class that expects to know the type of ViewModel it works with, and takes in four important pieces for it to work:

  1. The name of the data property bound to the cell;
  2. A list of dependent properties. For instance, the background color for the total cell depends on the value of the category;
  3. A Func that takes in an instance of the ViewModel, and returns whatever gives the value that’ll be used to determine the cell background color. In the example above, we’re interested on the value of Category; 
  4. A dictionary indicating the colors to be used for each expected value (in the example above, “1” is red, “2” is pink, “3” is purple.

Real World: the application in the real world didn’t have those definitions set in code; instead, those were all stored in the database, with support to have both default settings that shipped with the app, as well as user overrides.

Once we have those “background definitions” specified, we have to inject them into our decorated DTO (in our case, the view model). For that, I’ve added an InjectInto method to the InvoiceItemVisuals class:

public void InjectInto(DynamicDtoDecorator decoratedDto)
    GetCellBackgrounds().ForEach(definition =>
        var backgroundProperty = {0}#x22;{definition.PropertyName}_Background";
        decoratedDto.RegisterPropertyDependencies(backgroundProperty, definition.DependsOn);
        decoratedDto.Register(backgroundProperty, () => definition.Func(decoratedDto.GetDto()), newValue => {});

The method takes in the DynamicDtoDecorator, goes through all the cell background definitions, and register those as dynamic properties and their dependencies. As mentioned before, the new property is named after the data property it refers to, and it has a “Background” suffix, so for the Category background, we’ll have a “Category_Background” property.

Notice that the Register method on the DynamicDtoDecorator takes in the name of the new property, as well as Funcs for the property’s getter and setter. Our getter in this case simply calls the Func that is part of the background definition (which, for the Category background looks like vm => vm.Category), whereas the setter doesn’t really need to do anything.

The final piece for this feature to work is to set things up in the UI so it knows how to use our dynamic properties. Please, remember this is a WPF application, so we can create styles and triggers to handle the visual stuff. Instead of defining those declaratively in XAML, we do it imperatively in C#. To keep things simple in this sample app, I’ve added a ConfigureDataGrid to my InvoiceView Window class, which in turn calls a ConfigureCellBackgrounds method, and this is the guy who does the heavy lifting here:

private void ConfigureDataGrid()
    var modelVisuals = new InvoiceItemVisuals();

private void ConfigureCellBackgrounds(InvoiceItemVisuals modelVisuals)
    var cellsBackgrounds = modelVisuals.GetCellBackgrounds();

    cellsBackgrounds.ForEach(cellDefinition =>
        var column = (DataGridTextColumn) ItemsGrid.Columns
            .Single(c => c.Header.ToString() == cellDefinition.PropertyName);
        var style = new Style(typeof(TextBlock));

        cellDefinition.TriggerDefinitions.ForEach(trigger =>
            var binding = {0}#x22;{cellDefinition.PropertyName}_Background";
            var propertyValue = trigger.Key;
            var propertyBackground = trigger.Value;
            var dataTrigger = new DataTrigger
                Binding = new Binding(binding),
                Value = propertyValue
            dataTrigger.Setters.Add(new Setter
                Property = TextBlock.BackgroundProperty,
                Value = propertyBackground

        column.ElementStyle = style;

Breaking down the implementation of ConfigureCellBackgrounds, here’s what we do:

  1. Get the cell background definitions and loop through them;
  2. Get a reference to the GridColumn that hosts the data cell we’re interested in;
  3. Go through the TriggerDefinitions;
  4. Set up the Binding expression so it points to the appropriate “Cell_background” property;
  5. Put the binding expression in a DataTrigger for the TextBlock.BackgroundProperty;
  6. Put the data trigger in a new style created for TextBlock (where the values are displayed on the UI);
  7. Set the style on the grid column.


If you’d like to check out this sample app in action, here’s a link to the repo in GitHub:

Dynamic Decorator

Once again, bear in mind that this sample app shows a very simplified version of a full-blown Real World app that used this approach extensively. In the full app, a lot of the implementation went into a custom framework, and expressions and definitions for visual things and behaviors were specified both in C# code (for the options shipped with the application) and stored in the database (for the options overridden by specific clients and users).

I’ve used this approach successfully in at least two other projects, and will probably keep it in mind to use again if appropriate. 🙂

Leave a comment

Fun with C#: Enhancing ViewModels with a Dynamic Decorator

I’ve been posting a series on how to use C# Dynamic Features in order to get rid of implementing INotifiyPropertyChanged (INPC) on my ViewModels. If you’ve been following those posts, you’ll notice that the class I created to enable this is called DynamicDtoDecorator.

That class initially started as a proxy, simply bridging access to the properties on the internal object. After I added the INPC support to it, it really became a decorator. But I really started leveraging its abilities as a decorator when I started injecting more properties into the object in order to support more visual behavior.

As I mentioned back in this post, I wanted to leverage WPF’s data-binding capabilities. Using those capabilities to simply show data on the screen is really just the tip of the iceberg; the framework also allows binding to be used to do things like controlling visibility of UI elements, change visual aspects for elements (for instance, changing the background color of a grid cell), etc.

In this post, we saw that we can use the decorator like so:

var viewModel = new InvoiceItemViewModel { ProductName = “Some value" };
dynamic decorator = new DynamicDtoDecorator(viewModel);

We can then bind UI elements to the ProductName property, which is exposed through the decorator. Now, maybe we have some requirement that indicates the background where we show product name should change based on some data (which could potentially be changed by the user). It’d be handy to have a property on object like so:


Usually, property names in C# classes don’t have an “_”, but I do that as a simple convention so it makes it easy to parse it out and know the “data” property and the visual aspect we’re talking about there. Also, bear in mind that in the real world app where I’ve used this approach nobody would be accessing those properties directly in code: each property gets added dynamically to the decorator, and the all the data-binding is also hooked up dynamically.

In the next post we’ll see how we make the main part of that actually happen.

Leave a comment

Fun with C#: How to get rid of INPC using Dynamic – Part 5

Taking it from where we left off at the previous post on this series, let’s improve our DynamicDtoDecorator so it handles raising PropertyChanged events for properties that depend on other properties.

First, let’s revisit our InvoiceItemViewModel class:

public class InvoiceItemViewModel
    public string ProductName { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public decimal Total => Price * Quantity;

As far as the UI is concerned, whenever either Price or Quantity changes on that object, the display of Total should refresh accordingly. In other words, Total depends on both Price and Quantity. I wanted to represent this dependency decorating the property with an attribute in the following manner:

[DependsOnAttribute("Price, Quantity")]public decimal Total => Price * Quantity;

Let’s look at the changes needed to implement that behavior. First, the implementation of DependsOnAttribute:

public class DependsOnAttribute : Attribute
	public string PropertyNames { get; set; }

	public DependsOnAttribute(string propertyNames)
		PropertyNames = propertyNames;

Definitely nothing special there. Next, changes to the DynamicDtoDecorator. Starting with a property to keep a dictionary of property dependencies (the key is the name of the property that has dependencies and the value is a list of properties that it depends on):
readonly Dictionary<string, IEnumerable<string>> _propertyDependencies = new Dictionary<string, IEnumerable<string>>();
We then change the RegisterProperties method so it verifies whether the property its registering has dependencies, and if so, it calls out the RegisterPropertyDependencies method:

protected virtual void RegisterProperties(object dto)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .ForEach(prop =>
            object[] notIndexedProperty = null;
            Func valueGetter = () => prop.GetValue(dto, notIndexedProperty);
            Action valueSetter = newValue => prop.SetValue(dto, newValue, notIndexedProperty);
            Register(prop.Name, valueGetter, valueSetter);

            var dependsOn = prop.GetCustomAttributes(true).OfType().SingleOrDefault();
            if (dependsOn != null)
                RegisterPropertyDependencies(prop.Name, Array.ConvertAll(dependsOn.PropertyNames.Split(','), d => d.Trim()));

Here’s the implementation of RegisterPropertyDependencies:

public void RegisterPropertyDependencies(string property, string[] dependencies)
	_propertyDependencies.Add(property, dependencies);

We then have to change the SetProperty method to make sure we raise PropertyChanged for properties that depend on the property being changed:

public virtual void SetProperty(string propertyName, dynamic value)
	if (!_members.ContainsKey(propertyName))
		throw new InvalidOperationException({0}#x22;Unregistered member: {propertyName}");

	if (_members[propertyName].Get() == value) return;


Here’s the implementation for the RaisePropertyChangedForDependentsOn method:

void RaisePropertyChangedForDependentsOn(string propertyThatWasChanged)
    _propertyDependencies.ForEach(dependentProperty =>
        var dependableProperties = dependentProperty.Value;
        if (!dependableProperties.Contains(propertyThatWasChanged)) return;

        var dependentPropertyName = dependentProperty.Key;

The code simply looks through the registered properties that have dependencies and raise the event as appropriate.

This pretty much wraps up all the main pieces for getting rid of direct implementation of INotifiyPropertyChanged in ViewModels by using the C# Dynamic features. I’ll be keeping the latest version of the code in this repository, so feel free to check it out. I’ll be writing new posts for other improvements I’ve added to the decorator and you might find useful. Stay tuned!

In case you missed any part of this series, here are the links to Part 1, Part 2, Part 3 and Part 4.

Leave a comment