DreamWeek #3

Technical

Everything you need to know about the Shellshock Bash bug
Yes, last week was all about the shellshock bug – here you can find all the info you need to know about this bug. Apparently this one is much bigger than Heartbleed.

Total Moving Face Reconstruction
Library that takes a single video of a person’s face and creates a high detail 3D shape for each video frame. You can find there not only the explanation but a great yt-movie with samples.

Microsoft OCR Library for Windows Runtime
Another great package can be found in NuGet gallery. This one empowers you to easily add text recognition capabilities in your application.

Microsoft legend Ray Ozzie wants to kill the conference call
Ray Ozzie creates new type of application – as it is advertised this app “even your boss will approve of”. Find out more.

Non-technical

Liberia signs ‘transformational’ deal to stem deforestation
Liberia will be the first nation in Africa to completely stop cutting down trees in return for development aid from Norwegian country.

The ultimate photo shoot: on location in Iceland with the iPhone 6 and iPhone 6 Plus
Incredible photo shots made with iPhone with some explanation there. Definitely worth reading and seeing.

DreamWeek #2

Another set of links from the last week.

Technical

KaTeX
Interesting library for programmers familiar with LaTeX who would like to insert math equations on their web pages.

Cloud Face
Have you ever stared at the clouds and seen faces, animals, dragons etc.? Apparently this is not only seen by humans but als face recognition algorithms can be fouled by clouds. On this page you will find plenty of great examples.

I crashed the web servers of a $100M+ multi-national corporation …
Another example that everyone makes mistakes! What you can learn from this post is that making mistake doesn’t mean you will be fired. A mistake gives you chance to face with deadlines, stress, angry users and yelling boss – and during that time you will learn new things about yourself.

Stack Overflow – performance lessons (part 2)
This is second part of the performance lessons learned on Stack Overflow – in the second part Matt is looking on the examples of coding performance lessons.

Non-technical

Microsoft confirms it will buy ‘Minecraft’ for $2.5 billion
OK, I had to put it here. This was probably the most important purchase during last week.

All-electric racing: Formula E’s thrilling debut
I am fan of Formula 1 and when I heard about the idea to start Formula E I wasn’t really convinced it is a good idea. But apparently you can find some new experiences in that sport – I think we can see the grow in the interest of that new motorsport!

The Song of the Introvert – Rands in Repose
Are you a programmer? Probably yes – and you are probably also an introvert. This article is for you.

The Marshmallow Test for Grownups – Harvard Business Review
We are distracted every day by a rising number of devices and services. This is the study by psychologists about how our ability to be creative and focused decreases because of all the distractions.

The Feynman Lectures on Physics, The Most Popular Physics Book Ever Written, Now Completely Online
Recently I read (and described here as well) the autobiography of Richard Feynman. I also found that you can read his whole book online for free.

Surely You’re Joking, Mr. Feynman!

You have no responsibility to live up to what other people think you ought to accomplish. I have no responsibility to be like they expect me to be. It’s their mistake, not my failing.

okladka

I really like biographies of famous people mostly because you often don’t think about people in newspapers or tv as normal person. But they have a normal life, they drink, they smoke (as Mr. Feynman for example marihuana). By reading such books you can find them in different context and you will find out that they are normal as you or me.

And that’s what this book is about – it is a set of anecdotes told by Richard Feynman.The book is a transcription from conversations that Feynman had with his close friend and drumming partner Ralph Leighton. You will see a Nobel-winner who did not like this prize because it changed his life so much.

This is not a standard biography book where you read about person’s childhood then school, college, work etc. You won’t find there any dates any particular events from the start of the book to its end. This is something different. But it doesn’t make this book boring – contrary this is very funny and entertaining. You can open this book on any page and dive into the text – no matter where, you will find plenty of situations from Feynman’s life. You will read about his fascination with safe-cracking, ventures into art (drawing especially) and samba music, drums. There are also more serious ones – such as description of times when he worked on Manhattan Project.

There are plenty of famous quotations from these book. One of my favorite I put on the beginning of the post. And truly Richard Feynman lived with that in mind – that brought him a meeting with Bohr who wanted someone who will tell truly what he thinks about his ideas (not only agree!)… For more you need to go to the library! Smile

