Combining two objects in lodash

I’m a huge fan of the lodash library. It encourages functional programming style in JavaScript and as a result lets you write less error-prone and more readable code.

Some time ago I discovered the assign (extend) function which copies properties from target object(s) and assigns them to the target object. It also returns the target object. This is very handy whenever you want to combine properties from two objects into one object.

For example, given these two objects:

…instead of copying properties manually:

…one could write:

The result in c would be the same. However, with assign, object a will be modified. What I often wanted to do is to “merge” a and b into c but not modify neither a nor b.

Recently I learnt that the way to do this is the following:

With above code we copy properties of a and b into a new empty object and than return this new object. This is exactly what we wanted to achieve.

Scala for C# developers – part III

I’m back from a rather lenghty break and would like to continue the Scala for C# developers series. So far I have covered the syntax, the basics of OO in Scala and functions. In this post I will look at the Option type and pattern matching.

Issues with null references

If you have programmed in C# (or Java, or any other language that supports null references) you must already know the pain of NullReferenceException. This exception is thrown whenever you are expecting that a variable points to an actual object but in reality it does not point to anything. Therefore, calling a method on such reference would result in the exception.

There is a famous quote from Tony Hoare who introduced the concept of null references claiming that it was his billion-dollar mistake:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

The Option type

What does it mean when a NullReferenceException is thrown? As I said, it means that the CLR was expecting a reference to an object but found an empty refence and does not know what to do with it. In the majority of cases, it means that you as the programmer should have thought about it and check for the null reference before doing anything with it. Unfortunately, it would require some great discipline to keep track of all references that could become null and to take care of each and every one of them.

The Option type comes to rescue. The idea is to force the compiler to do the hard work for you.

Option[T] is an abstract type which has two subclasses: Some[T] and None. For example, a value of type Option[Int] represents an object that can, but does not have to hold some integer. If this Option is an instance of Some than the object has some value. If it’s None than it does not have any value.

So, None is like null except we explicitly declare that an object can be None by making it an Option. If we decide to use Option types in our project we must forget about null references completly. Therefore, whenever we expect a value of type T to be optional, we must declare it as Option[T]. Thanks to that, the compiler will forbid us from writing such code:

For this to compile, we must explicitly handle the case when the provided argument is undefined.

Such code, although lengthier, is much, much safer than traditional code which allows use of null references.

Of course, the key thing is to make sure that there is never a null inside Some value. However, this is easy to ensure as long as we decide not to use null references in the whole project.

Pattern matching

The above code snippet introduces some new syntax. The match
construct is the Scala syntax for pattern matching. It is a very powerful tool common in functional programming. You can think of it as a much more advanced switch statement which always returns a value as a whole.

In the above example, the value of textOpt is examined. It is an instance of Option type and we know that it has two subclasses. Therefore, there are two case branches. The first branch demonstrates how the value contained inside Some[T] can be extracted.

Pattern matching can be used with simple types:

Additionally, pattern matching works very well with case classes which we discussed in the previous post.

Why I like C#: feature-wise comparison with Java

Recently I was browsing Quora and was quite surprised to stumble upon this question: Java vs C#. Is Microsoft finally closing the gap? I decided to have a closer look and found more of similiar questions there.

Furthermore, at the place where I am currently working at, I am the only person with .NET background amongst mostly JVM people. We are all working on Scala projects and my colleagues are often surprised when I tell them that this or that Scala feature is also available in C#.

This makes me want to write a blog post about how cool a language C# is, especially when compared with Java. I want to underline that I’m speaking only about the language features and not about things like popularity, cross-platformness, ability to deploy easily, etc.

Generics

C# creators were in a great situation since they could learn from Java’s mistakes. They didn’t waste the opportunity and did the right thing. The main problem with Java’s generics is type erasure. The term means that the information about the type parameter of a generic type is not available at runtime. In simple words, this:

…becomes this:

Type erasure makes writing generic types more difficult and less clean. For example, sometimes generic methods have to explicitly take a Class object representing the type parameter (like here).

In C# this is not the case. You can easily access the type of the type parameter:

 

Lambdas, higher-order functions and LINQ

Not long ago I found this article on Hacker News. It discusses some of the new features of Java 8 such as lambdas, streams and functional interfaces. These things are called modern Java whereas in C# they have been available for quite a long time (not to mention that they have been available in Haskell or Ocaml for even longer).

While not everyone has to agree about superiority of functional over imperative programming, it’s hard to disagree that processing collections with higher-order functions (such as map/select or filter/where) is cleaner, less error-prone and much more readable than doing it with loops.

Even though Java has already adopted lambdas and higher-order functions, it seems that C# has better support for them. Examples?

  • In Java 8, you need to convert collections to Stream before calling map or filter
  • C# has built-in syntactic sugar for such opearations which makes such code even more readable and cleaner

 

Type inference

Type inference is a nice feature that allows you not to declare the type of a variable if it’s being initialized on the same line. While it’s not as great as in Scala or Haskell, it certainly lets you cut some boilerplate code. Java does also have some type inference but it is limited to generic methods.

With type inference, the below declaration:

…can be written as:

 

Asynchronous code

C# 5.0 introduced excellent support for asynchronous programming. The async and await keywords let you replace callback-style programming with code that looks exactly as if it were synchronous. It makes the code much cleaner and far easier to read.

The comparison with Java is especially striking if you look at pre-Java 8 code where in order to execute a piece of code asynchronously, you had to create an anounymous type with one method! Have a look at usage of the AsyncHttpClient library:

…and compare it with this C# code:

 

Value types

Value types is part of the reason why there is a C in C#. There are two kinds of types in C# – value types and reference types. Value types differ from reference types mainly in the assignment sementics. When you assign a reference to a new variable, this variable points to the same object. When you assign a value type to a new variable, the whole piece of memory holding the data in the type is copied. This is great for lightweight objects representing data. In some situations it might save you from writing the equals and hashCode operators. What’s more, value types cannot be null which makes them safer than reference types. Finally, value types make primitive types such as int or double more natural.

In Java, every type is a reference type.

Extension methods

Extension methods allow you to add functionality to an object (even if it had already been compiled). One of the cool uses of extension methods is providing a concrete method for an interface. Also, they allow better code reuse and makes it easier to write fluent APIs.

Example of an extension method:

 

C# 6.0 features

Finally, there are many great features introduced in C# 6.0. The language seems to be gravitating towards functional programming, which I think is a good idea, but most of them do not require the programmer to learn a new paradigm. To name some of the most exciting features of C# 6.0:

  • Expression bodied methods – syntax improvment which makes you write shorter code
  • Conditional null operator – which allows writing safer code (which feels like simplified Maybe monad)
  • Expression filters – convenient syntax for exception handling
  • Using static members – again, an improvment to make your code even shorter

 

Conclusion

I have named just a few of the language features of C# which I believe make it a superior language to Java. Obviously, there are many more things to look at when choosing a language than its features. However, I think it’s worth mentioning that thanks to Mono, Xamarin and Microsoft’s BizSpark program for startups, .NET became much more accessible to small companies and startups than it was a decade ago.

Scala for C# developers – part II

This is the second post in the series. Click here to see the previous part.

In the previous post I covered the basics of Scala syntax as well as some comparison of OOP in Scala and C#. Today, I will focus on lambdas and higher-order functions.

Functions as function parameters

You are most likely familiar with lambda expessions in C#. Lambda expression is simply an anonymous function. Lambdas are useful when you want to pass a piece of code as a parameter to some other function. This concept is actually one of the cornerstones of functional programming.

One great example of how useful lambdas are operations on collections. The following piece of code takes a list of integeres, filters out odd numbers and multiplies the remaining numbers by 5.

In Scala, it would look surprisingly similiar:

Scala uses more traditional FP names for map and filter but apart from this, the code looks very similiar. In Scala, we can make it a bit tighter (and less readable):

As you can see, Scala allows you to use anonymous parameters inside anonymous functions. However, be careful when using the underscore notation. The (_ * 5) + _ expression does not translate into x => (x * 5) + x. Instead, the second underscore is assumed to be the second anonymous parameter of the lambda, therefore meaning this: (x, y) => (x * 5) + y.

Returning functions

C# not only allows to have functions which take functions as parameters but also functions that return other functions. In the following piece, the GetMultiplier function takes a single integer and returns a function that can multiply it by any other integer.

Let’s see how would it look in Scala:

Again, it looks fairly similiar. The Function1[Int, Int] has the same semantics as Func%lt;int, int> – it represents a one-argument function that takes an integer and returns an integer. Interestingly, in Scala Function1[Int, Int] can be denoted as Int => Int.

We can go one step further and rewrite the above function as:

This certainly looks odd – our function now has two parameter lists! It is Scala’s special syntax for functions returning functions. You can pass one integer to getMultiplier and what you get is a partially applied function. What is the type of getMultiplier now? It’s Int => (Int => Int) which can also be written simply as Int => Int => Int. This technique is called currying. The idea of currying is that a function with multiple parameters can be treated as a function that takes the first parameter and returns a function that takes a second parameters which returns a function… and so on.

Scala for C# developers – part I

Recently, after three years of focusing mainly on the .NET platform, I’ve changed jobs. My current company uses Scala for server-side programming in their projects. I was very happy for this transition. Both Scala and C# can be considered hybrid functional and object-oriented programming languages. However, Scala seemed to feel more functional than C# – more built-in functional constructs, tighter syntax, default immutability, etc. While this is true, I was surprised how many similarities these languages. I concluded that as long as you have already seen the more functional side of C#, it is really easy to transition to Scala. This post series will discuss some of the similarities and differences between Scala and C#.

Syntax

The syntax in Scala is indeed quite different from C# syntax. Let’s have a look at this HelloWorld program in Scala.

First of all, the object keyword seems unfamiliar. In Scala, singleton objects are part of the language. It is like declaring a class and saying that there can be only one instance of this class – and this instance is like a global variable, accessible by name of the class. The concept is not very similiar to static classes in C#.

Another difference is method declaration. As you can see, in Scala the type (of method or variable) comes after the name, not before. The def keyword marks a method declaration. The Unit type is a bit like void in C# – it is the return type of a method which does not return any sensible value.

One more thing – the println call is not preceeded with any class/object name. In Scala, objects can behave like namespaces in C#. It is possible to import all methods from an object. The using static members feature in C# 6.0 gives you the same behaviour.

It is possible to write the above piece in a more compact way:

As you can see, the braces can be omited for single-line methods. Also, the Unit type disappeared – now it is inferred by the compiler (similarly to how the var keyword works in C#). Again, C# 6.0 brings us something similiar – the expression-bodied members.

Classes and objects

I have already introduced the object keyword. Let’s now have a look at regular classes.

Again, let’s look at the differences, case by case. There is no such thing as class constructor here, as we know it from C#. The constructor arguments are writen next to the class name. The initialization code lies directly in the class body. You could conclued that the class can only have one construcor in Scala. This is not true – additional constructors can be provided as secondary constructors.

In the following lines there are two field declarations. Fields are public by default. The keyword used here is val which means that x and y are immutable. Immutability is at the heart of functional programming. Immutable values are values that cannot be modified. It may seem counterintuitive at first but in fact immutable values can help you eliminate whole classes of errors form your programs. I will discuss immutability in more detail in one of the future posts. For now, I recommend this article.

Member fields do not have to have type declarations – the compilers infers the correct types.

The distanceFrom method declaration is pretty straightforward. You may notice that there is not return statement here. This is because in Scala the method always, by default, returns the last expression in its body. In our case, there is only one expression.

Class instantiation is very C#-like – we use the new keyword and provide constructor arguments.

Case classes

Scala introduces a very useful concept called case class. Let’s see how we could rewrite the above code in a more succinct way.

With case classes, all constructor parameters automatically become members, hence no need for member initialization. Also, the new keyword is no longer needed for creating new instances.

Although very helpful, this is only one aspect of case classes. More importantly, case classes automatically provide value-base equals, hashCode and toString implementations. Additionally, they are sealed. In other words, case classes are perfect for creating immutable data types.

Let’s now compare the C# and Scala implementations of a class representing a two dimensional point so that you can see for yourself how nicer it is to write in Scala.

And now C#:

As you may now, implementing equals is not trivial. Not to mention that we would need to implement GetHashCode. In Scala we get the default implementation for free.

Editable cells in Angular UI Grid not working

This week at work I spent too much time on this small issue I had with UI Grid so I thought I will share the solution.

Angular documentation tells you that it is possible to make a column editable by setting enableCellEdit to true in columnDef.

What wasn’t obvious for me, is that for this to work you also need to load the ui.grid.edit module and add the uiGridEdit directive to the element on which you enabled uiGrid. Code example below.

 

 

Is array of Dogs an array of Animals? Covariance, contravariance and invariance explained – part 2

This post is a continuation of Is array of Dogs an array of Animals? Covariance, contravariance and invariance explained – part 1.

Method overriding

Type variance is not just relevant to generics but also to ineritance of regular, not generic, classes.

When overriding a method in a class you usually make sure that it has the same argument types and return type. Note that it is not always necessary.

For example, it makes sense for the overriding method to return a subtype of the return type of the original method.

The caller of getAnimal will expect an instance of Animal. Returning something more derived (a Dog) will be perfectly type safe. Therefore, we can say that return type of overriden method is covariant.

Let’s now look at argument types.

AdvancedDogComparator is a specialized version od DogComparator. Just as DogComparator, it can compare two Dogs but it can do more than that. So, AdvancedDogComparator.isLarger must take at least a Dog, but it can also take the supertype of Dog – an Animal. We can say that parameter types of the overriden method are contravariant.

You may see an analogy here to how we deduced in the first post that it should be possible to make MyList<T> covariant as long as it does not have the add method.

Return type covariance is supported both Java and C#. Argument type contravariance is not supported neither in Java nor C#.

One more interesting case – if you create a covariant generic interface of type T, C# will not allow you to create a method that takes T in it.

Compiler output:

This is actually related to the contravariance of argument types when overriding methods. Any subtype of IMyList would have to override add. Therefore, the T would have to be contravariant but it is declared as covariant (the out) keyword which makes a contradiction.

Is array of Dogs an array of Animals? Covariance, contravariance and invariance explained – part 1

Welcome to the first post on my blog. I would like to dedicate it to a topic that sounds quite intimidating but is in fact quite simple to understand. There are already good explanations of type variance to be found on other blogs or Stack Overflow but I would like to take a broader approach and look at how different programming languages deal with it.

The problem

So, what is this cryptic title about? Let me start with this classic example in Java.

Would you expect this piece of code to compile? The answer depends on what operations are available on MyList. Let’s assume that MyList is very similiar to ArrayList and it allows you to get and add.

Now, assuming that the questioned piece of code would compile, it would be perfectly valid to add a Cat to the list of Animals which is in fact a list of Dogs. This is not something we would want the compiler to allow.

In this case, MyList<Dog> is not (does not inherit from) MyList<Animal>. We call MyList invariant. This is the kind of behaviour that we get in Java.

Let’s now assume that MyList is read-only and does not have an add method.

Now, the previous issue is no longer the case. If we call animals.get() we can get either a Dog or a Cat an we are ok with this.

In such case, it makes sense to allow the questioned piece to compile. Hence, MyList<Dog> is (does inherit from) MyList<Animal> and we call MyList covariant.

Java

As stated before, in Java the below piece would not compile. In other words, generic types in Java are invariant. This is quite limiting when compared to other languages which allow you to specify variance for generics.

Compiler output:

However, there is an interesting exception to generic’s invariance in Java. The below code will compile:

So, what happens when we try do add a Cat to an array of Dogs? Java gives us an exception (of course this will happen on runtime and not on compile time). So, arrays are covariant in Java! This is not a very elegant situation and the reasons behind it are mainly historic. There is a good explanation of this on Stack Overflow.

C#

Similarly to Java, C# would not allow us to compile below code:

Compiler output:

However, C# goes a step further and allows us to create variant generic interfaces. It is possible to mark a type parameter with the in keyword to make the generic interface covariant.

There are some nice examples of contravariance in C#. Since covariance means that you can use a more derived type than specified in type parameter, in contravariance you can use a more generic type than specified. It may seem a bit counterintuitive but let’s look at the Action<T> type which represents a function that takes a parameter of type T and does not return anything.

In this case, it makes sense to say that Action<Base> is Action<Derived>. Action<Derived> requires a prameter of type Derived so giving it an instance of something more generic (Base) is ok.

In the next post I will look at how variance is exploited in inheritance.