Alternatives for Common Anti-Patterns
Alternatives for Common Anti-Patterns
12 January 2022
Anti-patterns have a negative impact on the maintainability of a software systems. These are nothing but a poor solution to recurring design problem and generally occurs when developers unknowingly introduce them while designing and implementing the features to the product.
So in this blog we will try to replace the negative aspects of the anti-pattern with something that will give a positive outcome.
Using FirstOrDefault and Any
Try avoiding to call Any() or Count > 0 before foreach() such as in the following code:
Prefer IEnumerable<>.Any to List<>.Exists
When manipulating IEnumerable, prefer to use Any() instead of ToList().Exists(). Check out the following code:
Becomes:
Prefer Any() over Count() while checking for empty
The iteration on the sequence stops as soon as the condition (if any) is fulfilled without allocating any temporary list therefore any extension methods should be preferred to count computation on IEnumerable.
Becomes:
Using Throw Ex
While planning to play with catch and re-throw an exception, then using throw ex will not preserve the exception call stack and that can be a big blunder. So this can be avoided by using simple throw syntax to preserve the exception call stack.
Becomes:
USING T CASTING
Generally casting has a negative impact because casted objects can be easily castable so to protect casted objects from turning into castable following use as for casting given as follows.
Becomes: