You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!
Generic type parameters were introduced in C# 2.0, and they gave us the ability to write code that works against any type that matches a set of constraints and remove the need to create type-specific overloads, e.g.:
A few years passed, and dynamic types was introduced in C# 4, which allows us to bypass compile-time type checking (type checking still happens at runtime) when we use the dynamic keyword, e.g.:
this code works so long as the ‘+’ operator is defined for the runtime types of obj1 and obj2, otherwise, you’ll get a RuntimeBinderException when this code is executed. This kind of type checking is often referred to as Duck typing.
Duck typing is a very powerful language feature but it also makes your code less safe, as you now face the possibility of having runtime type errors that would have otherwise been caught by the compiler.
It’s a damn shame that there’s no way for you to combine the powers of generics and dynamic typing.. because if you could, you’d be able to write DoSomethingElse like this instead:
public void DoSomethingElse<T, U, V>(T obj1, U obj2) where T + U => V
var obj3 = obj1 + obj2;
which stops you from mistakenly trying to invoke the method with an int and a List<int> at compile time, and saves you 10 mins of debugging and bug fixing time.
Well, would it blow your mind if I tell you that such feature already exists in the .Net framework today? No, I kid you not, member constraints in F# lets you do just that!
In F#, you can specify a statically resolved type parameter by prefixing it with the caret symbol ( ^ ), e.g. ^T. These type parameters can be used with member constraints which allows you to specify that a type argument must have a particular member or members in order to be used.
Take the following F# code for instance:
It’s equivalent to the earlier C# version of DoSomethingElse, but this function has the following signature:
which says that the types ^a and ^b used in the function must have a static member ‘+’ defined on either one of them that can be used on instances of these two types.
You can explicitly state member constraints too, for instance:
Member constraints are very useful in those tight spots where you find yourself wrestling with the .Net type system, it gives you the flexibility of duck typing but also the safety of static typing, so really it gives you the best of both worlds!
However, useful as it may be, there are some restrictions to when you can use member constraints.
First, they cannot be used with generic type parameters, they can only be used with statically resolved type parameters.
Secondly, they can only be used with functions or methods that are inline.
Which brings us to the topic of inline functions, which as the name suggests, creates the functions ‘inline’.
But what does that mean? It means that, at every call site to an inlined function or method, the concrete types for the statically resolved type parameters (e.g. ^T, ^U) are resolved and the specific code for those types are inserted at the call site.
This has the obvious implication that the compiler will generate many duplicated IL code for inline functions and it increases the size of your assembly.
By contrast, a normal function or method will generate only one instance of that function or method and every call site makes a ‘jump’ to the location of that function or method in memory to execute it. The inlining behaviour also has some performance implications which we will go through shortly.
The one major restriction on inline functions is that an inlined function cannot be overloaded.
When to use inline functions
As with most powerful features, such as duck typing and inline functions, they are often open to abuse.. Personally, I think it’s important for one to think carefully about what it is that they’re trying to do before deciding to use the latest and greatest language features just for the sake of it.
Take the last code snippet for example, there’s no reason why I can’t solve this problem using interfaces and generic type parameters – define an ISpeaker interface with a Speak member and requiring the parameter x to be an instance of ISpeaker.
Doing so will achieve the same end goal, there will be a stronger contract (a well understood, shared interface) and the code will be cleaner and easier to read:
As far as I’m aware, there are really only two main reasons for using inline functions:
This is the problem inline functions were designed to solve, and a problem that can’t be solved by using interfaces and generics because there’s no way to specific constraints on operators without using member constraints (and therefore inline functions).
Take this simple add function for example:
without making it inline the parameters a and b will be inferred to be of type int, and there’s no way to make this function generic and usable with every numeric type (int32, int64, uint32, uint64, float, etc.). This is a prime example of when you should inline a function, doing so solves the aforementioned problem:
In some cases, it’s possible to get a performance improvement by making a function inline as it removes the jumps from call sites to the function’s location in memory.
Jon Harrop gave this example of how by making the following fold function inline it can run 5x faster:
As you can see, in my test, the inline version managed to run a whopping 8.5x faster!
This might just be too much temptation to those of us constantly seeking better performance from our apps, but it’s important to keep a couple of things in mind too:
- making a function or method inline does not always guarantee a performance improvement
- overuse can add significant bloat and makes your assembly bigger and takes longer to load, hence potentially impeding overall performance
- always measure/profile your app first, don’t prematurely optimize
Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.
Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.
Skill up your serverless game with this hands-on workshop.
My 4-week Production-Ready Serverless online workshop is back!
This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.
We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.
If you enrol now you can also get 15% OFF with the promo code “yanprs15”.
Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.
Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!
Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- All you need to know about caching for serverless applications
- Lambda optimization tip – enable HTTP keep-alive
- You are wrong about serverless and vendor lock-in
- You are thinking about serverless costs all wrong
- Just how expensive is the full AWS SDK?
- Check-list for going live with API Gateway and Lambda
- How to choose the right API Gateway auth method
- CloudFormation protip: use !Sub instead of !Join
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- Guys, we’re doing pagination wrong
- Top 10 Serverless framework best practices
- How to break the “senior engineer” career ceiling
- My advice to junior developers