Skip to main content

Defensive Code

What is Defensive Code?

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.

Why you should use Defensive Code?

  1. Prevent Incorrect Entries 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:

  • Validating method arguments
  • Writing unit tests
  1. 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,
  • Adding checks (Checking network connectivity before saving)
  • Managing Exceptions

Defensive Code Best Practices

Better Reading for Future Developers Software applications are maintained by many developers during it’s life span. Therefore, it is important for the devs 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.

📝 Reading code is more difficult than writing code.

Logging and Monitoring: Implement logging and monitoring mechanisms to track errors and unexpected behavior in your application. This information is invaluable for debugging and improving software quality.

Unit Testing: Write unit tests that include edge cases and boundary conditions. This helps identify issues early in the development process and ensures that defensive code remains effective as the codebase evolves.

Code Reviews: Conduct code reviews to identify and address potential vulnerabilities and areas where defensive coding practices can be improved.

Documentation: Document and comment your code, especially the defensive measures you've implemented, to make it easier for other developers to understand and maintain the codebase.


Code Examples

Input Validation: Always validate user inputs and external data before using them in your program. Ensure that inputs are within expected ranges and formats to prevent unexpected behavior or security breaches.

if (inputString != null)
{
// Process inputString
}

Input Validation: Validate user inputs and external data to prevent security vulnerabilities and unexpected behavior.

if (string.IsNullOrWhiteSpace(userInput))
{
// Handles empty or whitespace input
}

Exception Handling: Handle exceptions gracefully by using try-catch blocks. Catch specific exceptions whenever possible to provide appropriate error messages and recover from failures gracefully.

try
{
// Code that may throw exceptions
}
catch (Exception ex)
{
// Handle the exception or log it
}

Null Checks: Avoid null reference exceptions by checking for null values before accessing objects or variables.

if (object != null)
{
// Access object safely
}

Defensive Copying: When dealing with mutable objects, consider making defensive copies to prevent unintended modifications.

var defensiveCopy = new List<int>(originalList);

Conclusion

Defensive coding is not just about handling errors; it's about building a robust and secure software foundation. By consistently applying these principles and techniques in your C# projects, you can minimize the chances of unexpected failures and enhance the overall quality and reliability of your software.