Top 3 Mistakes I See in .NET Codebases
I often work with and talk to developers in different companies and development teams.
Today, I want to talk about the mistakes I see on many .NET code bases and how to fix those mistakes. You may have one (or more) of those mistakes in your code base.
Poor Async Handling
The async/await pattern introduced in C# opened up the doors for writing efficient asynchronous code with ease. However, it has to be done correctly.
Make sure to use Task instead of void as the return type for your methods. Otherwise, the caller cannot wait for the method’s execution (await keyword).
Also, while APIs and other remote code execution should always be done asynchronously, there are situations where synchronous code is preferable.
For example, when updating the user interface of your desktop application, you might not need three levels of async/await.
Tight Coupling/Missing Dependency Injection
C# and .NET make heavy use of dependency injection. I often see people overusing or underusing dependency injection.
Tight coupling makes your applications hard to maintain while creating a 7-level-deep DI hierarchy, which results in the same mess.
Define clear interfaces and implement services that can be combined to perform the tasks needed. Don’t lose yourself in dependency hell.
Bad Exception Handling
Exception Handling is another important topic. Libraries, such as Polly, provide you with a simple interface to retry HTTP requests that have failed.
Make sure to use the try-catch pattern to provide the user with a meaningful error message, and make sure the application remains in a safe state in case an exception occurs.
Bonus: Missing/Wrong Log Statements
Another important topic is log statements. Especially (but not only in) web development. How often does a user say something went wrong, and you don’t know why?
Proper log statements will help you fix bugs and understand what really happens to your software during execution.
A proper log statement clearly communicates the state the application is in and the operation that has been performed by the user.
For logging in .NET applications, I highly recommend Serilog.