Generics–some things all developers should know

generics 000

Generics are available in most programming languages which are currently used by developers. In this post we will dig into details of the C# language. We will also check how they differ from Java and C++ implementation.

generics 001

When the C# was released in 2002, it did not contain generics. This could also be called “generic-free world”. In that time, a developer had to apply casting when he was using collections such as ArrayList. Sometimes that led to exceptions which either stopped the application or had to be wrapped in try/catch clauses. But more importantly, casting was influencing the performance, which in my opinion, put forward the biggest argument to introduce generics in the next version of the C# framework.

During that time we had to use an object as either a parameter or return type in almost every place. This is bad – like Jon Skeet says – it’s “bad in a necessary evil kind of way”. At some point you will simply need to do the casting – and that is just bad.

generics 002

I think it’s very important to know what is going on out there in the universe. However, before we dig into details about the C# implementation of generics, let’s see how other languages implemented them or emulated such behavior.

generics 003

In C++ there are no generics, there are templates. In a nutshell, they are macros on steroids.

When a particular type is used in C++, the compiler for that particular type parameter generates appropriate code. The compiler will change all the places where the type parameter is used and will change it to the used type for creation of a template. The compiler creates the type only once – so using the same type again is going to apply the same code. This means that there can be a great output library size increase because of that – we will just have more types (as we will see, this is quite more clever in CLR).

One of the biggest advantages of the C# implementation, which the templates have, is the fact that the type parameter does not have to be just type names. We can use function names, variable names or even constant expressions (e.g. 20). This is a very interesting feature which I sometimes miss in C# (but very rarely clip_image001 ).

generics 004

Object = one (ring?) to rule them all.

This is all that JVM knows about a particular object (ok, there is some metadata to describe a type as generic in the bytecode before compilation) that it is generic.

generics 005

