views:

273

answers:

5

I usually save serialized structs to my database, so I pass them by reference a lot!

Is that a bad practice?

+3  A: 

Well, sometimes passing anything by reference a lot can be a code smell, indicating the need for member variables or method refactoring. But you also might want to consider why these are structs. Are you only passing them by reference to get around the fact that structs are value copied? If so you might want to make them a class instead. Unless it's a struct that you didn't define. Maybe more information will be useful?

Tesserex
+9  A: 

What do these structs look like in the first place? If you find you're passing them by reference a lot, why are they structs? It's generally worth "defaulting" to creating classes rather than structs... I find it's very rare that I create my own structs. (Outside Noda Time, I can't remember writing more than one or two.)

The fact that you're using ref a lot is at least suggestive that classes would be a better fit. If you could give us a concrete example, that would definitely help.

Jon Skeet
A: 

Well, the funny thing is it's probably bad, but I would have quite likely done the same thing.

Joshua
+2  A: 

Serializing structures into a database table column is very definitely a bad practice. Only your code could ever read them back reliably. And you'll have a huge problem when requirements change and you need to add a field to the structure, you'll need to re-create all the data, the dbase engine cannot help you.

Passing these structures by reference is likely to be the correct thing to do. Surely they are larger than 16 bytes (~4 fields), beyond which passing by value starts to get (relatively) expensive. Not that you'd ever notice, the cost of updating the dbase is orders of magnitude larger than the cost of copying structures.

Hans Passant
@nobugz: what if he serializes to XML using the DataContractSerializer, which can support content being added later.
John Saunders
A: 

Serializing struct to db field make very difficult to: add new field to struct, read that data from another application, filtering on structure data by database engine (using in where clause), make foreign key on another table point to structure filed, make database constraints on structure fields, ....

In short that way database doesn't know anything about that structure and that means it can't help you when dealing with it.

Petar Repac