Good Code and Bad Code - Tips for Programmers

Referred Linkhttps://www.linkedin.com/feed/update/urn:li:activity:7229846743327096832


When it comes to writing good versus bad code in .NET, especially regarding validation (either form validation, business logic validation, or data validation), it’s important to adhere to best practices that enhance maintainability, readability, and performance of your code. Below are examples illustrating the differences between good and bad code in .NET, particularly focusing on a hypothetical Validator class.


Issues with the Bad Code:
Hard-coded error messages: Printing messages directly in the validation method makes it less reusable and inflexible.

Magic numbers and values: Age limits are hard-coded, making it less maintainable.

Single Responsibility Principle violation: This method handles validation and error reporting.

Lack of structured error handling: There’s no way to retrieve error messages in a meaningful way after the validation fails.

✔ Improvements in the Good Code:
Error Collection: Instead of printing errors, we collect and return them as a list. This allows the calling method to decide how to handle the errors (e.g., logging, displaying them to a user).

Use of string.IsNullOrWhiteSpace: This is a more robust method to check for null or empty strings.

Encapsulation of logic: The validation logic is kept modular, which adheres to the Single Responsibility Principle.

Ease of testing: The return type allows easier unit testing by verifying returned errors for given inputs.

💡 Additional Best Practices for Validation in .NET:
🔦 Data Annotations: Utilize built-in data annotations (e.g., [Required], [EmailAddress], etc.) to leverage built-in validation features.

🔎 Fluent Validation: Consider using libraries like FluentValidation to create more complex validation rules in a fluent interface.

🕯 Separation of Concerns: Separate your validation logic from business logic. Consider using a dedicated service or function for validations.

🌠 Asynchronous Validation: If validation includes I/O operations (like checking email availability), consider making your validation methods asynchronous.

⭐ Custom Exceptions: Instead of returning a list of strings for validation errors, consider throwing custom exceptions that can carry context about what went wrong.

By adhering to these practices, you can ensure that your validation logic remains efficient, maintainable, and easy to understand.

Tags:

You May Also Like

0 comments