Method, Delegate and Event Anti-Patterns in C#
No enterprise application exists without a method, event, delegate and every developer would have written methods in his/her application. While defining these methods/delegates/events, we follow a standard definitions. Apart from these definitions there are some best practices that one should follow to ensure that method does not leave any object references, other methods are called in appropriate way, arguments to parameters are validated and many more.
This article outlines some of the anti-patterns while using Method, Delegate and Event and in-effect highlights the best practices to be followed to get the best performance of your application and have a very low memory footprint.
The right disposal of objects
We have seen multiple demonstrations that implementing IDisposable interface (in class BaseClass) and wrapping its object instance in ‘using’ block is sufficient to have a good clean-up process. While this is true in most of the cases, this approach does not guarantee that derived classes (let’s say DerivedClass) will have the same clean-up behaviour as that of the base class.
To ensure that all derived classes take responsibility of cleaning up their resources, it is advisable to add an additional virtual method in the BaseClass that is overridden in the DerivedClass and cleanup is done appropriately. One such implementation would look like,
- public class BaseClass : IDisposable
- {
- protected virtual void Dispose(bool requiresDispose)
- {
- if (requiresDispose)
- {
- // dispose the objects
- }
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- ~BaseClass()
- {
- Dispose(false);
- }
- }
- public class DerivedClass: BaseClass
- {
- // some members here
- protected override void Dispose(bool requiresDispose)
- {
- // Dispose derived class members
- base.Dispose(requiresDispose);
- }
- }
This implementation assures that the object is not stuck in finalizer queue when the object is wrapped in ‘using’ block and members of both BaseClass and DerivedClass are freed from the memory
The return value of a method can cause a leak
While most of our focus is on freeing the resources used inside the method, it is the return value of the method that also occupies memory space. If you are returning an object, the memory space occupied (but not used) is large
Let’s see some bad piece of code that can leave some unwanted objects in memory.
- public void MethodWhoseReturnValueIsNotUsed(string input)
- {
- if (!string.IsNullOrEmpty(input))
- {
- // value is not used any where
- input.Replace(" ", "_");
- // another example
- new MethodAntiPatterns();
- }
- }
Most of the string methods like Replace, Trim (and its variants), Remove, IndexOf and alike return a ‘new’ string value instead of manipulating the ‘input’ string. Even if the output of these methods is not used, CLR will create a variable and store it in memory. Another similar example is creation of an object that is never used (ref: MethodAntiPattern object in the example)
Virtual methods in constructor can cause issues
The heading speaks for itself. When calling virtual methods from constructor of ABaseClass, you can not guarantee that the ADerivedClass would have been instantiated.
- public partial class ABaseClass
- {
- protected bool init = false;
- public ABaseClass()
- {
- Console.WriteLine(".ctor - base");
- DoWork();
- }
- protected virtual void DoWork()
- {
- Console.WriteLine("dowork - base >> "
- + init);
- }
- }
- public partial class ADerivedClass: ABaseClass
- {
- public ADerivedClass()
- {
- Console.WriteLine(".ctor - derived");
- init = true;
- }
- protected override void DoWork()
- {
- Console.WriteLine("dowork - derived >> "
- + init);
- base.DoWork();
- }
- }
Use SecurityCritical attribute for code that requires elevated privileges
Accessing of critical code from a non-critical block is not a good practice.
Mark methods and delegates that require elevated privileges with SecurityCritical attribute and ensure that only the right (with elevated privileges) code can call those methods or delegates
- [SecurityCritical]
- public delegate void CriticalDelegate();
- public class DelegateAntiPattern
- {
- public void Experiment()
- {
- CriticalDelegate critical = new CriticalDelegate(CriticalMethod);
- // Should not call a non-critical method or vice-versa
- CriticalDelegate nonCritical = new CriticalDelegate(NonCriticalMethod);
- }
- // Should not be called from non-critical delegate
- [SecurityCritical]
- private void CriticalMethod() {}
- private void NonCriticalMethod() { }
- }
Override GetHashCode when using overriding Equals method
When you are overriding the Equals method to do object comparisons, you would typically choose one or more (mandatory) fields to check if 2 objects are same. So your Equal method would look like,
- public class User
- {
- public string Name { get; set; }
- public int Id { get; set; }
- //optional for comparison
- public string PhoneNumber { get; set; }
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- var input = obj as User;
- return input != null &&
- (input.Name == Name && input.Id == Id);
- }
- }
Now this approach checks if all mandatory field values are same. This looks good in an example for demonstration, but when you are dealing with business entities this method becomes an anti-pattern. The best approach for such comparisons would be to rely on GetHashCode to find out if the object references are the same
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- var input = obj as User;
- return input == this;
- }
- public override int GetHashCode()
- {
- unchecked
- {
- // 17 and 23 are combinations for XOR
- // this algorithm is used in C# compiler
- // for anonymous types
- int hash = 17;
- hash = hash * 23 + Name.GetHashCode();
- hash = hash * 23 + Id.GetHashCode();
- return hash;
- }
- }
You can use any hashing algorithm here to compute a hash of an object. In this case, comparisons happen between computed hash of objects (int values) which will be more accurate, faster and scalable when you are adding new properties for comparison.
Detach the events when not in use
Is it necessary to remove event handler explicitly in C#? Yes if you are looking for lower memory footprint of your application. Leaving the events subscribed is an anti-pattern.
Let’s understand the reason by an example
- public class Publisher
- {
- public event EventHandler Completed;
- public void Process()
- {
- // do something
- if (Completed != null)
- {
- Completed(this, EventArgs.Empty);
- }
- }
- }
- public class Subscriber
- {
- public void Handler(object sender, EventArgs args) { }
- }
Now we will attach the Completed event of Published to Handler method of Subscriber to understand the clean up.
- Publisher pub = new Publisher();
- Subscriber sub = new Subscriber();
- pub.Completed += sub.Handler;
- // this will invoke the event
- pub.Process();
- // frees up the event & references
- pub.Completed -= sub.Handler;
- // will not invoke the event
- pub.Process();
- // frees up the memory
- pub = null; sub = null;
After the Process method has been executed the Handler method would have got the execution flow and completed the processing. However, the event is still live and so are its references. If you again call Process method, the Handler method will be invoked. Now when we unsubscribe (-=) the Handler method, the event association and its references are freed up from the memory but objects pub and sub are not freed yet. When pub and sub objects are assigned null, they are marked for collection by GC.
If we do not unsubscribe (-=) and keep other code AS-IS – GC will check for any live references for pub and sub and it will find a live event. It will not collect these objects and they will cause a memory leak. This common anti-pattern is more prevalent in UI based solutions where the UI events are attached/hooked to code-behind / view-models / facade.
Following these practices will definitely reduce your application’s footprint and make it faster.