Archive for July, 2017

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