Sunday, October 15, 2017

C++ inheritance flavors

C++ has 4 types of inheritance. Let's start with public inheritance:

class A {
public:
void one() {}
protected:
void two() {}
private:
void three() {}
};

class B : public A {};

Public inheritance implies that class B inherits all public and protected methods from class A as is. This is what signature of class B looks like now:

class B : public A
{
public:
void one() {}
protected:
void two() {}
};

Let's move on and take a look at protected inheritance as well:

class B : protected A
{
protected:
void one() {}
void two() {}
};

As you can see the difference between the two is that all public methods of class A become protected in class B. Now, guess what happens when you use private inheritance? This is what happens:

class B : private A
{
private:
void one() {}
void two() {}
};

All public and protected methods inherited from A become private. Ok, I said there are 4, the fourth one is so-called virtual inheritance which allows you to literally share your base class when, for instance to fight famous diamond problem. Let's create some kinda diamond for clarity:

class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}

void topMethod() {}
};

class Left : public Top
{
public:
void leftMethod()
{
topMethod();
}
};


class Right : public Top
{
public:
void rightMethod()
{
topMethod();
}
};


class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};

Despite the fact that there will be two Top classes in our hierarchy, this will compile and run like it's no problem. Please run it and you'll see that Top constructor gets called twice. If such a behavior bothers you, you can get rid of the second Top class using virtual inheritance:

class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}

void topMethod() {}
};

class Left : public virtual Top
{
public:
void leftMethod()
{
topMethod();
}
};


class Right : public virtual Top
{
public:
void rightMethod()
{
topMethod();
}
};


class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};

Now, run it again to make sure we have only one Top.

Multithreading in C++

Since C++ 11 multithreading in C++ became a lot easier. You no longer need to wrap system specific stuff like threads and synchronization primitives yourself as they all are already there. Ok, let's get to it. In modern C++ you can spawn a new thread as easy as that:

#include <thread>

void threadFunction() {}

int main()
{
    std::thread thread(threadFunction);
    thread.join();

    return 0;
}

Now, let's talk about synchronization, starting with Mutex. Mutex is a quite simple synchronization primitive meant for protecting a resource from accessing by multiple threads at the same time. Here is what it looks like:

#include <thread>
#include <mutex>

std::mutex mutex;
int resource = 2;

void threadFunction()
{
    std::lock_guard<std::mutex> lock(mutex);

    resource *= 2;
}

int main()
{
    std::thread thread1(threadFunction);
    std::thread thread2(threadFunction);

    thread1.join();
    thread2.join();

    return 0;
}

As you can see from the example above we successfully protected our resource variable from accessing by multiple threads using mutex. You probably noticed that we used std::lock_guard template class to lock our mutex, well std::lock_guard is that exact lock wrapper we used to make ourselves before C++11 arrival. If you forgot how it works, its very simple. It locks mutex upon construction and then releases it upon destruction when we leave function body scope. You may be wondering why cant you lock and unlock mutex whenever you need using std::lock_guard, well, thats because std::lock_guard follows so-called scope ownership which prevents you from managing your lock in any way. If you need to manage your lock you kinda have to use a different kinda lock which is std::unique_lock.

#include <thread>
#include <mutex>

std::mutex mutex;
int resource = 2;

void threadFunction()
{
    std::unique_lock<std::mutex> lock(mutex);

    resource *= 2;

    lock.unlock();
}

int main()
{
    std::thread thread1(threadFunction);
    std::thread thread2(threadFunction);

    thread1.join();
    thread2.join();

    return 0;
}

As you can see std::unique_lock is much more flexible when it comes to a lock management. Talking about flexibility, there is one more synchronization primitive I'd like to show you, which is a condition variable. Let's slightly modify our example to use this primitive:


#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mutex;
std::condition_variable condition_variable;
int resource = 2;

void threadFunction()
{
    // Lock or if we can't block as usual
    std::unique_lock<std::mutex> lock(mutex);
    // Successfully acquired lock, now we can access our std::condition_variable.

    // Calling wait method, which blocks this thread and releases lock.
    condition_variable.wait(lock);
    // If we got here it means main thread called condition_variable.notify_all(),
    // which resulted in unblocking current thread and reacquiring lock.

    // We can thread-safely mess with out beloved resource.
    resource *= 2;
}

