How to comment/document an override in C#?

梦想的初衷 提交于 2019-12-23 18:28:38

问题


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

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

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

(I know a commented line of code is a bad thing. I used to do it)

But I want to do better:

  • How do I document the intention of the override? specifically:
  • What do I write in the override's XML (<summary>?) documentation?

回答1:


A comment like

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

is much better than

// base.SomeMethod();

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

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




回答2:


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)
{
    ...

For clarifying the intention I would just put a comment like

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

The line

// base.OnMouseUp(e);

makes an impression that the call is commented out temporarily (and perhaps someone forgot to restore it back)




回答3:


Commenting out the base class call does, in my opinion the exact opposite of making intent clear. People will wonder why the commented line is still there, and whether it might still be of some use because you didn't delete it. So i would remove the commented out line.

You could document the override just like any other method and in the documentation, specify why exactly you left the method empty. You could write the reason into the method body as comment as well, i guess that's a matter of preference.

I think it depends on whether this information is only important for the developer maintaining the code or also for the user of the code (e.g. users of your library). In the case of an event that usually gets called by the operating system only (like in your example), putting it in the summary tag wouldn't really be necessary.

Still, if you need to override methods to disable behavior of the base class, maybe you should reconsider that part of your design. That behavior seems a bit unintuitive to me.



来源:https://stackoverflow.com/questions/9915419/how-to-comment-document-an-override-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!