Take-home coding exercises aren’t rare in interviews.
I’ve found from 4-hour exercises to 2-day exercises to a Pull Request in an open-source project.
Even though, in my CV I have links to my GitHub profile (with some green squares, not just cricket sounds) and my personal blog (the one you’re reading), I’ve had to finish take-home exercises.
Yes, hiring is broken!
For my last job, I had to solve a take-home challenge when applying as a C#/.NET backend software engineer. It was a decent company and I wanted to play the hiring game. So I accepted.
After I joined I was assigned to review applicants’ solutions.
Here are 13 short tips to help you solve your next take-home interview exercise. These are the same guidelines I used to review other people’s take-home exercises.
Stick to standards
Follow good practices and stick to coding standards. Write clean code.
1. Write descriptive names. Don’t use Information or Info as name suffixes, like AccountInfo. Keep names consistent all over your code. If you used AddAccount in one place, don’t use AccountAdd anywhere else.
2. Use one single “spoken” language. Write variables, functions, classes, and all other names in the same language. Don’t mix English and your native language if your native language isn’t English. Always prefer the language you will be using at the new place.
3. Don’t keep commented-out code. And don’t have extra blank lines. Use linters and extensions to keep your code tidy.
4. Use third-party libraries to solve common problems. But don’t keep unused libraries or NuGet packages around.
5. Have clearly separated responsibilities. Use separate classes, maybe Services and Repositories or Commands and Queries. But stay away from Helper and Utility classes full of static methods. Often, they mean you have wrong abstractions.
6. Add unit or integration tests, at least for the main parts of your solution.
If you’re new to unit testing or want to learn more, don’t miss my Unit Testing 101 series where I cover everything from the basics of unit testing to mocking and best practices.
Keep your solution under version control. Use Git.
7. Write small and incremental commits. Don’t just use a single commit with “Finished homework” as the message.
8. Write good commit messages. Don’t use “Uploading changes,” “more changes,” or anything along those lines.
9. Use GitHub, GitLab, or any hosting service, unless you have different instructions for your take-home exercise.
Write a good README file
Write a good README file for your solution. Don’t miss this one! Seriously!
10. Add installation instructions. Make it easy for reviewers to install and run your solution. Consider using Docker or deploying your solution to a free hosting provider.
11. Add instructions to run and test your solution. Maybe, some step-by-step instructions with screenshots or a Postman collection with the endpoints to hit. You get the idea!
12. Tell what third-party tools you used. Include what libraries, NuGet packages, or third-party APIs you used.
13. Document any major design choices. Did you choose any architectural patterns? Any storage layer? Tell why.
Voilà! These are my best tips to succeed at your next take-home interview challenge. Remember, it’s your time to shine. Write code as clean as possible and maintain consistency. Good luck!
If you want to see how I followed these tips on a real take-home coding exercise, check SignalChat on my GitHub account. It’s a simple browser-based chat application using ASP.NET Core and SignalR.
These days I got this exception message: “The transaction operation cannot be performed because there are pending requests working on this transaction.” This is how I fixed it after almost a whole day of Googling and debugging.
To fix the “pending requests” exception, make sure to properly await all asynchronous methods wrapped inside any database transaction.
The reservation process used two types of steps inside a pipeline: foreground and background steps.
The foreground steps ran to separate enough rooms for the reservation. And the background steps did everything else to fulfill the reservation but in background jobs.
If anything wrong happened while executing the foreground steps, the whole operation rollbacked. And there were no rooms set aside for the incoming reservation. To achieve this, every foreground step had a method to revert its own operation.
The code to revert the whole pipeline was wrapped inside a transaction. It looked something like this,
The Commit() method broke with the exception mentioned earlier. Arrrggg!
No displays or electronic devices were damaged while debugging this issue. Photo by Julia Joppien on Unsplash
Always await async methods
After Googling for a while, I found a couple of StackOverflow answers that mention to await all asynchronous methods. But, I thought it was a silly mistake and I started to look for something else more complicated.
After checking for a while, trying to isolate the problem, following one of my debugging tips, something like this code got all my attention.
Did you notice any asynchronous methods not being awaited? No? I didn’t for a while. Neither did my reviewers.
But, there it was. Unnoticed for the code analyzer too. And, for all the passing tests.
Oh, dear! var updatedByUserId = GetSystemUserAsync(context).Id. This line was the root of the issue. It was meant to log the user Id who performed an operation, not the Id of the Task not being awaited.
Voilà! In case you have to face this exception, take a deep breath and carefully look for any async methods not being awaited inside your transactions.
If you want to read more content, check my debugging tips. To learn to write unit tests, start reading Unit Testing 101. A better failing test would’ve caught this issue.
To read about C# async/await keywords, check my C# Definitive Guide. It contains good resources to be a fluent developer in C#.
Another Monday Links. Five articles I found interesting in last month.
Don’t waste time on heroic death marches
“Successful companies, whether they’re programming houses, retailers, law firms, whatever, make their employees’ needs a priority.” Totally agree. No more comments! Read full article
How to study effectively
One of my favorite subjects: how to study. Don’t cram. Don’t reread the material. Don’t highlight. Instead, study in short sessions and recall the material. Easy! There are even more strategies. Read full article
Undervalued Software Engineering Skills: Writing Well
We, as developers, spend a lot of time writing prose, not only code. Commit messages, ticket and PR descriptions, README files. We should get better at it. To check my writings, I use the Hemingway app often. Read full article
15 signs you joined the wrong company as a developer
Number 12. and 13. are BIG red flags. Let’s pay attention to those. Recently, I read about “disagree with your feet.” It resonates with this article. When you don’t like something about your job and you can’t do anything about it, walk away. Read full article
No, we won’t have a video call for that
I don’t like those chat messages with only “Hi!” or “How are you?” when we both know that’s not the message. This article shows how to better communicate on remote teams. Embrace asynchronous communication. Prefer (in order) Issue tracker, Wiki, email, and chat. Stay away from video calls as much as possible. Don’t ping people on chat software. And other ideas. Read full article, Watch full presentation.
Voilà! This Monday Links ended up being about better workplaces. See you in a month or two in the next Monday Links! In the meantime, grab your own copy of my free eBook Unit Testing 101. Don’t miss the previous Monday Links on Farmers, Incidents and Holmes.
Today, I needed to pass a dictionary between two ASP.NET Core 6.0 API sites. To my surprise, on the receiving side, I got the dictionary with all its keys converted to lowercase instead of PascalCase. I couldn’t find any element on the dictionary, even though the keys had the same names on each API site. This is what I learned about serializing dictionary keys.
Serialization with Newtonsoft.Json
It turns out that the two API sites were using Newtonsoft.Json for serialization. Both of them used the CamelCasePropertyNamesContractResolver when adding Newtonsoft.Json.
Something like this,
usingNewtonsoft.Json.Serialization;usingNewtonsoft.Json;varbuilder=WebApplication.CreateBuilder(args);builder.Services.AddControllers().AddNewtonsoftJson(options=>// ^^^^^{options.SerializerSettings.NullValueHandling=NullValueHandling.Ignore;options.SerializerSettings.ContractResolver=newCamelCasePropertyNamesContractResolver();// ^^^^^// This is what I mean});varapp=builder.Build();app.MapControllers();app.Run();
With CamelCasePropertyNamesContractResolver, Newtonsoft.Json writes property names in camelCase. But, Newtonsoft.Json treats dictionary keys like properties too.
That was the reason why I got my dictionary keys in lowercase. I used one-word names and Newtonsoft.Json made them camelCase.
To prove this, let’s create a simple controller that read and writes a dictionary. Let’s do this,
usingMicrosoft.AspNetCore.Mvc;namespaceLowerCaseDictionaryKeys.Controllers;[ApiController][Route("[controller]")]publicclassDictionaryController:ControllerBase{[HttpPost]publicMyViewModelPost(MyViewModelinput){returninput;// ^^^^^// Just return the same input}}publicclassMyViewModel{publicIDictionary<string,string>Dict{get;set;}}
Now, let’s notice in the output from Postman how the request and the response differ. The keys have a different case. Arggg!
Postman request and response bodies
1. Configure Newtonsoft.Json naming strategy
To preserve the case of dictionary keys with Newtonsoft.Json, configure the ContractResolver setting with CamelCaseNamingStrategy class and set its ProcessDictionaryKeys property to false.
When registering Newtonsoft.Json, in the SerializerSettings option, let’s do:
usingNewtonsoft.Json.Serialization;usingNewtonsoft.Json;varbuilder=WebApplication.CreateBuilder(args);builder.Services.AddControllers().AddNewtonsoftJson(options=>// ^^^^^{options.SerializerSettings.NullValueHandling=NullValueHandling.Ignore;options.SerializerSettings.ContractResolver=newCamelCasePropertyNamesContractResolver{NamingStrategy=newCamelCaseNamingStrategy{ProcessDictionaryKeys=false// ^^^^^// Do not change dictionary keys casing}};});varapp=builder.Build();app.MapControllers();app.Run();
After changing the naming strategy, let’s see the response of our sample controller. That’s what I wanted!
Postman request and response bodies
What about System.Text.Json?
To maintain case of dictionary keys with System.Text.Json, let’s set the DictionaryKeyPolicy property inside the JsonSerializerOptions to JsonNamingPolicy.CamelCase.
Another alternative is to use a dictionary with a comparer that ignores case of keys.
On the receiving API site, let’s add an empty constructor on the request view model to initialize the dictionary with a comparer to ignore cases.
In my case, I was passing a metadata dictionary between the two sites. I could use a StringComparer.OrdinalIgnoreCase to create a dictionary ignoring the case of keys.
This way, no matter the case of keys, I could find them when using the TryGetValue() method.
Voilà! That’s how we can configure the case of dictionary keys when serializing requests and how to read dictionaries with keys no matter the case of its keys.
We have covered some common mistakes when writing unit tests. Some of them may seem obvious. But, we all have made this mistake when we started to write unit tests. This is the most common mistake when writing unit tests and how to fix it.
Don’t repeat the logic under test when verifying the expected result of tests. Instead, use known, hard-coded, pre-calculated values.
Let’s write some tests for Stringie, a (fictional) library to manipulate strings with a fluent interface. Stringie has a Remove() method to remove substrings from the end of a string.
When writing unit tests, don’t copy the tested logic and paste it into private methods to use them inside assertions.
If we bring the tested logic to private methods in our tests, we will have code and bugs in two places. Duplication is the root of all evil. Even, inside our tests.
Please, don’t write assertions like the one in this test.
[TestMethod]publicvoidRemove_ASubstring_RemovesThatSubstringFromTheEnd(){stringstr="Hello, world!";stringtransformed=str.Remove("world!").From(The.End);Assert.AreEqual(RemoveFromEnd(str,"world!"),transformed);// ^^^^^// We duplicate the Remove logic in another method}privatestringRemoveFromEnd(stringstr,stringsubstring){varindex=str.IndexOf(substring);returnindex>=0?str.Remove(index,substring.Length):str;}
Also, by mistake, we expose the internals of the tested logic to use them in assertions. We make private methods public and static. Even to test those private methods directly.
From our Unit Testing 101, we learned to write unit tests through public methods. We should test the observable behavior of our tested code. A returned value, a thrown exception, or an external invocation.
Again, don’t write assertions like the one in this test.
[TestMethod]publicvoidRemove_ASubstring_RemovesThatSubstringFromTheEnd(){stringstr="Hello, world!";stringtransformed=str.Remove("world!").From(The.End);Assert.AreEqual(Stringie.PrivateMethodMadePublicAndStatic(str),transformed);// ^^^^^// An "internal" method exposed to our tests }
Use known values to Assert
Instead of duplicating the tested logic, by exposing internals or copy-pasting code into assertions, use a known expected value.
For our sample test, let’s simply use the expected substring "Hello,". Like this,
[TestMethod]publicvoidRemove_ASubstring_RemovesThatSubstringFromTheEnd(){stringstr="Hello, world!";stringtransformed=str.Remove("world!").From(The.End);Assert.AreEqual("Hello,",transformed);// ^^^^^^^^// Let's use a known value in our assertions}
If we end up using the same expected values, we can create constants for them. Like,
Voilà! That’s the most common mistake when writing unit tests. It seems silly! But often, we duplicate Math operations and string concatenations and it passes unnoticed. Remember, don’t put too much logic in your tests. Tests should be only assignments and method calls.
Want to write readable and maintainable unit tests in C#? Join my course Mastering C# Unit Testing with Real-world Examples on Udemy and learn unit testing best practices while refactoring real unit tests from my past projects. No more tests for a Calculator class.