This is great example from Skeet book (which I highly recommend  – C# in depth is just must-read position if you are C# developer!) – if it only compiled Smile 

1 ArrayList strings = new ArrayList(); 2 strings.add("hello"); 3 String entry = (String) strings.get(0); 4 strings.add(new Object());

and this one

1 ArrayList<String> strings = new ArrayList<String>(); 2 strings.add("hello"); 3 String entry = strings.get(0); 4 strings.add(new Object());

Both of these codes would, in fact, generate the same bytecode – just because of Java’s feature which is called type erasure. As it is described in the documentation – it is applied by the compiler to implement generics. This just replaces all the type parameters in generic types, insert type casts where necessary and generate bridge methods to preserve polymorphism in extended generic types.

Why?! This is a normal question at this point. I think that the main reason is the back-compatibility. Even from the new code with generics you are able to run your application on an older runtime. This is not possible in C# 2.0 – your application just won’t start on CLR 1.1. Another interesting feature, which can be missing in C#, is the generic variance. Through it you are can form something like this:

1 ArrayList<? extends SuperBase> myList;

generics 006

I wish I could describe more languages and their generics implementation and I hope I can extend this in the future. If any of you have any interesting information – please leave a comment.

generics 007

Microsoft presented a new version of a language in a pack with Visual Studio 2005 and .NET Framework 2.0. One of the most important features introduced by the new version were generics. You may also remember that in 2005 we received partial classes from MS, anonymous methods, a yield keyword and thanks to generics we got Nullable types as well.

generics 008

Using System.Object does not only cost the runtime to perform casting, but also when you keep your value type as an object – there is boxing involved. And you probably know very well that this causes a lot of operations – when saving (there is boxing), and when you retrieve value from the collection – there is unboxing. The JIT can treat value types, so there is no boxing and unboxing involved!

There is not much improvement in performance for reference types. Though this was also slightly improved, you probably won’t see much improvement in your application just by changing the type to the generic one.

generics 009

Thanks to generics we got compile checks – so the safety of our programs increased. But did we get…

generics 010

This question was on my mind for quite a long time. And I am not sure how many bugs in applications were caused by the wrong casting. I talked to a couple of people in my company and we agreed that this is not the greatest output programming the world got from generics. It’s undoubtedly true, but we should not treat generics as a solution for a programmer’s lack of knowledge, experience and time. clip_image001[4]

generics 011

When you use generics in your code it is very often more self-explanatory than the non-generic version. Sometimes we just call our collection list or set and without a comment (which very often goes out-of-date very soon) or deeper analysis it is not easy to recognize its purpose. Thanks to generics the IDE support is also possible.

generics 012

Ok, finally we can see how it looks like:

1 IList<int> myList = new List<int>();

generics 013

There are several ways you can declare a type:

1 List<int> list1 = new List<int>(); 2 var list2 = new List<int>(); 3 IList<int> list3 = new List<int>();

I have presented three different ways of declaring a list. At first glance they would all give us the same.

To be honest, only the 1st and 2nd will give us *exactly* the same resultvar is just removed during a compilation time and changed by the type itself. It does not cause any performance overhead during runtime – you can use it.

In my opinion, the best option is the third one where you use an interface type – I will prepare another post about this behavior, and since I’ve seen so many developers using the first one, I need to give it more focused attention. In brief, you will be able to assign any other type which implements IList to list3 – for example your own type. When using the 1st – such a possibility does not exist.

generics 014

It is very usual that you want to call a method of the generic type – to do that you must define what that type is. You can do that by type constraints – where you force the type to fulfill the constraint.

There are three types of constraints:

1. The first type of constraint ensures that the type is either reference or value type. To say that the type is a reference type you just set where T : class.  The twin constraint is T : struct – where you ensure that the generic is a value type.

2. The second and most encountered by me is the constructor type constraint. In this one you just order that the type must have a parameterless constructor. The only thing you need to remember while using this one is that it must be the last constraint for any particular type parameter.

3. This one is, of course, the most complicated of constraint types– where you ensure that a type can be converted to another type (or in other words – that your generic type implements a specific base class or interface). There is also another interesting (let’s call it a sub-type) feature – that your generic type can be converted to another type argument – this is called a type parameter constraint. I often find this one difficult to understand, but after a while with playing around this comes very handy. Here are couple of samples:

1 class Base1<T> where T : IDisposable 2 class Base2<T> where T : IEnumerable<T> 3 class Base3<T, U> where T : U

These are very easy cases of the conversion type constraint – but you probably already got it. In the future I will dig into the details about these constraint types – because I sometimes receive questions from developers in my company regarding these types of parameter constraints (these are probably harder to understand).

generics 015

Why do we even care if the new() constraint should be the last one?! Here’s what the answer is – it can just frequently save you a lot of time. Of course this simple one is caught by the compiler with a correct error message:

new_error

But you need to remember – that not all of these cases are so easy to spot. And what is also more important – you will need no compiler to design your class on a whiteboard correctly and talk to your peers.

generics 016

Let’s see an example when you work with arrays. Let’s say that you have a hierarchy of fruits – where you have a class Fruit and two derivatives from that – Apple and Banana.

1 Apple apple = new Apple(); 2 Fruit fruit = apple; 3 fruit = new Banana();

Thanks to polymorphism this would work correctly – the runtime will have the information about the banana as the fruit. And this will be resolved correctly.

But hey – if it works correctly on the types, maybe we could do the same with arrays, right? You probably would like to be able to do that:

1 Apple[] apples = new Apple[] { new Apple(), new Apple() }; 2 Fruit[] fruits = apples;

All of this works fine – up to this point. But you have already imagined an example when you just try to assign a banana as the first element of fruits. This will case the ArrayTypeMismatchException. There is a special IL method which checks whether you assign the correct type to the array.

arraytypemismatch 

generics 017

OK, so for five years there were no changes in the generics. But when the version C# 4.0 came into the light, there were some changes in the generics implementation.  Microsoft introduced covariance and contravariance to the language – everything thanks to two additional keywords – in and out.

When you think variance you should think – possibility to use an object as one type, as if it was another, but always in a type-safe way. You are used to that – but you probably never heard of it by such a name – for example when you should return BaseTypeClassand you return SomeDerivedClass instead.  In case of generics, things get a little bit more complicated – because this is not the type, but the type parameters on which the variance is applied.

generics 018

Every book, blog post or any other kind of an article about the variance starts with the covariance – probably because this one is just easier to understand as it seems to be more natural for us.

Covariance means that the value is being returned from an operation back to the caller. One of the most commonly used examples of the covariant type is IEnumerable<T>. When you check the implementation you will see this:

1 public interface IEnumerable<out T> : IEnumerable 2 { 3 IEnumerator<T> GetEnumerator(); 4 }

There is one particular thing you should look at – the out keyword. By setting this keyword you guarantee that the type parameter is returned only by your API. Thanks to that you are able to make such an operation:

1 IEnumerable<Manager> managers = GetManagers(); 2 IEnumerable<Employee> employees = managers;

And everything will work as usually thanks to the improved implementation of the language and runtime. Nothing will be broken, because the base collection (managers) will never be changed – because it is OUT-going parameter.

generics 019

As you probably have guessed – the other way around is the cotravariance where the type goes IN-to the type. That is why the keyword in is used for these types. One of the most used example of the contravariant class is

1 public interface IComparable<in T> 2 { 3 int CompareTo(T other); 4 }

As you can see, the contravariant IComparable<T> is marked with inkeyword – this means that API is consuming the values instead of producing them.

Now you probably understand why it is called contra-variant – because it is contrary to the usual derivation direction.

1 IComparer<Employee> empl = GetEmployeeComparer(); 2 IComparer<Manager> mng = empl;

You probably ask – why are the two additional keywords even introduced – and the compiler is able to derive that information directly from the source code. I think that you should consider two things when you think about that:

1. We are all humans and the more we express our ideas, the easier another person (or even ourselves in the future!) will understand. By looking at the source code you don’t have to think whether it is contravariant, covariant or even invariant (which means that it goes both ways and we cannot mark it either way!).

2. It is easy to add another method into the class (interface) which could probably break some code using it. By having these keywords you will see that by changing that, you are making breaking change by making something invariant. And that’s something we don’t want to do – break some code we are not aware of (either in our own implementation or even worse, in the client who uses our API!).

The topic of contra- and covariance is so broad that it requires more attention, so you can expect another blog post about it in the future.

generics 020

As you have seen – generics gives C# very much. I have only covered the most important parts. Some of them need more detailed attention and this is what I would like to do – prepare shorter posts in which I will dive into more details for some cool features the generics have.

generics 021

This whole post is based on my presentation I created for my colleagues. I wanted to share it with you and I hope you found this more interesting than just a plain text you usually see on the programming blog.

FYI: I do not have rights to the pictures and photos which you can see.

DreamWeek #1–List of useful links for a week

During the whole week I find plenty of interesting, inspiring and well.. just cool stuff on the web. I think it’s worthy to share it with you all. So I decided that once a week I will publish a list of things which I read and by which I was inspired during the week.

(Yes I know this blog was dead for almost a year. But plenty of things were going on and I did not have time to focus on blog. This time is now over and I can get back to blogging! Yay!)

Technical

The Warehouse is Dead, Long Live the Warehouse!
I know this is an old post from NuGet.org team – but by reading that you can find out that everyone makes mistakes! I am thinking about writing a post which will cover this area – making mistakes and getting feedback.

WHEN IS A CONSTANT NOT A CONSTANT? WHEN IT’S A DECIMAL…
Jon again took my mind on the higher gear during his post. You really need to focus when you read his blog posts – this one is on the same category. He is using Roslyn to investigate the curious cases of const decimal value and goes very deep into the implementation and the IL. Totally worth reading!

The Curious Case of iPhone 6+ 1080p Display
Of course – this week was all about Apple. This cool article describes details about pixel density in the upcoming iPhone 6+ display.

I wrote the original blue screen of death, sort of
Cool, as usual – post on The Old New Thing. This is a great starting point to find other posts there which are not only interesting and inspiring, but also very educational.

No More Cracked Smartphone Glass
At last – times when we care about our smartphones’ screens are coming to an end?

Manufacturing Advances Mean Truly Flexible Devices Are on the Way
Another article about smartphones’ – this time about their flexible versions. We trully live in such interesting times..

Non-technical

How the global banana industry is killing the world’s favorite fruit
Will our children eat bananas? Great article because sometimes we forget that some things are not just “from our supermarket” but actually they are produced (or grow) somewhere else on the planet.

Visual guide to selling software as a service by @prezly
You blog? You make content? This is what I found this week – super presentation and great content. Especially for marketing companies. But all of us can get something from this presentation.