Jeffrey van Binsbergen.nl

C and C++ are not dead

Recently I’ve picked up C++ development again and it is great. As most people know, I love fast applications and I love making them. With C#, Python, Node.JS and many more higher level languages gaining in popularity and performance getting pretty cheap, low level languages like C are often forgotten. Hopefully this article will encourage more people to give it a try.

Efficiency matters

A big reason to choose for a low level language is of course: Efficiency. You’re working close to the hardware and you suddenly gain flexibility to do all kinds of fun things, especially with memory access. And it still matters for any application which needs to do some actual work. Conversions, Machine Learning, Image processing or what I’m using it for at this moment: IoT data processing and aggregation. It all runs incredibly fast. To make it more fun for myself I’m testing it on a Raspberry PI zero (5 dollar Linux computer) and it can still handle thousands of clients at the same time. It is great!

Another reason why to think of efficiency: Running it in the cloud. Running things in cloud is actually not that cheap, especially if you need a bit more performance than the budget option. Most problems in the cloud can be solved by throwing a credit card towards it but all the costs add up. By making a small efficient application for any important processing, you can really get the required specs down.

Making something very efficient allows people to do more with your application. If data from a chart takes half a second to get generated, you can only put 1 or 2 on a web page before it feels ‘too slow’. When putting some effort in making a small efficient application. You can display your charts with a lot of additional information instantly and extract information from it the user actually wants to see.

Portability

It is incredibly portable if you are careful with platform specific features and libraries. The same code can run on Windows, Linux, FreeBSD, etc. with just some small modifications to the platform specific functions. You can even try to run your code on an embedded system like an ESP8266. This is especially useful when making a library which can be integrated into a wide selection of other projects on different platforms.

Downside

Making your application takes more time. You will have to worry about things you otherwise never see. Clean up your used data from the memory. A lot of the handy flexible features of your favorite high level language won’t be available. Also some other people will probably think you’re insane. I can definitely recommend taking a look and experimenting with it.

Developers can do more than just typing code

A good programmer is an artist. Making sense of an difficult idea and actually implement it in a way which makes customers happy is an art. A good developer will find solutions and make things possible on a smart and efficient way. Typing code is just one of the things a developer has to do, and it is the boring part.

Unleash the creativity

Creativity is an important part of making a good application or website. There are some challenges and there are literally thousands of ways to deal with them. Often someone has to think outside of the box and that is alright. Most developers actually became a developer just to deal with those challenges! It is like a complicated puzzle and you can actually feel proud solving it and often together with other developers.

Layers, Layers, Layers

Nowadays a lot of software development is done in a very guideline-followed style. People make abstractions of everything, adding more and more layers to any application. Maybe throw in some dependency injection and other fancy stuff which suddenly seems to be a requirement for everything. This style is forcing developers to think in a very similar and limited style. Every feature you add is like walking the same road. Surely it looks nice on the progress charts but there is no room for creativity at all. Often new technologies are introduced to the system to keep things interesting, even while some “old methods” would’ve been even better.

It can make a big difference

Most applications can be ‘dumbed down’ to a level where creativity during developing isn’t needed. Code will be made. Resources will be thrown and in the end an application will work. But the code will probably not be very efficient. There are no smart tricks being done and people will just hope the used libraries and framework is efficient enough to deal with the difficult problems. Also the application will do just what the requirements were and nothing more. Boxes are ticked, money is earned. Done.

Give some freedom to the developer, let them get a feel for the application and what people want to do with it. They’ll get motivated and enjoy working on it, and they actually want it to turn into a good application. Let them see how the customer is responding to it. The application will turn out better, faster and actually something which will make a customer happy.

Stay careful

Of course there are many reasons people started programming like we do now. Just letting everyone do whatever will sometimes result in messy code which are difficult to integrate together. Also progress is harder to track as a creative moment isn’t always guaranteed and sometimes ideas just don’t work out for various reasons. Let developers work together on things and make clear requirements about what the application should do for a customer and also what future plans are with said application. Also make sure developers get enough time to really focus on this application, including some time to refactor their code.

Awesome JavaScript Tricks

Just like C-Sharp, JavaScript has some unique tricks not known to everyone. In this article I'll share some of the tricks I know about JavaScript. Like everything with JavaScript, some tricks will require a recent version of your web browser but all tricks should work in all major browsers.

Object.defineProperty

This is a method available in all recent browsers (Firefox 4+, Chrome 5+, Safari 5.1+, Opera 11.6+, IE 9+) which allows you to do unique and awesome stuff with properties. For example you can use Getters and Setters:

var obj = {};

