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 »

Advertisements

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”)

Prism UWP for beginners: lifecycle

 

In this post we’ll explore the management of the lifecycle of a UWP app inside the OS.

Classic programs (Win32, for example) have two states: not running and running. When the typical desktop app is running it use all the RAM and CPU it needs, even when it is in the background. This is a problem in the world of universal apps because many types of device have very limited battery, CPU, and memory. So in this ecosystem we need to be green and free resources as soon as possible.

Windows comes to our help about power management but we need to know a few more things that we have to manage in our code. The OS can suspend our app when it wants in some cases and we need to give our useres the best user experience.

By default, apps that are not in the foreground are suspended which results in power savings and more resources available for the app currently in the foreground.

updated-lifecycle

In MSDN documentation we can find a detailed explanation of every status and the suggested action to take:

image

When a user leaves our application by switching to another one without terminating, he or she expects to find all the things in place when he/she’ll come back. The termination by the OS has to be transparent. So we need to save the state of the app and restore when the OS will restore the app.

Let’s do it!

Plain data

When we need to save simple data like boolean, strings, or numeric values we decorate with the RestorableState attribute in our viewmodel the properties that we need to save and restore. For example we have a TextBox binded to a string property:

  <StackPanel>
        <TextBlock Text="Simple property restore" />
        <TextBox Text="{Binding SimpleProperty, Mode=TwoWay}" />
  </StackPanel>

And this is our code behind:


class RestoreStatePageViewModel : ViewModelBase
{
[RestorableState]
public string SimpleProperty
{
get { return _simpleProperty; }

set
{
_simpleProperty = value;

SetProperty(ref _simpleProperty, value);
}
}

public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
{
base.OnNavigatedTo(e, viewModelState);
}

private ISessionStateService _sessionStateService;

private string _simpleProperty;
}

That’s it! Now: how to try? How can we force the OS to suspend our App? Visual Studio helps providing the Debug Location toolbar with the Lifecycle Events dropdown.

image

If this toolbar is not visible we find it by right-clicking in the white space of the main toolbar and select Debug Location.

image

Now we can launch our app and write something in the TextBox. Then we select Suspend and shutdown in the Lifecycle events dropdown. Visual studio will stop debugging and the app terminated. Now we hit F5 again to restart our app and we’ll find that the TextBox has the same value we writed before.

Complex data

Sometimes we have to save and restore complex or custom data. In this scenario we rely on the SessionStateService provided by Prism.

We register this service during the bootstrap in the App.xaml.cs code in the OnInitializeAsync method:

 protected override Task OnInitializeAsync(IActivatedEventArgs args)
        {

            Container.RegisterInstance(SessionStateService);

            return base.OnInitializeAsync(args);
        }

Let’s say we have a class that represents our Twitter Timeline. We need to decorate the class and the properties we want to save and restore with the DataContract and the DataMember attributes respectively.

This is because the Prism framework needs to serialize and deserialize our class and with UWP we don’t have the [Serializable] attribute we have in the standard .net environment.

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace IC6.Buongiorno.Services.Twitter
{
    [DataContract]
    public class TwitterTimeline
    {
        [DataMember]
        public string Timeline { get; private set; }

        public TwitterTimeline(IEnumerable<string> tweets)
        {
            Timeline = string.Join("\r\n\r\n\r\n", tweets);
        }
    }
}

We also need to configure Prism to serialize our custom class. We do this the App.xaml.cs code in the override of the OnRegisterKnownTypesForSerialization() method in which we have to register, in the SessionStateService, every custom class we’re going to use in the application, like in the following sample:

 protected override void OnRegisterKnownTypesForSerialization()
        {
            base.OnRegisterKnownTypesForSerialization();

            SessionStateService.RegisterKnownType(typeof(TwitterTimeline));
        }

Our class is now ready to be saved and restored.

In our viewmodel we need to save our timeline and we write:

public void SaveState()
{
if (_sessionStateService.SessionState.ContainsKey(SettingNames.Timeline.ToString()))
                {
                    _sessionStateService.SessionState.Remove(SettingNames.Timeline.ToString());
                }
                _sessionStateService.SessionState.Add(SettingNames.Timeline.ToString(), twitter);
}

To restore the state the best place is the OnNavigatedTo event.

 public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

                        if (_sessionStateService.SessionState.ContainsKey(SettingNames.Timeline.ToString()))
            {
                var twitter = _sessionStateService.SessionState[SettingNames.Timeline.ToString()] as TwitterTimeline;

                Timeline =  twitter.Timeline;
            }

                    }

We can test all this with the same procedure as before.

TL;DR

In this post we explored the concepts of lifecycle management and how to use Prism event to save and restore the state of our app to provide the best experience to our users.

If you want to learn more: