Clean Tuples

Depending on the preferences of a developer you may sometimes find a lot of tuples within the source code. Whether this is good or bad practice is another discussion which is not part of this article. Therefore I don’t want to start a discussion whether you shall use classes, structs or tuples. I want to have a look at tuples form the “clean code” point of view.

In my opinion, tuples have one major disadvantage: The code to access tuples is not easy to read. If you use tuples and you write your code they are very easy to use. But in case you have to read, understand and maintain your code after a while or source code which was written by other developers, tuples can become a mess. The following source code shows an easy example. We define a tuple to store information about a person, we create a person tuple in some function and we access the elements of the tuple.

typedef std::tuple<std::string, std::string, int> Person;

Person CreatePerson()
{
  return std::make_tuple("John", "Doe", 35);
}

int _tmain(int argc, _TCHAR* argv[])
{
  Person person = CreatePerson();

  int age = std::get<2>(person);

  std::cout << age << std::endl;

  return 0;
}

This simple example is easy to read. You will understand the source code immediately and you are able to maintain the code. But I think that’s only possible because the whole source code will fit in one screen. What will happen if you use such tuples in a bigger context? The type definition will be placed in one file, the function to create the tuple in another file and the function which access the tuple elements is in a third file. In such a case you will lose the big picture and you need additional time to collect all the information. You cannot longer just read the code, you have to spend time and explore the code to find all needed information.

Have a look at the function to create the tuple. Within this function you have to know that the first parameter is the first name and the second parameter is the last name of the person. Therefore such source code has a high possibility for errors. And on the other hand if you want to use the tuple, you access the elements by an index. In case of the age parameter there is no issue as the used type is unique within the tuple. But if you want to access the first or last name of the person, you will find the same issue like before. Accessing by an index may lead to errors.

As a result of these issues we will think about a possible solution. How can we create clean source code? We found two issues: Creating the tuple and accessing the elements in a clear way. I think a very easy possibility is to exchange the not speaking index number with a speaking enumerator. By using an index enumerator you will be able to set and get the elements of a tuple by using their name. The following source code shows the adapted example.

typedef std::tuple<std::string, std::string, int> Person;

enum PersonIndex
{
  FirstName,
  LastName,
  Age
};

Person CreatePerson()
{
  Person person = std::make_tuple("", "", 0);

  std::get<FirstName>(person) = "John";
  std::get<LastName>(person) = "Doe";
  std::get<Age>(person) = 35;

  return person;
}

int _tmain(int argc, _TCHAR* argv[])
{  
  Person person = CreatePerson();

  int age = std::get<Age>(person);

  std::cout << age << std::endl;

  return 0;
}

This little modification will result in a lot of advantages. You type definition is followed by the according index enumerator which explains the tuple. So you don’t have to explain the tuple with a comment. The creation of the tuple can now be done with an explicit assignment of the parameter name and its value. And the access of the elements will also be done by using the parameter name. The resulting source code is now very easy to understand. You can read the code and will understand it immediately without the need of looking for some more information in other files. For example, it is no longer necessary to look for the type definition and an explanation of the elements. By using the index enumerator you can create “clean” tuples.

Veröffentlicht unter .NET, C++, Clean Code | Kommentar hinterlassen

Design patterns: Singleton

By using the Singleton design pattern you ensure that a class has only one instance. The instance operation is provided by the class itself. So it maintains its own unique instance.

The .NET framework offers a very simple and thread-safe way to create a Singleton. The following source code shows an according example, how to create a singleton instance for logging purposes.

At first we define a interface.

public interface ILogger
{
    void Log(string message);
}

Second we can implement the Singleton object. The class instance is provided by a property which returns a read only object. The .NET framework ensures a thread-safe and lazy creation of the class instance.

public class Logger : ILogger
{
    private static readonly Logger _instance = new Logger();

    private Logger()
    {
    }
           
    public static Logger Instince
    {
        get
        {
            return _instance;
        }
    }            

    public void Log(string message)
    {
        throw new NotImplementedException();
    }        
}

And the last code example shows how to use the Singleton within an demo application.

static void Main(string[] args)
{
    ILogger logger;

    logger = Logger.Instince;

    logger.Log("foo");
}
Veröffentlicht unter .NET, C#, Design Pattern | Kommentar hinterlassen

Dealing with conflicts