Object.defineProperty(obj, 'myprop', {
get: function() {
return myprop * 2;
},
set: function(value) {
alert('Setting value to '+value);
myprop = value;
}
});

obj.myprop = 5;
alert(obj.myprop); // 10

Another use is making a property read only and unchangeable (not even by another defineProperty call).

var obj = {};
obj.theAnswer = 42;

Object.defineProperty(obj, 'theAnswer', {
writable: false, // This makes the value read only
configurable: false // This makes this property undeletable
});

obj.theAnswer = 5;
alert(obj.theAnswer); // 42

The defineProperty method can be useful when making a custom elements, which can act just like a native element does (for example, directly updating the UI after you do: customElement.value = "123";).

Arguments as array

You can use the arguments keyword to get all parameters. Use this to make functions which accepts a unspecified range of arguments.

function printf(text) {
var i = 0, args = Array.prototype.slice.call(arguments); // Turn the arguments-object into a normal array

text = text.replace(/\%s/g, function(a) {
return args[++i];
});

return text;
}

alert(printf("Hello %s! Your score is %s", "Mr Anderson", 1337));
// Hello Mr Anderson! Your score is 1337

edit: Changed [].slice to Array.prototype.slice.call after someone pointed out it had some issues with Chrome

Override default methods

Like in every programming language, Objects in JavaScript have a few default methods you can override.

var TestObject =  function() {
this.valueOf = function() {
return 42;
};
this.toString = function() {
return "I am a test object";
};
};

var obj = new TestObject();
alert(obj == 42); // true
alert(obj); // I am a test object

This can be useful when making objects comparable to each other or making your code easier to debug (You can get a nice textual representation of your object instead of just a [object] text).

Function methods

In JavaScript, there are quite a few ways of working with functions. A more unknown feature are the methods available at functions. For example: By using the method apply you can call a function and give the parameters as an array, you can also change the 'this' scope of that function.

alert.apply(this, ["I am a message"]); // Shows 'I am a message'

The bind method can also be quite useful, especially when working with timeouts and intervals.

var TestObject = function() {
this.someValue = 100;
this.doSomething = function() {
alert(this.someValue);
};

setTimeout(this.doSomething, 1000); // undefined
setTimeout(this.doSomething.bind(this), 2000); // 100
}

new TestObject();

In Firefox, you can also retrieve the source code of a function:

function myFunction() {
return 1337;
}
alert(myFunction.toSource()); // Shows the function defined above including source

With keyword

Supported by pretty much every browser, but not recommended for use as it can causes a lot of confusion. Still for the sake of informing I'll include it in this overview. The With keyword allows you to use properties and functions from an object, without putting the object name in the front (As if all properties and functions are global).

with(document) {    
with(body) { // document.body
var textNode = createTextNode("Bla"); // document.createTextNode
appendChild(textNode); // document.body.appendChild
}
}

It also works when eval-ing code, Which can be useful if you want to support scripts with short function names. Note that it does not limit the script! Every other function will still be available. It can also be used to temporarily override global functions and properties:

var obj = {
alert: function() {}
};
with (obj) {
alert('This alert is not visible');
}

Comma operator

Next to all the more common operators, JavaScript has another operator: The Comma operator. The comma operator allows you to do some actions before returning a value. This can be useful in places where JavaScript only expects a single value. It can be compared to the && and || operators, but with the comma-operator all expresssions are always executed. Example:

function IsAlwaysFalse() {
return false;
}

function IsAlwaysTrue() {
return true;
}

// Continues when the value is not False/Null/0/Undefined
alert(IsAlwaysFalse() && 42); // False
alert(IsAlwaysTrue() && 42); // 42

// Continues when the value is False/Null/0/Undefined
alert(IsAlwaysFalse() || 42); // 42
alert(IsAlwaysTrue() || 42); // True

// Always continues
alert((IsAlwaysFalse(), 42)); // 42
alert((IsAlwaysTrue(), 42)); // 42

Scope labels

It is possible to put code in a specific scope and name the scope. By doing so it allows breaking out of a specific scope using the 'break' keyword.

