Thursday, April 13, 2006

What is wrong with visible instance fields?

FxCop rocks, in a kind of hectoring school teacher kind of way. It complains about loads of things that are only relevant if you happen to be developing a class library that will be used by 3 million developers using every conceivable .NET language and in every human language known to man. But us mere mortals are mainly developing code that might get dumped onto one web server if we're lucky. But FxCop still helps out on stupid things like code that never gets called and visible instance fields. Except, what's wrong with visible instance fields? OK, making fields public that users of your class never need to access is pretty dumb, but how does a public field differ from a property with simple getters and setters? The FxCop help says "the code in a property's accessors can change as the type's features expand without introducing breaking changes." But if I need to change a public field to a property, how will this cause a breaking change? Fields and properties are used in exactly the same way by client code. The only explanation I can think of is that it may cause serialization code to break, but serialization code breaks all the time anyway so that doesn't seem particularly relevant. Saying all that, I'm still going to continue to use properties, if only to stop FxCop complaining.

1 comment:

David M. Kean said...

Changing a field to a property is a breaking change.

Although consumers (that use VB and C#) that recompile their code when you make a change like this won't be affected, those that don't recompile and simply deploy your updated binary, will be.