In conflict situations it may often be difficult to keep the talk on a solution-oriented way. Personal emotions, different goals of the people, criticism and many other factors will influence the talk. Therefore it is helpful to have a procedure in mind which will guide you through a conflict talk. The following bullet point list will show a very simple procedure for conflict discussion. Try to have this list in mind or write it down as short note and follow this procedure during the talk.

Procedure for a conflict discussion
  • Name the problem (Everyone shall explain his point of view)
  • Find the common goal
  • Search for possible solutions
  • Discuss about the individual concerns against the solutions
  • Find a compromise which covers the collective goals
Veröffentlicht unter Projektleitung | Kommentar hinterlassen

Design patterns: Proxy

The idea of the Proxy design pattern is to provide a substitute for another object were the substitute controls the access to the other project. So there is one real subject with a given interface, for example an object to access a database. And there is a proxy which maintains a reference to this real subject. They both implement the same interface. So the proxy can be used as substitute of the real subject. Often the client does not even know that he uses a proxy.

The proxy controls the access to the real subject and will be responsible for additional tasks, for example creation or deleting of the real subject. The proxy may add some new functionality for example logging, caching, queuing, remote execution or access control.

The following example shows a possible implementation of the Proxy design pattern. Within the example we want to create a class which sends a message to one or some remote listeners. Sending the message may take a while. Therefore the send method will block the client or the client hast to implement asynchronous method calls. Therefore we want to provide a proxy which is responsible for queuing and sending messages. The proxy shall offer the same functionality like the real message provider extended with a queuing mechanism and asynchronous execution of the remote data transfer.

At first we will define the interface for the message channel.

public interface IMessageChannel
{
    void SendMessage(string message);
}

Now we will implement an according class. To simulate the slow remote execution we add a timeout of one second.

public class MessageChannel : IMessageChannel
{
    public void SendMessage(string message)
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
}

At next we can create the queued message channel which is a proxy of the real message channel. Therefore it holds an instance of the real object and it implements the same interface. To keep it simple we don’t implement the parallel task which executes the sending process. Instead we just add a DoWork method as example of the content of the parallel task.

public class QueuedMessageChannel : IMessageChannel
{
    Queue<string> _messages = new Queue<string>();
    IMessageChannel _messageChannel = new MessageChannel();

    public void SendMessage(string message)
    {
        _messages.Enqueue(message);
    }

    /// <summary>
    /// send the messages
    /// TODO: this must be executed as loop inside a parallel task
    /// </summary>
    private void DoWork()
    {
        string message;

        if (_messages.Count > 0)
        {
            message = _messages.Dequeue();
            _messageChannel.SendMessage(message);
        }
    }
}

Within a console application we can new use the proxy. In this example the client creates the proxy explicitly. If you use a factory instead, the console application will not even know whether it uses a proxy or not. But on execution of the send method you will see the difference as the proxy method will return immediately.

static void Main(string[] args)
{
    IMessageChannel messageChannel;

    messageChannel = new QueuedMessageChannel();

    messageChannel.SendMessage("abc");
    Console.WriteLine("Message was send");

    messageChannel.SendMessage("abc");
    Console.WriteLine("Message was send");

    messageChannel.SendMessage("abc");
    Console.WriteLine("Message was send");

    Console.ReadKey();
}
Veröffentlicht unter .NET, C#, Design Pattern | Kommentar hinterlassen

Write clean code instead of comments

Of course comments help to understand code. They are an essential part of the source code. But comments are an addition only. If you want to create readable and easy to understand source code, you have to focus on the code itself. An obscure implementation cannot be rescued by comments.

But how can we see whether a comment is a helpful addition to the source code or a helpless try to explain bad code. I think there are two main types of comments: the ones explaining “why” something is implemented in this way and the ones explaining “what” is implemented.

A good comment adds additional information to the source code and therefore explains the “why”. Bad comments instead explain “what” is implemented. Without these comments the source code is very hard to understand.

But how can we avoid bad comments and the bad source code they try to explain?

Every time we write a comment we shall ask ourselves: do we explain “what” or “why” we have implemented the code. If the comment explains “what” we have implemented we must try to refactor the source code. In such cases the source code shall be changed to self-explaining code which makes the comment obsolete.

int sellerIdentifier = 15;

//check whether the list of all sales of the seller contains the last sale
if(procuctManager.GetAllSales(sellerIdentifier).Contains(procuctManager.GetLastSale()))
{
	...
}

The comment within the example explains what the source code shall do. The source code itself is hard to read. Without the comment and even with the comment you have to read it several times to understand its behavior.

If you write such code and add the comment, you have to slow down for a moment and think whether the comment explains what the code does or why it is implemented. In this case the comment explains what the code does. So you should think about a possible refactoring. In this case you can remove the comment by using variables. Following you will see a possible refactoring result.

int sellerIdentifier = 15;

List<int> sales = procuctManager.GetAllSales(sellerIdentifier);
int lastSale = procuctManager.GetLastSale();

if(sales.Contains(lastSale))
{
	...
}

As you can see the second version of the source code does not need the comment anymore. Instead you may add a new comment and explain why this function is executed.

Summary

Comments are no substitute for bad code. Bad code stays bad code even if you write a detailed comment explaining each detail. It’s better to spend the time in a refactoring of the bad code then writing long comments.

Veröffentlicht unter .NET, C#, Clean Code | Kommentar hinterlassen

Design patterns: Observer

The Observer design pattern is used when you want to define a one-to-many dependency between objects. In case one object changes its state, all its dependents are notified and updated automatically.

In this design pattern you have two participants. The first one is the observable object, which knows his observers and provides an interface for attaching, detaching and notifying observer objects. The second participant or group of participants is the objects which want to be informed. These observer objects will implement a notification interface which is called by the observable object.

Following I want to show a simple implementation if this design pattern which is not thread-safe. In our example we want to create database connection which has status information. To keep it simple the status information is a string only.  Furthermore we want to create a user interface which shall show the database connection status within the main view and within a status bar. Therefore we have an observable object: the database connection, and several observers: the views.

The notification between the participants is done by events. So we start with an EventArgs class and an interface for the observer classes which contain the event receiver definition.

public class StatusChangedEventArgs : EventArgs
{
    public string Status { get; set; }        
}

public interface IStatusObserver
{
    void StatusChanged(object sender, StatusChangedEventArgs e);
}

At next we can implement a base class for the observable database connection class. As we implement it as abstract base class it can be reused for other observable classes to.

public abstract class StatusObservable
{
    private event EventHandler<StatusChangedEventArgs> _statusChanged;

    public void AttachObserver(IStatusObserver observer)
    {
        _statusChanged += observer.StatusChanged;
    }

    public void DetachObserver(IStatusObserver observer)
    {
        _statusChanged -= observer.StatusChanged;
    }
        
    public void NotifyAllObserver(StatusChangedEventArgs e)
    {
        if (_statusChanged != null)
        {
            _statusChanged(this, e);
        }
    }
}

Based on the observable class we will implement the database connection class. It contains two template methods to connect and disconnect the database. These methods will execute a status change which will trigger the observer notification process.

public class DatabaseConnection : StatusObservable
{
    public void Connect()
    {
        //todo: connect to database

        //change status            
        ChangeStatus("connected");
    }

    public void Disconnect()
    {
        //todo: disconnect from database

        //change status            
        ChangeStatus("disconnected");
    }

    private void ChangeStatus(string status)
    {
        NotifyAllObserver(new StatusChangedEventArgs() { Status = status });
    }
}

Now we can create the two view classes which will observe the database connection. To keep it simple these classes contain the interface implementation only and write the received status update to the console.

public class MainView : IStatusObserver
{
    public void StatusChanged(object sender, StatusChangedEventArgs e)
    {
        Console.WriteLine("MainView - StatusChanged received - new status: " + e.Status);
    }
}

public class StatusBar : IStatusObserver
{
    public void StatusChanged(object sender, StatusChangedEventArgs e)
    {
        Console.WriteLine("StatusBar - StatusChanged received - new status: " + e.Status);
    }
}

To test the implementation we can create a little console application. Within this application we will attach the observers to the observable database connection and execute some methods of this class. The according notifications will be send and shown as output in the console. Before the application gets closed, the observers will be detached from the observable class.

