Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent methods from being added to a class?

Tags:

c#

inheritance

I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).

Is there any way to achieve this?

like image 904
NickG Avatar asked Sep 18 '15 09:09

NickG


3 Answers

Use reflection and write a unit test that fails if a model-class has methods.

Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.

like image 64
Vilhelm H. Avatar answered Oct 12 '22 23:10

Vilhelm H.


I believe you are trying to solve a procedural issue with code where you should be using communication.

Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!

I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.

like image 38
Gusdor Avatar answered Oct 12 '22 23:10

Gusdor


You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.

However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.

like image 22
MakePeaceGreatAgain Avatar answered Oct 12 '22 23:10

MakePeaceGreatAgain