How do I comment / document an override in C #?

Sometimes I override methods in base classes. Sometimes I even override them with an empty method because I want to prevent the behavior.

In the past, I would write something like this to show the intent of the base method bypass:

protected override void OnMouseUp(MouseEventArgs e)
{
    // base.OnMouseUp(e);
}

      

(I know the commented line of code is a bad thing. I've done it)

But I want to do better:

  • How can I capture the intent of the override? :
  • What am I writing in an override XML document ( <summary>

    ?) ?
+3


source to share


3 answers


Comment like

// This method is intentionally blank because 
// we do not want the base class functionality

      

much better than



// base.SomeMethod();

      

The first comment clearly states why you did what you did, and the next developer that comes along won't have to wonder if a call to the base method was accidentally called.

If you have control over the base class, it might be better to remove this method and make the class more abstract. Then you can only choose to implement this functionality in child classes where needed.

+3


source


For documentation, I would just use the built-in documentation tags :

/// <summary>Exiting drag mode on mouse up</summary>
protected override void OnMouseUp(MouseEventArgs e)
{
    ...

      

To clarify the intent, I would just add a comment like

protected override void OnMouseUp(MouseEventArgs e)
{
    // not calling the base implementation
    ...
}

      



Line

// base.OnMouseUp(e);

      

it looks like the call is temporarily commented out (and maybe someone forgot to restore it)

+5


source


The base class invocation remark does, in my opinion, the exact opposite of making the intent clear. People will wonder why the commented line is still there, and if it might be useful because you didn't delete it. So I would remove the commented line.

You can document the override just like any other method and in the documentation, indicate exactly why you left the method empty. You could write the reason in the body of the method as a comment, and also I think it's a matter of preference.

I think it depends on whether this information is important to the developer maintaining the code as well as the user of the code (for example, users of your library). In the case of an event that is usually only raised by the operating system (like in your example), placing it in the summary tag is really not required.

However, if you need to override methods to disable base class behavior, you might want to revisit this part of your design. This behavior seems unintuitive to me.

+1


source







All Articles