SOLID principles by examples: open/closed

This post continues the analisys of the SOLID principles started some blog posts ago. This is the turn for the Open Closed Priciple (OCP).

The definition

An object/entity should be open for extension but closed for modification.

What we are basically talking about is to design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code.

Read More »

SOLID principles by examples: single responsability

This blog post will explain with simple examples the Singe Responsabily Principle of SOLID agiles principles to better understand how we can improve our daily coding activites. In future post I’ll cover the other four priciples.

The Definition

A class should have only one reason to change.

Defined by Robert C. Martin in his book Agile Software Development, Principles, Patterns, and Practices it is the first of the five SOLID agile principles. What it states is very simple, however achieving that simplicity is not so obvious.

Read More »

SOLID principles by examples: introduction

SOLID is a common acronym in the software development world. It’s useful to remeber five best practices to design classes in a object oriented language. It means:



Initial

Stands for

Concept

SRP Single Responsability Principle A class should have only a single responsability.
OCP Open Closed Principle Software entities should be open for extension but closed for modification.
LSP Liskov Substitution Principle Objects in a program should be replaceable with instances of theri subtypes without altering the correctness of that program.
ISP Interface Segregation Principle Many client-specific interfaces are better than one general purpose-interface.
DIP Dependency Injection Principle

One should depend upon abstractions, not concretions.

These concepts are easy to understand when we read them, but what does it mean to apply them in our daily coding activities? What do we have to do?

In the next posts we’ll go through each concept with coding examples because as someone much smarter than me said:

Tell me and I’ll foget, show me and I might remember. Involve me and I will remember. – Confucius

UWP Prism Unit Test

I’m sure we all hear about unit testing, test driven development and so on. These practices are useful and provide a long list of benefit like writing low-coupled and mantainable code to name a few.

We want to write unit test for our UWP Prism application and we’d like, for example, to put our ViewModels under tests to make sure the logic they implement is correct. Unit testing is possible only if we can get rid of all the dependencies in our class under test because we want to run our test every time we want (for exemple when the service library our teammate is writing is not yet finished) and as fast as we can.

Read More »

Prism UWP for beginners: events

In this post we explore another major component of Prism: the EventAggregator.

The Prism library provides an event mechanism to communicate between loosely coupled components in the application. Using .NET Framework events is the most straightforward approach for communication between components if loose coupling is not a requirement. Events in the .NET Framework implement the Publish-Subscribe pattern, but to subscribe to an object, you need a direct reference to that object, which, in composite applications, typically resides in another module. This is a tightly coupled design.

The EventAggregator provides a mechanism to matain the application loosely-coupled. It provides a multicast publish/subscribe funcionality (there can me multiple publishers of the same event with multiple subscribers).

image

We can obtain a reference to the EventAggregator using the container, for example we can write this code in the OnInitializeAsyunc method of the App class that is our bootstrapper.

protected override Task OnInitializeAsync(IActivatedEventArgs args)
         {
Container.RegisterInstance<IEventAggregator>(new EventAggregator());
return base.OnInitializeAsync(args);
         }

Events

Before we start publishing and subscribing to events we need to declare them. Events are simple classes that inherit from PubSubEvent<T> in the Prism.Event namespace. T is the type of the payload of our message. We declare our simple event like this:


class SimpleEvent : PubSubEvent<string>
     {

    }

In this case we defined an event which payload is a string.

Publisher

Now let’s make an example of a viewmodel that publishes an event of that type.


class PublisherViewModel {

	public DelegateCommand SendMessage { get; private set; }

        private readonly IEventAggregator _eventAggregator;

	public PublisherViewModel(IEventAggregator eventAggregator)
        {
            if (eventAggregator == null)
            {
                throw new ArgumentNullException(nameof(eventAggregator));
            }

            _eventAggregator = eventAggregator;

            SendMessage = new DelegateCommand(() =>
            {
                _eventAggregator.GetEvent<SimpleEvent>().Publish(DateTime.Now.ToString());
            });
        }
}

In the constrctor we specified a parameter to hold a reference to an instance of IEventAggregator. The container will do the heavylifting and inject the parameter every time we need an instance of PublisherViewModel. We defined a DelegateCommand that publishes a message using the EventAggregator: that message will have the currente date and time in string format.

Subscriber

Now we can define a subscriver view-model that listens to this type of events.

 

class SubscriberViewModel
{
       private readonly IEventAggregator _eventAggregator;	

	public SubscriberViewModel(IEventAggregator eventAggregator)
	{
		if (eventAggregator == null)
		{
			throw new ArgumentNullException(nameof(eventAggregator));
		}
		_eventAggregator = eventAggregator;

		_eventAggregator.GetEvent<SimpleEvent>().Subscribe((dateDesc) =>
{
//Do something with datedesc.
});
	}
} 

With the

_eventAggregator.GetEvent<SimpleEvent>().Subscribe(...)

line of code we set our SubscriberViewModel class to listen to events of type SimpleEvent and we can specify what we would like to do when the class is notified.

And that’s it! Managing messages between components is very easy thanks to Prism.

TL;DR

In this post we learned how components can communicate in a Prism app in a decoupled fashion. The EventAggregator is the main actor of this funcionality and it acts as a post office to deliver messages from publishers to subscribers.

Only the code tells the truth

Treat your code like any other composition, such as a poem, an essay, a public
blog, or an important email. Craft what you express carefully, so that it
does what it should and communicates as directly as possible what it is doing;
so that it still communicates your intention when you are no longer around.
Remember that useful code is used much longer than ever intended. Maintenance
programmers will thank you. And, if you are a maintenance programmer
and the code you are working on does not tell the truth easily, apply the
aforementioned guidelines in a proactive manner. Establish some sanity in the
code, and keep your own sanity.

– Peter Sommerlad (from “97 things every programmer should know”)