Importance of writing defensive code in C#

Gangesh r
4 min readApr 17, 2021

Defensive coding is a set of programming guidelines which aids developers to improve their code quality, code comprehension and code predictability. Following these guidelines will not only allow software applications to behave as expected despite of incorrect inputs but it also makes code readability much easier for future developers.
This article was written with the key objective of highlighting the importance of these guidelines for new developers who are in the early stages of their career so that they could keep these techniques in mind while writing code and adapt to these practices.

Reasons to write defensive code

1) Prevent Incorrect Entry

For an application to produce correct results it needs to be provided with correct data. To ensure the accuracy of the given data, we protect our code by adding validations which will ensure that the given inputs meet a set of standards before being passed on to the application logic.
Eg: Validating the name field of an user registration form to ensure that it contains certain length and does not contain any numbers or empty values.

2) Prevent Invalid operations

Protecting code segments from performing invalid operations.
Eg: division by zero
The following 2 approaches can be followed to avoid performing invalid operations:
a) Validating method arguments
b) Writing unit tests

3) Prevent System Mishaps

Application failures which are caused by certain factors that are out of the scope of the application’s control.
Eg: Losing network connectivity when saving data or failures due to hardware malfunction.
Such scenarios can be handled by,
a) Adding checks (Checking network connectivity before saving)
b) Managing Exceptions

4) Future Developers

Reading code is difficult than writing code.

Software applications are maintained by many developers during it’s life span. Therefore, it is important for developers to write clean code which could be understood by future developers and prevents them from making incorrect assumptions and push changes which can cause an application to fail.

When reading code our brain acts as the complier to understand what the code actually does. For the reader to understand the code easily, make sure to write code with the following characteristics.
a) Terse: Code should not be excessively wordy.
b) Expressive: The intent of the code should be clear.
c) Does one thing
d) Self documenting(Favor code over comments)

Facts to consider when writing defensive code

1) Code Comprehension

Following are some of the characteristics of good code comprehension,

  1. Easy to read - code which is easy to read is easier to understand and well formatted. It has clear names and reasonable size classes and methods.
  2. Have a clear intent - Each piece of code should have one clear purpose.
  3. Simple - complex code is hard to maintain and can introduce bugs.
  4. Thoughtful - writing code which is easier to read, understand and maintain over time.

Ways to improve Code Comprehension…

Single Responsibility
Single responsibility(The first concept of SOLID principles) principle suggests that developers write code as a set of single focused methods each with a single responsibility.
This makes code easier to read and understand.

Separation of Concerns
Separating an application into distinct parts where each part addresses a specific aspect of the application.
Eg: Organizing the application into separate layers such as Presentation Layer, Service Layer and Data Layer or using the MVC(Model-View-Controller) Architecture.

DRY Principle
DRY or “Do not Repeat Yourself” principle suggests developers to minimize repeating code and to reuse code.

2) Code Quality

Code quality measures how an application is coded, how it meets its requirements and how well the application works.

The following 3 techniques can be followed to improve code quality,

a) Code reviews: Code reviews are performed by well experienced professional developers examining the source code to ensure that the code meets certain standards and follows best practices. (Eg: Aligns well with SOLID, OOP and DRY principles)

b) Code execution: Running the code to ensure that it executes appropriately and meets it’s requirement.

c) Unit Testing: Automating the execution of our code to ensure that it performs as expected for multiple scenarios and to test the state of the defenses of our code.

3) Code predictability

Code predictability means that the application behaves as intended.
Code predictability can be improved by,
a) Handling incorrect inputs.
b)
Handling scenarios if a business rule is broken.
c)
Handling invalid operations.
d)
Handling events when something goes wrong.

Conclusion

The source code of software applications are well organized and maintained at the initial stages of it’s life cycle. But in the long run, since the application is maintained by many developers, the code tends to become more complex and sloppy which ultimately makes it difficult for developers to read and understand. When code becomes difficult to understand it introduces technical debts which may require more time and effort to be resolved.

As developers, if we could make it a practice to write clean code it will be possible to prevent our code from becoming more complex which gives us the ability to easily adapt to new change of requirements. By doing so, development becomes more efficient and ultimately it will be beneficial to our business as a whole.

References

  1. https://app.pluralsight.com/library/courses/csharp-defensive-coding/table-of-contents
  2. https://app.pluralsight.com/library/courses/csharp-clean-coding-principles/table-of-contents

--

--