SP2101: Method body must not contain more than 120 code lines - How can I suppress this?

StackOverflow https://stackoverflow.com/questions/10109361

  •  30-05-2021
  •  | 
  •  

Domanda

I have a method that goes through loads of file types like so:

case ".jpg": 
    res = "image/jpeg"; 
    break;
case ".pdf": 
    res = "application/pdf"; 
    break;
case ".doc": 
    res = "application/msword"; 
    break;

..this goes on for a few hundred lines. And I have run into a StyleCop error: SP2101: Method body must not contain more than 120 code lines

I have searched around and can't find anything on this, let alone the suppression. Does anyone know how to suppress this message?

Edit: I think this is a StyleCop+ error and cannot be solved using the FxCop program to copy the suppression.

È stato utile?

Soluzione

I am the author of StyleCop+.

One of the rule it adds to original StyleCop functionality is indeed SP2101 (MethodMustNotContainMoreLinesThan) which checks the size of your method.

Like any other StyleCop warning, it could be:

  • disabled, in that case it means you just don't need it
  • suppressed for some particular place in code (when you still need it generally, but not here)

Moreover, it is configurable. If you want to use this rule, you can put any number instead of 120 for your own configuration. 120 is just some default.

The point of this rule is around maintainability. It could be very important to check that you don't fall into spaghetti code. StyleCop is just a tool giving you an ability to get control over that. StyleCop+ offers some more rules to check. So if you wish to use them - go ahead. If you don't - just disable it. It is kind of a tool that really needs to be configured before the usage.

Let me know if you need any help with configuration.

Altri suggerimenti

You could refactor this to a Dictionary<string,string>:

var mimeTypesPerFileType = new Dictionary<string,string>();
mimeTypesPerFileType.Add(".jpg", "image/jpeg");
mimeTypesPerFileType.Add(".pdf", "application/pdf");
...

That would cut the number of lines in the method by about a third (though this could be in a separate method/field so you don't need to repopulate the dictionary every time).

And the method then just changes to:

return mimeTypesPerFileType[fileType];

Update:

Seeing as you have around 400 odd cases (around 1300 lines in the method), you really should load this map from a file or database. This will certainly reduce the number of lines.

I don't use StyleCop, but one suggestion might be to change your approach. You could store all of these value pairs in an XML file, etc, and use a List(Of T) to organize them all. Your method could be reduced to a couple of lines.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top