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
Saturday, October 14, 2017
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();
}
};
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);
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:
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.
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.
Factory pattern in C#
Ok, so the idea is to create a class able to mass-produce instances of a different class or classess.
First, let's create something to be produced by our Factory class as in product:
abstract class Product
{
public abstract ProductType GetProductType();
}
class Car : Product
{
public override ProductType GetProductType()
{
return ProductType.Car;
}
}
class Motorcycle : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
class Airplane : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
You don't have to do it exactly this way, I mean, you can use interfaces if you want or even concrete unrelated classes (which you can return from Factory as Object).
Now we need to make some Factories. I create one for each type of product, but again, this one is up to you, you can implement this functionality as you please:
abstract class Factory
{
public abstract Product createProduct();
}
class CarFactory : Factory
{
public override Product createProduct()
{
return new Car();
}
}
class MotorcycleFactory : Factory
{
public override Product createProduct()
{
return new Motorcycle();
}
}
class AirplaneFactory : Factory
{
public override Product createProduct()
{
return new Airplane();
}
}
Well, I guess, that's about it.
First, let's create something to be produced by our Factory class as in product:
abstract class Product
{
public abstract ProductType GetProductType();
}
class Car : Product
{
public override ProductType GetProductType()
{
return ProductType.Car;
}
}
class Motorcycle : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
class Airplane : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
You don't have to do it exactly this way, I mean, you can use interfaces if you want or even concrete unrelated classes (which you can return from Factory as Object).
Now we need to make some Factories. I create one for each type of product, but again, this one is up to you, you can implement this functionality as you please:
abstract class Factory
{
public abstract Product createProduct();
}
class CarFactory : Factory
{
public override Product createProduct()
{
return new Car();
}
}
class MotorcycleFactory : Factory
{
public override Product createProduct()
{
return new Motorcycle();
}
}
class AirplaneFactory : Factory
{
public override Product createProduct()
{
return new Airplane();
}
}
Well, I guess, that's about it.
Singleton pattern in C#
Frankly I am a big fan of globals and there is no way you can convince me that Singleton is better in any way. Here is the quite popular (from what I heard) not thread-safe implementation:
class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
If your extra cautious, you can also make this class uninheritable using keyword sealed like this:
sealed class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
I mean it's crystal clear that this is not thread-safe, but the real question is, why do people keep mentioning thread-safety which isn't directly related to this design pattern in particular?. Singleton's goal is to merely restrict class instantiation, which has nothing to do with multithreading.
Ok, here is a thread-safe implementation. As you can see the primary difference between the two is a presence of a lock, which is beyond intuitive, I mean anyone would do it exactly this way:
{
private static object dummy = new Object();
private static volatile Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (dummy)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
In case you forgot, volatile keyword tells the compiler that a variable is volatile, meaning its value may rapidly change, for example, if multiple threads change it. In other words, using volatile keyword we ask the compiler not to optimize anything about this variable in particular.
Subscribe to:
Posts (Atom)