static void Main(string[] args)
{
    //create objects
    DatabaseConnection databaseConnection = new DatabaseConnection();
    MainView mainView = new MainView();
    StatusBar statusBar = new StatusBar();

    //attach observer
    databaseConnection.AttachObserver(mainView);
    databaseConnection.AttachObserver(statusBar);

    //change status in observable object
    databaseConnection.Connect();
    databaseConnection.Disconnect();

    //detach observer
    databaseConnection.DetachObserver(mainView);
    databaseConnection.DetachObserver(statusBar);

    Console.ReadKey();
}
Veröffentlicht unter .NET, C#, Design Pattern | 1 Kommentar

Linq vs Loop: Check whether item exists

Like in the previous article of this series I want to compare Linq with a classical loop. This time we want to look at the common use case to check whether an item exists. Again we want to use validated clean data as input and raw data including null pointers.

Use case one: clean data

Let’s start with the first use case. We have a simple data class for a person. Out of a list of persons we want to check whether a specific person exists.

The data class is defined as following:

public class Person
{        
    public string Name { get; set; }
    public uint Age { get; set; }        
}

Our demo console application creates a list of data and calls the data query method, first with an existing person and second with a not existing one.

List<Person> persons = new List<Person>();

persons.Add(new Person() { Name = "John Doe", Age = 35 });
persons.Add(new Person() { Name = "Jane Doe", Age = 41 });

//---------

bool exist;

//search existing person
exist = DoesExist(persons, "Jane Doe");
Console.WriteLine("Exist: " + exist.ToString());

//search not existing person
exist = DoesExist(persons, "???");
Console.WriteLine("Exist: " + exist.ToString());

Console.ReadKey();

The data query method shall be implemented twice: by using a loop and by using Linq. We start with the classical loop:

static private bool DoesExist(List<Person> persons, string name)
{
    foreach (Person person in persons)
    {
        if (string.Equals(person.Name, name, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }
    }

    return false;
}

And we implement the same function by using Linq.

static private bool DoesExist(List<Person> persons, string name)
{
    return persons.Exists(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase));
}

Code Review for use case one

Both methods will survive a code review without any issues. The loop is clean and well structured. The Linq query contains a long predicate inside the Exists call. But I think as this string comparison is easy to understand it is fine to write the whole statement in this one line of code.

In this use case I prefer the Linq method because I think it is something easier and quicker to read and understand.

Use case two: dirty data

The second use case adds an important need: the query must be robust. So the data may for example contain null values. Like in the first use case the method shall return whether the person exists. Null pointers will be rated as not existing person and therefore they shall be ignored and shall not throw an exception.

In our test console application we create some dirty data. And we add additional tests to call the function with the data or even with null parameters.

List<Person> persons = new List<Person>();

persons.Add(new Person() { Name = "John Doe", Age = 35 });
persons.Add(null);
persons.Add(new Person() { Name = null, Age = 38 });
persons.Add(new Person() { Name = "Jane Doe", Age = 41 });

//---------
bool exist;

//search existing person
exist = DoesExist(persons, "Jane Doe");
Console.WriteLine("Exist: " + exist.ToString());

//search not existing person
exist = DoesExist(persons, "???");
Console.WriteLine("Exist: " + exist.ToString());

//search in a list which is not yet initialized
exist = DoesExist(null, "???");
Console.WriteLine("Exist: " + exist.ToString());

Console.ReadKey();

The implemented query using the loop must be adapted to handle these special cases. The following source code shows an according implementation. The list and the list content will be checked for null values.

static private bool DoesExist(List<Person> persons, string name)
{
    if (persons == null)
    {
        return false;
    }

    foreach (Person person in persons)
    {
        if (person == null)
        {
            continue;
        }

        if (string.Equals(person.Name, name, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }
    }

    return false;
}

The implementation of the Linq query must be adapted too. A check of the whole list, as well of the single element is added.

static private bool DoesExist(List<Person> persons, string name)
{
    if (persons == null)
    {
        return false;
    }

    Predicate<Person> personFinder = (Person p) =>
    {
        if (p == null)
        {
            return false;
        }

        return string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase);
    };

    return persons.Exists(personFinder);
}

Code Review for use case two

I think both implementations are fine. They are self-explaining and easy to understand.  This time I don’t see any advantage using Linq. The needed predicate definition and the null pointer checks will lead to an implementation which is nearly equal to the loop. Therefore in my opinion the two solutions are coequal.

Veröffentlicht unter .NET, C#, Clean Code, LINQ | Kommentar hinterlassen