Structs are Better?

“Going to the big class hierarchy is again, you write more code than you need to, and you get too much connection between different parts. I particularly dislike classes with a lot of get and set functions. That is often an indication that it shouldn't have been a class in the first place. It's just a data structure. And if it really is a data structure, make it a data structure.” [1]

Now, this is something I have been thinking about a bit lately. I know the OO school of thought tells us that we should always hide fields behind properties, but there are cases when it is just so much easier to bypass the properties. Mainly, this seems to be with classes that aren't really pieces of my code, they are (de)serialization intermediates. For example, classes that map to xml serialized configuration files. Or how about classes used to exchange messages via a webservice which, by definition, don't really contain logic anyway. Part of me says, just leave the fields in there, but then another part of me says, what if I wanted to add validation logic to my message class' properties (even if it is automatically generated by VS.NET to check required values according to the XSD or something)? I expect this debate will only get hotter as SOA and xml serialization become more common topics.

[1] The C++ Style Sweet Spot. Stroustrup, Bjarne. http://www.artima.com/intv/goldilocks2.html

4 Comments

  • I've also been trying to grasp proper OO design methods. Structs vs classes, etc.

  • From a less philosophical and more practical perspective, I tend to prefer properties in .NET because of the framework's generally poor support for databinding to fields. That's one of the reasons that I dislike WSDL.EXE's field-base web service proxies (so much that I've actually written a replacement that generates properties instead).



    Truth be told, I've never even tried data binding to a struct.



  • the problem with a "bare nekkid struct" is that you have to then be 100% sure that every access to that struct only writes valid data.



    so how many times do you want to check that? in how many files?



    do you then ship a .dll that does this for third party callers? or do you trust them?



    IMHO build a class / type and use the rule:



    do not trust input, assume it's evil and trying to hose your code.



    then we can stop having buffer overwrites and other simple but dangerours hacks and bugs.

  • i can make member functions in struct, is it true?

Comments have been disabled for this content.