Posts Tagged C#

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
Advertisements

,

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!!

,

2 Comments

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()
    {
        AddIngredients(Ingredients);
    }
}

public class MeatLovers : Pizza
{
    protected override void AddIngredients(List<string> ingredients)
    {
        ingredients.Add("Pepperoni");
        ingredients.Add("Sausage");
        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}
        });
}

</cellbackgrounddefinition

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();
    ConfigureCellBackgrounds(modelVisuals);
}

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
            });
            style.Triggers.Add(dataTrigger);
        });

        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.

Done.

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