Declaration-site and use-site variance explained

A common question posed by programming novices who have their first encounters with parametrized types (“generics” in Java and C#) is “Why can’t I use a List<Apple> as a List<Fruit>?” (given that Apple is a subclass of Fruit) Their reasoning usually goes like this: “An apple is a fruit, so a basket of apples is a fruit basket, right?”

Here’s another, similar, example:

Milk is a dairy product, but is a bottle of milk a dairy product bottle? Try putting a Cheddar cheese wheel into the milk bottle (without melting or shredding the cheese!). It’s obviously not that simple.

Let’s assume for a moment that it was possible to use a List<Apple> as a List<Fruit>. Then the following code would be legal, given that Orange is a subclass of Fruit as well:

List<Apple> apples = new ArrayList<>();
List<Fruit> fruits = apples;
fruits.add(new Orange());

// what's an orange doing here?!
Apple apple = apples.get(0);

This short code example demonstrates why it doesn’t make sense to treat a List<Apple> as a List<Fruit>. That’s why generic types in Java and C# don’t allow this kind of assignment by default. This behaviour is called invariance.

Variance of generic types

There are, however, other cases of generic types where assignments like this actually could make sense. For example, using an Iterable<Apple> as an Iterable<Fruit> is a reasonable wish. The opposite direction within the inheritance hierarchy of the type parameter is thinkable as well, e.g. using a Comparable<Fruit> as a Comparable<Apple>.

So what’s the difference between these generic types: List<T>, Iterable<T>, Comparable<T>? The difference is the “flow” direction of objects of type T in their interface:

  1. If a generic interface has only methods that return objects of type T, but don’t consume objects of type T, then assignment from a variable of Type<B> to a variable of Type<A> can make sense. This is called covariance. Examples are: Iterable<T>, Iterator<T>, Supplier<T>inheritance
  2. If a generic interface has only methods that consume objects of type T, but don’t return objects of type T, then assignment from a variable of Type<A> to a variable of Type<B> can make sense. This is called contravariance. Examples are: Comparable<T>, Consumer<T>
  3. If a generic interface has both methods that return and methods that consume objects of type T then it should be invariant. Examples are: List<T>, Set<T>

As mentioned before, neither Java nor C# allow covariance or contravariance for generic types by default. They’re invariant by default. But there are ways and means in both languages to achieve co- and contravariance.

Declaration-site variance

In C# you can use the in and out keywords on a type parameter to indicate variance:

interface IProducer<out T> // Covariant
    T produce();

interface IConsumer<in T> // Contravariant
    void consume(T t);

IProducer<B> producerOfB = /*...*/;
IProducer<A> producerOfA = producerOfB;  // now legal
// producerOfB = producerOfA;  // still illegal

IConsumer<A> consumerOfA = /*...*/;
IConsumer<B> consumerOfB = consumerOfA;  // now legal
// consumerOfA = consumerOfB;  // still illegal

This annotation style is called declaration-site variance, because the type parameter is annotated where the generic type is declared.

Use-site variance

In Java you can express co- and contravariance with wildcards like <? extends A> and <? super B>.

Producer<B> producerOfB = /*...*/;
Producer<? extends A> producerOfA = producerOfB; // legal
A a = producerOfA.produce();
// producerOfB = producerOfA; // still illegal

Consumer<A> consumerOfA = /*...*/;
Consumer<? super B> consumerOfB = consumerOfA; // legal
consumerOfB.consume(new B());
// consumerOfA = consumerOfB; // still illegal

This is called use-site variance, because the annotation is not placed where the type is declared, but where the type is used.


The variance behaviour of Java and C# arrays is different from the variance behaviour of their generics. Arrays are covariant, not invariant, even though a T[] has the same problem as a List<T> would have if it was covariant:

Apple[] apples = new Apple[10];
Fruit[] fruits = apples;
fruits[0] = new Orange();
Apple apple = apples[0];

Unfortunately, this code compiles in both languages. However, it throws an exception at runtime (ArrayStoreException or ArrayTypeMismatchException, respectively) in line 3.

C++ inheritance for Java developers

Both Java and C++ are modern programming languages with native support for object oriented programming (OOP). While similar in syntax and features there are a bunch of differences in implementation and (default) behaviour which can be surprising for Java developers learning C++ or vice versa. In my post I will depict the basics of inheritance and polymorphism in C++ and stress the points Java developers may find surprising.

Basic inheritance or user defined types

Every Java programmer knows that all classes have java.lang.Object at the root of their inheritance hierarchy. This is not true for C++ classes: They do not share some common base class and do not inherit more or less useful methods like toString() oder clone(). C++ classes do not have any member functions besides the constructor and destructor by default. In Java all instance methods are virtual by default, meaning that if a subclass overrides a method from a superclass only the overridden version will be visible and callable on all instances of the subclass. We will see the different behaviour in the following example:

#include <iostream>
#include <memory>

using namespace std;

class Parent
  void myName() { cout << "Parent\n"; }
  virtual void morph() { cout << "Base class\n"; }

class Child : public Parent
  void myName() { cout << "Child\n"; }
  virtual void morph() { cout << "Child class\n"; }

int main()
  // initialisations more or less equivalent to
  // Parent parent = new Parent(); etc. in Java
  unique_ptr parent(new Parent);
  unique_ptr parentPointerToChild(new Child);
  unique_ptr child(new Child);
  parent->myName(); // prints Parent as expected
  parent->morph(); // prints Base class as expected
  parentPointerToChild->myName(); // surprise: prints Parent!
  parentPointerToChild->morph(); // prints Child class as expected
  child->myName(); // prints Child as expected
  child->morph(); // prints Child class as expected
  return 0;

The difference to Java becomes visible in line 29 where we call to an instance of Child using the type Parent. Since myName() is not virtual the implementation in the parent class is not overridden but only shadowed by the subclass. Depending on the type of our variable on which we call the method either the parent method or the child method (line 31) is invoked.

Access modifiers in Java and C++ are almost identical as both are offering public, protected and private. As there are no packages in C++ protected restricts access to child classes only.

Different syntax and fewer keywords

There are no keywords for interface or abstract class in C++ but the concepts are supported by pure virtual functions and multiple inheritance. So a class that defines a virtual function without a body like:

class Interface
  virtual void m() = 0;

becomes abstract and cannot be instanciated. Subclasses must provide implementations for all pure virtual functions or become abstract themselves. A class having exclusively pure virtual functions serves as the equivalent of an Java interface in C++. Since C++ supports inheritance from multiple classes you can easily use these features for interface segregation (see ISP). Most people advise against multiple implementation inheritance although C++ makes that possible, too.

Class interface control

One problem with inheritance in Java is that you always inherit all non-private methods of the base classes. This can lead to large and sometimes unfocused interfaces when using inheritance blindly. Delegation gives you more control about your classes interface and means less coupling but requires a bit more writing effort. While you can (and should most of the time) do the same in C++ it offers more control to your classes interface using private/protected inheritance where you can decide on an per-method-basis which functions to expose and what virtual functions you would like to override:

class ReuseMe
    void somethingGreat();
    void somethingSpecial();

// does expose somethingGreat() but hides sometingSpecial()
class PrivateParent : private ReuseMe
    using ReuseMe::somethingGreat;

Children also gain access to their parents protected members.

Using super class functions and delegating constructors

Calling the functions of the parent class or other constructors looks a bit different in C++, as there is no super keyword and this is only a pointer to the current instance (please excuse the contrived example…):

class CoordinateSet
    string toString() {
        stringstream s;
        std::copy(coordinates.begin(), coordinates.end(), std::ostream_iterator<double>(s, ","));
        return s.str();
    vector<double> coordinates;

class Point : public CoordinateSet
    // delegating constructor
    Point() : Point(0, 0) {}
    Point(double x, double y)
    // call a function of the parent class
    void print() { cout << CoordinateSet::toString() << "\n"; }

I hope my little guide helps some Java people getting hold of C++ inheritance features and syntax.

The typography of source code

Take a look at the following source code, can you guess which language this is written in?

It’s CSS. CSS has a typical layout with a minimal indentation depth where a group of selectors embraces lines of attribute / value pairs. Take a look:

As with the example above all of our source code has typical (macro) typographical properties. This features can tell us something about the language used, about the type of artifact and even about the composition of the individual parts of a class or file itself.
Here’s another typical file in a common language:

In this case it is a Java class. It reveals itself by its block of imports at the top (1). The class declaration (2) is rather long probably due to generics. The typical block of field declarations (3) starts the class body. Quickly a short constructor follows (4). It is too short but has parameters so it is a convenience constructor. The real constructor is next (5). Here we see the constructor is too long. It does so much we almost take it for a normal method. At (6) we see parameters for a method call one on each line. The slight change in indentation at (7) indicates an inner class. The block at (8) confirms the inner class: here parameters from the outer class are referenced by prefixing it with OuterClassName.this.
Even subtle things like annotations (9) can be seen at macro level.

Let’s compare two object oriented languages one is Java, the other one Ruby.

Several things can be noticed (besides the Java version is much longer than the Ruby one). First the Java block of imports is missing in Ruby. The field block seems to be small in Ruby but another big block follows in the middle. The Ruby class shown here is a Rails domain class. The block in the middle contains the associations (has_many and friends). Looking closer one can glimpse that the closing part of the methods seems a bit thicker in Ruby (Ruby closes the method with end whereas Java closes with }). But besides the difference a similarity is also there: both classes have a couple of short methods near the bottom.
Even within one language and one framework classes with different purpose have different shapes. Seeing a Rails model and a controller side by side shows some interesting patterns.

While controllers have a block at the end of the class (which is for permitting request parameters), model classes have blocks of scope declarations and associations typical at the center. Whereas model methods are short in both dimensions, the controller methods have a level of indentation (which is a typical if which checks for the success or failure of the operation).

But why does this all matter? The first thing when we look a block of text is its (macro) structure. Typical patterns can help us to identify the type of class or language. Inconsistencies could be bugs or parts which were difficult to write. Kevlin Henney advocates in his talk Seven Ineffective Coding Habits Of Many Programmers for formatting techniques that are stable and produce a minimal set of alignments. Because:

You convey information by the way you arrange a design’s elements in relation to each other. This information is understood immediately, if not consciously, by the people viewing your designs.

Daniel Higginbotham,

I think many more things can be seen by looking at the macro level but for now I leave you with another picture of a sourcecode of a well known language. Can you guess what it is?

Recap of the Schneide Dev Brunch 2015-04-12

brunch64-borderedA week ago, we held another Schneide Dev Brunch, a regular brunch on the second sunday of every other (even) month, only that all attendees want to talk about software development and various other topics. So if you bring a software-related topic along with your food, everyone has something to share. The brunch was a little sparsely attented this time but there was enough stuff to talk about. As usual, a lot of topics and chatter were exchanged. This recapitulation tries to highlight the main topics of the brunch, but cannot reiterate everything that was spoken. If you were there, you probably find this list inconclusive:

Review of San Francisco

As it turned out, San Francisco might be half a planet away, but several of our attendees happened to live there for a while. They described the city and its culture to us and shared stories about specific persons and places. For a moment, San Francisco was just around the corner.

Review Ninja

One reason that San Francisco came up was the mentioning of Review Ninja, a second-generation code review tool with one of the coolest project URLs ever. If you ever were smitten by code review tools like gerrit, then Review Ninja might be worth a look. It has a lightweight and simplistic approach to a activity that could as well end up being a bureaucratic nightmare.

Be convincing

Another topic was the art of being convincing – to convince people of something useful but unfamiliar. We concluded that you cannot change people, no matter the effort. Only people can change people. You can try to facilitate their change, though. But don’t expect appreciation or even acknowledgement for your effort. Everybody will be convinced that they came up with the solution themselves. That’s the art of being convincing – or so we convinced ourselves.

Google recruitment process

We spent a lot of time discussing the Google recruitment process that one attendee had just successfully passed. But it’s a long and extensive process, so our timeframe fit. There is a book, “Cracking the Coding Interview” by Gayle Laakmann McDowell, that seems to be quite useful for preparation on the daylong in-depth interview marathon that needs to be mastered if you want to join Google. A number of similar books try to teach you the knowledge necessary to pass the recruitment process – not the job that usually follows, mind you, just the recruitment. Our participant counted more than thirty distinguishable contacts with Google during the process. The process itself is highly formalized, while interviews are performed by normal engineers on Google’s side. The comparability between applicants is achieved through the great number of interviews to even out random outliers.

Nearly all big IT companies utilize a similar recruitment process, so this insight can be applied nearly everywhere: If you want to be recognized as talented, you have to be prepared for the tests to come. Don’t assume that your interviewer presupposes anything about your abilities. Just because you have a degree in computer sciences doesn’t mean you know how to program, for example. They will test for that, and with rather challenging tasks, so better learn your stuff again.

Work environment

Anticipating the next topic, we talked about different workplace setups, like open-plan offices, separate rooms for everyone and the like. A great insight was that very different preferences exist. The ideal work environment of one developer is a nightmare for the next. And now imagine how difficult it gets to agree on a trade-off in a bigger team. We couldn’t even agree on music vs. silence for in-zone programming sessions, let alone the style of music that should be playing.

Room setup

As a practical exercise, we tried to rearrange the desks in the Softwareschneiderei to increase the number of desks on our second floor. We started without any restrictions on placement and iterated through several layouts, discussing several side-effects and drawbacks in our solutions. In the end, two applicable layout alternatives survived our weeding process. It was a lesson in group dynamics and emergent rulesets and even gave us a viable result.

 What defines object orientation?

We talked about the different approaches to define object orientation in terms of developer thinking. The classic approach of giving entities an identity was explored as well as the rather personal definition of flowing functionality instead of flowing data. We agreed that knowing all kinds of programming paradigms (with imperative, object oriented and functional being the major ones) enables developers to make the right choices for the task at hand. Being unable to choose leads to being ineffective fast.

The Java Memory Model

A short recap of the very informative and insightful talk about the Java Memory Model given by one of our attendees closed our brunch. The Java Memory Model (or any other memory model in fact) is a great help in determining if something weird can possibly happen with your code, like one thread observing a field X being set first and Y second, while another thread swears that Y was set first and X later. A memory model helps you to understand the quantum mechanics of your programming language and therefore survive multithreaded programming. And a simple rule will let you understand the vast majority of the Java Memory Model, as shown in the talk. I highly recommend you read up about the memory model of your favorite programming language.


As usual, the Dev Brunch contained a lot more chatter and talk than listed here. The number of attendees makes for an unique experience every time. We are looking forward to the next Dev Brunch at the Softwareschneiderei. And as always, we are open for guests and future regulars. Just drop us a notice and we’ll invite you over next time.

Creating a GPS network service using a Raspberry Pi – Part 1

Using sensors is a task we often face in our company. This article series consisting of two parts will show how to install a GPS module in a Raspberry Pi and to provide access to the GPS data over ethernet. This guide is based on a Raspberry Pi Model B Revision 2 and the GPS shield “Sparqee GPSv1.0″. In the first part, we will demonstrate the setup of the hardware and the retrieval of GPS data within the Raspberry Pi.

Hardware configuration

The GPS shield can be connected to the Raspberry Pi by using the pins in the top left corner of the board.

Raspberry Pi B Rev. 2 (Source: Wikipedia)

Raspberry Pi B Rev. 2 (Source: Wikipedia)

The Sparqee GPS shield possesses five pins whose purpose can be found on the product page:

Pin Function Voltage I/O
GND Ground connection 0 I
RX Receive 2.5-6V I
TX Transmit 2.5-6V O
2.5-6V Power input 2.5-6V I
EN Enable power module 2.5-6V I
Sparqee GPSv1.0

Sparqee GPSv1.0

We used the following pin configuration for connecting the GPS shield:

GPS Shield Raspberry Pi Pin-Nummer
2.5-6V +3V3 OUT 1
EN +3V3 OUT 17

You can see the corresponding pin numbers on the Raspberry board in the graphic below. A more detailed guide for the functionality of the different pins can be found here.

Relevant pins of the Raspberry Pi

Relevant pins of the Raspberry Pi

After attaching the GPS module, our Raspberry Pi looks like this:

Attaching the GPS shield to the Raspberry

Attaching the GPS shield to the Raspberry


GPS data retrieval

The Raspberry GPS communicates with the Sparqee GPS shield over the serial port UART0. However, in Raspbian this port is usually used as serial console, which is why we cannot directly access the GPS shield. To turn this feature off and activate the module, you have to follow these steps:

  1. Edit the file /boot/cmdline.txt and delete all parameters containing the key ttyAMA0:
    console=ttyAMA0,115200 kgdboc=ttyAMA0,115200

    Afterwards, our file contains this text:

    dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
  2. Edit the file /etc/inittab and comment the following line out:
    T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

    Comments are identified by the hash sign; the result should look as follows:

    #T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
  3. Next, we have to reboot the Raspberry Pi:
    sudo reboot
  4. Finally, we can test the GPS module with Minicom. The baud rate is 9600 and the device name is /dev/ttyAMA0:
    sudo minicom -b 9600 -D /dev/ttyAMA0 -o

    If necessary, you can install Minicom using APT:

    sudo apt-get install minicom

    You can quit Minicom with the key combination strg+a followed by z.

If you succeed, Minicom will continually output a stream of GPS data. Depending on wether the GPS module attains a lock, that is, wether it receives GPS data by a satellite, the output changes. While no data is received, the output remains mostly empty.


Once the GPS module starts receiving a signal, Minicom will display more data as in the example below. If you encounter problems in attaining a GPS lock, it might help to place the Raspberry Pi outside.


A detailed description of the GPS format emitted by the Sparqee GPSv1.0 can be found here. Probably the most important information, the GPS coordinates, is contained by the line starting with $GPGGA: In this case, the module was located at 33° 55.3471′ Latitude North and 117° 41.7128′ Longitude West at an altitude of 112.2 meters above mean sea level.


We demonstrated how to connect a Sparqee GPS shield to a Raspberry Pi and how to display the GPS data via Minicom. In the next part, we will write a network service that extracts and delivers the GPS data from the serial port.

Streaming images from your application to the web with GStreamer and Icecast – Part 2

In the last article we learned how to create a GStreamer pipeline that streams a test video via an Icecast server to the web. In this article we will use GStreamer’s programmable appsrc element, in order to feed the pipeline with raw image data from our application.

First we will recreate the pipeline from the last article in C source code. We use plain C, since the original GStreamer API is a GLib based C API.

#include <gst/gst.h>

int main(int argc, char *argv)
    GError *error = NULL;

    gst_init(&argc, &argv);

    GstPipeline *pipeline = gst_parse_launch("videotestsrc ! vp8enc ! webmmux ! shout2send ip= port=8000 password=hackme mount=/test.webm", &error);
    if (error != NULL) {
        g_printerr("Could not create pipeline: %s\n", error->message);
        return 1;
    gst_element_set_state(pipeline, GST_STATE_PLAYING);

    GMainLoop *loop = g_main_loop_new(NULL, FALSE);


    return 0;

In order to compile this code the GStreamer development files must be installed on your system. On an openSUSE Linux system, for example, you have to install the package gstreamer-plugins-base-devel. Compile and run this code from the command line:

$ cc demo1.c -o demo1 $(pkg-config --cflags --libs gstreamer-1.0)
$ ./demo1

The key in this simple program is the gst_parse_launch call. It takes the same pipeline string that we built on the command line in the previous article as an argument and creates a pipeline object. The pipeline is then started by setting its state to playing.


So far we have only recreated the same pipeline that we called via gst-launch-1.0 before in C code. Now we will replace the videotestsrc element with an appsrc element:

#include <gst/gst.h>

extern guchar *get_next_image(gsize *size);

const gchar *format = "GRAY8";
const guint fps = 15;
const guint width = 640;
const guint height = 480;

typedef struct {
    GstClockTime timestamp;
    guint sourceid;
    GstElement *appsrc;
} StreamContext;

static StreamContext *stream_context_new(GstElement *appsrc)
    StreamContext *ctx = g_new0(StreamContext, 1);
    ctx->timestamp = 0;
    ctx->sourceid = 0;
    ctx->appsrc = appsrc;
    return ctx;

static gboolean read_data(StreamContext *ctx)
    gsize size;

    guchar *pixels = get_next_image(&size);
    GstBuffer *buffer = gst_buffer_new_wrapped(pixels, size);

    GST_BUFFER_PTS(buffer) = ctx->timestamp;
    GST_BUFFER_DURATION(buffer) = gst_util_uint64_scale_int(1, GST_SECOND, fps);
    ctx->timestamp += GST_BUFFER_DURATION(buffer);

    gst_app_src_push_buffer(ctx->appsrc, buffer);

    return TRUE;

static void enough_data(GstElement *appsrc, guint unused, StreamContext *ctx)
    if (ctx->sourceid != 0) {
        ctx->sourceid = 0;

static void need_data(GstElement *appsrc, guint unused, StreamContext *ctx)
    if (ctx->sourceid == 0) {
        ctx->sourceid = g_idle_add((GSourceFunc)read_data, ctx);

int main(int argc, char *argv[])
    gst_init(&argc, &argv);

    GstElement *pipeline = gst_parse_launch("appsrc name=imagesrc ! videoconvert ! vp8enc ! webmmux ! shout2send ip= port=8000 password=hackme mount=/test.webm", NULL);
    GstElement *appsrc = gst_bin_get_by_name(GST_BIN(pipeline), "imagesrc");

    gst_util_set_object_arg(G_OBJECT(appsrc), "format", "time");
    gst_app_src_set_caps(appsrc, gst_caps_new_simple("video/x-raw",
        "format", G_TYPE_STRING, format,
        "width", G_TYPE_INT, width,
        "height", G_TYPE_INT, height,
        "framerate", GST_TYPE_FRACTION, fps, 1, NULL));

    GMainLoop *loop = g_main_loop_new(NULL, FALSE);
    StreamContext *ctx = stream_context_new(appsrc);

    g_signal_connect(appsrc, "need-data", G_CALLBACK(need_data), ctx);
    g_signal_connect(appsrc, "enough-data", G_CALLBACK(enough_data), ctx);

    gst_element_set_state(pipeline, GST_STATE_PLAYING);


    gst_element_set_state(pipeline, GST_STATE_NULL);


    return 0;

We assign a name (“imagesrc”) to the appsrc element by setting its name attribute in the pipeline string in line 58. The element can then be retrieved via this name by calling the function gst_bin_get_by_name. In lines 61-66 we set properties and capabilities of the appsrc element such as the image format (in this example 8 bit greyscale), width, height and frames per second.

In lines 71 and 72 we connect callback functions to the “need-data” and “enough-data” signals. The appsrc element emits the need-data signal, when it wants us to feed more image frame buffers to the pipeline and the enough-data signal when it wants us to stop.

We use an idle source to schedule calls to the read_data function in the main loop. The interesting work happens in read_data: we acquire the raw pixel data of the image for the next frame as byte array, in this example represented by a call to a function named get_next_image. The pixel data is wrapped into a GStreamer buffer and the duration and timestamp of the buffer is set. We track the time in a self-defined context object. The buffer is then sent to the appsrc via gst_app_src_push_buffer. GStreamer will take care of freeing the buffer once it’s no longer needed.


With little effort we created a simple C program that streams image frames from within the program itself as video to the Web by leveraging the power of GStreamer and Icecast.

Managing C++’s complexity or learning to enjoy C++


I have never been a big fan of C++ coming from C and Java. C is a nice little language and yet offers many means of code structuring. Java offers many object-oriented features and makes the use of them quite easy. Together with garbage collection, a huge ecosystem and powerful IDEs it lets you work on the problem at hand at quite some speed. C++ on the other hand is a huge language with myriads of concepts and supports almost all features of C. So at first it seemed to me as worst of all worlds. Similar to Scala which is also a quite large multi-paradigm language (that I happen to like).

Why and how use C++ then?

On my job I have to work with C++ regularily. Diving deeper into the language, learning STL and modern code styles I am starting to actually like C++. In addition to the runtime-efficiency (that you can get with C too, and to some extent even with Java) C++ provides many means for robust programs and nice abstractions. Using idioms like RAII, the Algorithms library, smart pointers and operating mostly on values takes away most of the resource management and memory buffer handling hassle. But since C++ is so large and supports so many programming styles I think the following measures really help to build robust and maintainable programs and enjoy using C++:

  • Establish rules for your code, e.g. no naked pointer, no friend, no multiple inheritance, use of exceptions etc. That way you create an idyllic world where you develop most of the time and the number of pitfalls is greatly reduced. Your rules may change like you see them fit but adhere to them and do not change them lightly.
  • Protect your code from legacy/3rd party code and libraries using anti-corruption layers, wrappers and adapters. They are means to preserve your idyllic world and make life there easier. Don’t let the null pointers slip in.
  • Use modern idioms and APIs, as modern as your compiler/environment supports them (see gcc c++11 support, Visual Studio etc.). Like in other programming environments take special care regarding your dependencies! Manage them carefully.
  • Understand and learn to use STL containers, smart pointers, RAII, algorithm, streams etc. There are plethora of concise, clear and robust solutions for your everyday problems without the need of iterating over vectors with and index variable…
  • Build classes/components that manage their resources and provide easy to use interfaces. Use type-rich interfaces and work mostly with values. The compiler will help you a lot more than with a pointer-heavy and mostly primitives style. Treat delete (outside of a destructor) and naked new as smells and restrict them to areas where you cannot find a way around them.

Where is the fun for me?

I find it rewarding and satisfying carefully crafting these easy-to-use components and improving them over time. Adding some const statements, deciding between pass-by-value or pass-by-reference, making the components thread-safe, finding the right balance between using classes or free floating functions, private inheritance etc. You can really do a lot have the compiler as a friend instead of a dreaded enemy and let it guarantee many things programmers tend to do wrong. Build your components so that they are hard to use in a wrong way. Then there are really cool features like call_once library support, closures (aka lambda functions) and type inference with the auto keyword, user-defined literals and many more.