myLabel: {
alert('I am shown :)');
break myLabel;
alert('I'm not :(');
}

Multiple lines

And a small trick to end this article with: Use the \ character to allow using multiple lines in your string definitions. Just put them on the end of the line like this:

var x = "abc\
def";

Note that it doesn't actually add a linebreak in the string. You still have to use \r\n for that to happen.

Conclusion

Like C-Sharp, JavaScript has a lot of hidden gems. This is just a small selection of the lesser known things I know about. Do you have some awesome tricks in JavaScript worth a mention? Let me know!

Awesome little C# tricks

C# is a very powerful flexible programming language and the .NET standard library offer tons of great functionality ready to use in your code. As a developer, I always look for new ways to write code quicker, make it more readable and faster, or just more fun. Here are some lesser-known tricks I've found and/or used myself.

Null checking

string result = variable1 ?? variable2 ?? variable3 ?? String.Empty;

You can use the ?? operator to check if a value is null and set a default value then, which is neat of its own. But you can also chain it to also check for other variables before resulting in a default value. Also, in C# 6 there is a new ?. operator you can use to quickly check for child properties:

string result = variable1?.childproperty?.childproperty ?? String.Empty;

Parsing a formula

var result = Convert.ToDouble(new System.Data.DataTable().Compute("(3*3)+1", null)); // 10

By using a bit of a creative trick of a method of the DataTable, you can parse simple formulas in your application. This can be useful when you want to support editable formulas in your application. For example to allow a reseller to customize their price based on an original prize: originalPrize * 1.2 + 1.

Making aliases for type names

using MyDictionary = Dictionary<string, List<int>>;

Put the above code outside your class declaration, and you'll be able to use "MyDictionary" as an alias. This can be useful when working with generics. They tend to make code unreadable quickly.

WeakReference

Sometimes when retrieving some specific information from the database, you want to cache it in case it needs to be requested again. But you don't want to store it forever in your memory. For example: Information about the current user doing a website request. By using the WeakReference class you can initialize your class with user information and allow the .NET garbage collector to unload it at any time it wishes (for example when it needs memory). Note the example below requires C# 4.5.

public class UserInfo
{
public string RealName;

private static Dictionary<string, WeakReference<UserInfo>> Cached =
new Dictionary<string, WeakReference<UserInfo>>();

public static UserInfo FromCache(string identity) {
UserInfo userInfo;

if (Cached.ContainsKey(identity) && Cached[identity].TryGetTarget(out userInfo))
return userInfo;

userInfo = new UserInfo()
{
RealName = "" // Retrieve from database
};
Cached[identity] = new WeakReference<UserInfo>(userInfo);

return userInfo;
}
}

Example usage

UserInfo.FromCache(User.Identity.Name).RealName

Implementing operators in your class

You can implement the standard Math operators in your C# class. It looks like something idiotic to do, but it can actually turn out to be really useful. For example this is done with the default DateTime struct:

TimeSpan difference = new DateTime(2015,01,01) - new DateTime(2014,01,01);
// difference.TotalDays is 365

Another use case would be to quickly throw a few groups of people together like I've did in this example:

class Program
{
static void Main(string[] args)
{
var town1 = new GroupOfPeople("A");
var town2 = new GroupOfPeople("B","C");
var bothTowns = town1 + town2;
// bothTowns.Names contains "A", "B", "C"
}

public class GroupOfPeople
{
public string[] Names;

public GroupOfPeople(params string[] names)
{
Names = names;
}

public static GroupOfPeople operator +(GroupOfPeople a, GroupOfPeople b)
{
return new GroupOfPeople()
{
Names = a.Names.Concat(b.Names).ToArray()
};
}
}
}

MethodImplAttribute

The MethodImplAttribute attribute provides some useful things you can do. You can put it above Methods and Property accessors.

By using [MethodImpl(MethodImplOptions.Synchronized)] you can make methods and properties thread-safe (Fields, those without {get; set;} are already thread safe). In C# 3.5 and earlier, it does a lock(this) { }, however in newer C# versions it uses a different implementation without locks making it even faster to use. The use of this attribute can be compared with using the synchronized keyword in java.

public class Bank {
public double Balance
{
private set;
[MethodImpl(MethodImplOptions.Synchronized)]
get;
}

[MethodImpl(MethodImplOptions.Synchronized)]
public void AddTransaction(double amount)
{
if (amount + Balance < 0)
throw new Exception("Not enough balance");
Balance += amount;
}
}

To really micro-optimize your method calls, you can use [MethodImpl(MethodImplOptions.AggressiveInlining)] to make the compiler move a method implementation to the code calling it (reducing a method call). This can be useful for those small methods which needs to be called a lot of times, for example: When drawing frames in a game. Note that this won't save you that much time, but it is a fun trick nonetheless.

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static double StartPosWhenCentering(double containerSize, double childSize)
{
return (containerSize / 2) - (childSize / 2);
}

Summary

There is a lot of nice gems you can do with C#. Knowing a few of them will definitely make your days as a C# developer happier. Let me know if you also know a few tricks.

The dark side of libraries

Software libraries are awesome, they add a lot of functionality within seconds to your application. However, it also comes with a few downsides. Should you really add that library to your project? Here is a small article doing my favorite thing: Nagging about using libraries inappropriate.

The right tool

Most libraries are designed with a specific use in mind, and most can be used for a lot of other purposes as well. Usually when you get creative, you may come across bugs or stuff which just isn’t possible, adding hours to your development time you thought you saved. Always see if a library is made for what you want to use it for.

Also does the library really offer you a solution you can’t make yourself within a few hours? If you want to generate a word document it is perfectly understandable, but don’t use JQuery if you just want to toggle the visibility of a text (Yes I’ve seen this being done, multiple times). You can do that with one line of native JavaScript code as well.

Resources

An obvious downside is resources: footprint, ram usage and performance. Most libraries have a bunch of code you will never use, but still get embedded in your project. Resources are still important when thinking about: Speed of initializing, low-end devices, cloud solutions (program smart or pay more) and even power consumption.

With JavaScript libraries, adding a library means more data for the browser to download when visiting your site the first time. The first visit of your visitor matters a lot. On some connections adding a library easily causes a few extra seconds of delay. Also JavaScript code is parsed on every single page request and can cause for a slow user experience. People really don’t like slow websites.

Maintainability

A thing most people don't think about is that using a library requires knowledge about that library, even if it is ‘very easy to use’. Not every library is that easy to gasp just by looking at the code. This is especially true for libraries which require usage of a specific pattern (for example KnockoutJS). Whenever someone new works on your project, they have to get familiar with all the code and libraries used which takes up time. The behavior of a library may even surprise yourself when fixing bugs.

All libraries get updated at some point because of bug fixes or new features. Upgrading may cause for problems in your project and not upgrading may leave security leaks or awful bugs in your application. You save development time, but you increase the hours you have to put in maintaining your project.

Conclusion

Libraries aren't evil but think before adding a library to your project. You may be able to stop your application to get slow, buggy and difficult to maintain just by writing a few lines of code yourself.

JavaScript Array extensions

For my Japanese learn site I needed a way to quickly filter on an array of objects in JavaScript. I really like LINQ in C# and I missed it in JavaScript. So I decided to make it myself, which barely took 5 minutes but saved me probably hours and a lot of repetitive loops.

Array.prototype.Where = function (func) {
var items = [];
for (var i = 0; i < this.length; i++) {
if (func(this[i]))
items.push(this[i]);
}
return items;
};

Array.prototype.First = function (func) {
for (var i = 0; i < this.length; i++) {
if (func(this[i]))
return this[i];
}
};

Array.prototype.Take = function (count) {
var items = [];
for (var i = 0; i < this.length && i < count; i++) {
items.push(this[i]);
}
return items;
};

Array.prototype.Skip = function (count) {
var items = [];
for (var i = count; i < this.length; i++) {
items.push(this[i]);
}
return items;
};

Array.prototype.OrderBy = function (func) {
return this.sort(function (a, b) {
return func(a) - func(b);
});
};

Array.prototype.Select = function (func) {
var items = [];
for (var i = 0; i < this.length; i++)
items.push(func(this[i]));
return items;
};

Array.prototype.Max = function (func) {
var highest = null;
for (var i = 0; i < this.length; i++) {
var value = func(this[i]);
if (highest == null || value > highest)
highest = value;
}
return highest;
};

Array.prototype.Unique = function (func) {
var items = [];
var uniqueKeys = [];
for (var i = 0; i < this.length; i++) {
var key = func(this[i]);
if (uniqueKeys.indexOf(key) < 0) {
items.push(this[i]);
uniqueKeys.push(key);
}
}
return items;
};

Array.prototype.Randomize = function () {
var items = this.slice();
var currentIndex = items.length, temporaryValue, randomIndex;

while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

temporaryValue = items[currentIndex];
items[currentIndex] = items[randomIndex];
items[randomIndex] = temporaryValue;
}
return array;
};

A few examples of cool stuff you can do by using this code:

var colors = [
{ name: "Blue", votes: 2 },
{ name: "Green", votes: 9 },
{ name: "Red", votes: 1 }
];

var color = colors.First(function (a) { return a.votes > 5 });
alert(color.name); // Green

var filteredColors = colors.Where(function (a) { return a.votes < 5 });
alert(filteredColors.length); // 2

var colorsInUppercase = colors.Select(function (a) {
return { name: a.name.toUpperCase(), votes: a.votes }
}).OrderBy(function(a) {
return a.votes;
});
alert(colorsInUppercase[0].name); // RED

Of course, after making those few functions and being all happy about it... I saw that are multiple existing projects which do just the same thing. Oh well, I like to make stuff myself anyway.

Show all articles