int main()
{
    std::thread thread1(threadFunction);
    std::thread thread2(threadFunction);

    std::unique_lock<std::mutex> lock(mutex);
    condition_variable.notify_all();

    thread1.join();
    thread2.join();

    return 0;
}

Ok, now let me try to explain to you what's going on in here. First of, as you can see, we still use locks to protect our resource. Well, actually we protect both our resource and std::condition_variable whose purpose is to unblock all threads waiting on it and then reacquire locks upon notification from other thread, which, in our example, happens to be main thread. Yes, I know, my example is way too trivial to be practical, but it wasn't the goal here, I merely wanted to explain the idea.




Saturday, October 14, 2017

SOLID

SOLID is an acronym for 5 design principles:

S - Single Responsibility Principle
O - Open Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle

Friday, October 13, 2017

Lambdas in C++

So you wanna use lambdas in C++ huh? It's as simple as that:

auto lambda = []() = {
    printf("Hello, I am a simplest lambda.");
};

Now, if you wanna invoke it only once you can omit assigning value and either add parentheses at the end or use std::invoke():

[]() = {
    printf("Hello, I am a simplest lambda.");
}();

std::invoke([]() {
    printf("Hello, I am a simplest lambda.");
});

Or if you got a value you can just call it like any other function:

lambda(); 

What about parameters, return value? Just put them where they belong:

auto lambda = [](int a, int b) {
    return a + b;
};

int result = lambda(1, 2);

Guess we are done here, let's move on and talk about captures. Ok, see those square brackets over there? That's called Capture List, a place where you put your captures. A capture is an identifier of a variable defined outside your lambda and a method to copy(capture) it.

[] - empty brackets mean there is nothing to capture.
[count] - identifier means capturing a variable by value.

int count = 9;

auto lambda = [count]() {
    std::cout << count << std::endl;
};

[&count] - identifier with ampersand means capturing a variable by reference.

auto lambda = [&count]() {
    std::cout << count << std::endl;
};

[=] - means capturing all local variables used inside lambda by value.

void function()
{
int count = 9;

auto lambda = [=]() {
std::cout << count << std::endl;
};

lambda();
}

[&] - means capturing all local variables used inside lambda by reference.

void function()
{
int count = 9;

auto lambda = [&]() {
std::cout << count << std::endl;
};

lambda();
}

[this] - means capturing this pointer.

class ClassWithLambda
{
private:
  int count;

public:
  ClassWithLambda():count(9) {}

    void methodWithLambda()
    {
        auto lambda = [this]() {
std::cout << count << std::endl;
};

lambda();
}
};

Actually [=] and [&] capture this pointer too, if it exists:

class ClassWithLambda
{
private:
  int count;

public:
  ClassWithLambda():count(9) {}

  void methodWithLambda()
    {
  auto lambda = [=]() {
std::cout << count << std::endl;
};

lambda();
}
};

class ClassWithLambda
{
private:
  int count;

public:
  ClassWithLambda():count(9) {}

  void methodWithLambda()
    {
auto lambda = [&]() {
std::cout << count << std::endl;
};

lambda();
}
};

Thursday, October 12, 2017

Arrays and Collections in C#

Arrays

C# supports single-dimensional as well as multidimensional arrays. Here is what array declaration looks like:

int[] array1 = new int[4];

This is how you normally access its elements using subscript operator:

array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;

Now I'mma show you exactly the same array, but with initialization upon declaration:

int[] array1 = new int[4] {0,1,2,3};

Convenient, isn't it? Ok, before we go any further, I wanna show you a couple of ways to iterate through an array:

for (int i = 0; i < array1.Length; ++i)
    Console.WriteLine(array1[i]);

foreach (int element in array1)
    Console.WriteLine(element);

I think it's time to get familiar with multidimensional arrays.

int[,] array2 = new int[4,4];
int[,] array2 = new int[4,4];
{
    { 0, 1, 2, 3 },
    { 0, 1, 2, 3 },
    { 0, 1, 2, 3 },
    { 0, 1, 2, 3 }
};

Array.Length property returns total length of the array including all dimensions. If you wanna know how many elements are in concrete dimension, use Array.GetLength(dimension). If you wanna know how many dimensions are in your array, use Array.Rank property.

foreach doesnt care about dimensionality of your array, it will iterate from the beginning to the end, dimension by dimension:

foreach (int element in array2)
    Console.WriteLine(element);

If you wanna use regular for loop with indices, it's a little bit more tricky:

for (int i = 0; i < array2.GetLength(0); ++i)
    for (int k = 0; k < array2.GetLength(1); ++k)
        Console.WriteLine(array2[i,k]);


Collections

C# also got plenty of different collections, let's take a brief look at some of them, starting with dictionary. Ok this is what dictionary looks like:

Dictionary<string, int> dictionary =
    new Dictionary<string, int>();

Basically it's just an associative array storing key-value pairs. The first generic type parameter is a type of key, the second one is a type of value respectively. Let me show you how this thing works.
You add key-value pairs this way:

dictionary.Add("One", 1);
dictionary.Add("Two", 2);

And that's how you access its values:

int one = dictionary["One"];
int two = dictionary["Two"];

Ok, now I wanna show you some lists. Let's start with regular List which looks like this:

List<string> list = new List<string>();

And works like this:

list.Add("One");
list.Add("Two");
list.Add("Three");

string One = list[0];
string Two = list[1];
string Three = list[2];

As you can see List behaves just like array, but its more advanced and flexible. Ok, the last one is gonna be LinkedList. This is what it looks like:

LinkedList<string> linkedList =
    new LinkedList<string>();

You can add nodes at any end:

linkedList.AddFirst("first");
linkedList.AddLast("last");

And access them in the following manner:

string first = linkedList.First.Value;
string last = linkedList.First.Next.Value;

foreach (var element in linkedList){}

Lambdas in C#

C# supports lambdas. Here is what simplest lambda looks like:

Action l = () => Console.WriteLine(
"Hello, I am a simplest lambda.");
l();

As its the simplest, it got no parameters and doesn't return anything. Ok, now I'mma show you lambda with one parameter:

Action<string> l = (s) => Console.WriteLine(s);
l("Hello, I am a lambda 1 parameter.");

You probably noticed that I omitted parameter type, it's not necessary as type was already specified by the delegate. Well, if you really want it, you can safely put the same type in argument list.

Action<string> l = (string s) => Console.WriteLine(s);
l("Hello, I am a lambda with 1 parameter.");

Now, what about lambdas with multiple parameters?

Action<string, string> l = (s1, s2) => Console.WriteLine(s1 + s2);
l("Hello,", "I am a lambda with 2 parameters.");

Almost forgot, lambdas can have bodies too:

Action<string, string> l = (s1, s2) =>
{
    Console.WriteLine(s1 + s2);
};
l("Hello,", "I am a lambda with 2 parameters.");

If you need lambdas returning some kinda value you need different delegate:

Func<int> l = () => { return 7; };

Func delegate may have parameters too, just like Action:

Func<int, int> l = (i) => { return i; };
Func<int, int> l = i => i;


Equality in C#

Ok, let's start with so-called reference equality (as in two pointers with same or different addresses).
In order to demonstrate reference comparison I'mma create some class and then instantiate it 2 times, so we cover both true and false cases:

class A{}

var a1 = new A();
var a2 = new A();


What's really interesting about this comparison is that its kinda default, meaning all method calls including equality operator will return true for a1 == a1:

var result1 = Object.Equals(a1,a1); // true
var result2 = Object.ReferenceEquals(a1, a1); // true
var result3 = a1.equals(a1); // true
var result4 = a1 == a2; // true

Correspondingly, all of them will return false for a1 == a2:

var result1 = Object.Equals(a1,a2); // false
var result2 = Object.ReferenceEquals(a1, a2); // false
var result3 = a1.equals(a2); // false
var result4 = a1 == a2; // false

Unlike Java C# actually has operator overloading, so why don't we overload all equality related methods of class A? Here is how we do this:

class A
{
    public static bool operator == (A a1, A a2)
    {
        return true;
    }

    // Irrelevant, but C# requires that we overload this one too
    public static bool operator != (A a1, A a2)
    {
         return false;
    }

    public bool Equals(A a)
    {
        return true;
    }
}

Let's compare a1 to a2 again:
var result1 = Object.Equals(a1,a2); // false
var result2 = Object.ReferenceEquals(a1, a2); // false
var result3 = a1.equals(a2); // true
var result4 = a1 == a2; // true

Now that we overloaded A's equality operators we can no longer rely on them to do reference equality comparison unless we know for sure they behave exactly like the default ones. In other words if we want reference equality our best option is definitely Object.ReferenceEquals method.

Looks like I completely omitted Value Equality. Well, if you need it, just implement your own equality/inequality operators and Equals method.