-->

Prevent other developers using base methods within

2019-06-17 07:20发布

问题:

I have a class that uses filesystem entities to manipulate data. We have several methods specifically designed to (attempt to) cope with some of the issues we face with this approach (file locking, non-existent files, etc.). Ideally I'd like to be able to issue a warning if another developer attempts access the filesystem directly via System.IO rather than using the helper methods.

Is this possible? The behaviour I'm looking for is to effectively mark methods such as File.ReadAllText() as if they were obsolete, but only within this project (NOT solution-wide).

I've done some digging around, and it looks like my only option is "tell them to make sure they use your methods". I'm hoping someone can give me a different, and more helpful answer. :)

--EDIT-- The suggestions of a custom StyleCop or FxCop rule are good, but unfortunately impractical in this scenario (not every developer in the department uses these excellent tools), and the legitimate methods that do the file access do use System.IO. Adding "ignore" attributes to the legit methods is a dangerous idea, too. If someone sees how I've "broken" my own rule, they'll likely copy the attribute to their own method.

回答1:

Use a static analysis tool (such as StyleCop or FxCop) with a rule that captures "Do not use System.IO directly." Then integrate it as part of your automated build process and throw up if someone does try to use System.IO directly. No one likes to break the build.



回答2:

You can write custom analysis rule for FxCop/Visual Studio Code Analysis and run these as part of your automated build.



回答3:

Hmm. Not tried this myself, but how about forcing people to use your custom file handling classes, by using a namespace alias that "hides" the genuine System.IO. If I remember rightly these are applied at a project level.



回答4:

Not sure if either of these suggestions are valid as I've never done them, but some food for thought:

Isn't this what "Enterprise Templates" are designed for? Don't they allow you to craft a policy file that restricts the allowed project references?

Alternatively, while not foolproof, could you add a pre-build event to the project that throws a warning if System.IO is referenced?



回答5:

Can you add some custom functionality to a source-control commit hook? It won't find existing violations (if there are any) unless those files are changed but should detect new uses?

Any good?