Rock Your Code - Defensive Programming For Microsoft .NET By David McCarter

Talking about Defensive Programming during times of Test Driven Development, Clean Code, Domain Driven Development and other buzzwords seems a bit unusual. From his many years of experience, David McCarter shares a collection of rules of thumb to write better, rock-solid code. The book is part of his conference series titled Improving Code Quality... One Developer at A Time.

Back in 2017 I met David at the C# Corner conference in Delhi, India. While I gave a session on .NET Core on Linux, he had several sessions on how to be successful as a software developer and how to improve programming skills by sharing his experience as a programmer for over two decades.

His series Improving Code Quality... One Developer at A Time was already in full swing and the review of his book on Defensive Programming is a milestone on this journey.

The targeted audience of the title are .NET developers with a little to a few years of experience. The major focus is on how to write code that avoids causing exceptions. And in case an exception happens, how to deal with it depending on the application layer where it occurs. Lastly, David writes about techniques to log exceptions in .NET Core.

Stop exceptions before they happen.

Of course, the best way to deal with an exception is not to cause an exception. And that's how defensive programming adds value to your code base. Use the existing features of .NET and .NET Core to check the state of objects, properties and parameters before using them further.

Typically, one would always check an object or property for null. If you're working with file system operations check whether a file really exists before accessing it. Treat all incoming parameters and data as incomplete or damaging to your program execution. If the state of an object or property does not match the expected situation stop any further execution and return back to the caller. Stay on the positive path. ...

Lastly, David gives a few tips on how to deal with exceptions that are still occurring including the ones that our code might actually throw given incorrect state evaluation. The .NET Framework has several options on where to catch such exceptions, including the option to implement a "catch-all" exception handler that won't miss a single beat.

The book has 42 pages in total and is relatively short in regards to the topic overall. Given the length of Rock Your Code - Defensive Programming it is a good fit for a couple of lunch breaks, one or two commute units or a dedicated Friday afternoon learning session. Some information might be too obvious to an experienced .NET developer but surely it's a good resource for junior developers to get on the right track of writing better source code from the very beginning.