I have a class that started life being mutable, but I've since made it immutable. Should I change it to be a struct
? What sort of considerations go into choosing one over the other? My particular case is a Point
type class (it represents a coordinate in a custom coordinate system) that is made up of 4 int
fields, plus a few properties to access the same data in different ways. I note that String
is a class and is immutable, so there must be some use-case for this.
Generally, no, you should not change it to a struct. Just because it's immutable doesn't mean that it's automatically a good candidate for being a struct.
A struct should be small. With your four ints it's just at the recommended limit of 16 bytes where performance for structs starts to degrade.
A struct should represent a single entity of some kind. Perhaps your class does that, but from your description it doesn't sound likely.
A structure is harder to implement correctly than a class. It should behave well to things like comparisons, so there are more things to implement than what is expected of a class.
Unless you have a really good reason to implement it as a struct, like performance issues, you should keep your class as a class.
As I understand, using a struct instead of a class is a matter of optimization. Structs are stored on the stack rather than the heap, so they are well suited as lightweight bundles of multiple fields that are used in great quantity. They are copied whenever passed between methods, which makes passing them more expensive - however this may lend itself to your desire for immutability. Disadvantages of using structs include the natural restrictions imposed by the language.
I'm not at all an expert on the subject but wanted to bring this aspect up. Someone with more experience should certainly step in and expand on this. Also, here is a useful discussion on it: When to use struct?
Ultimately I would say if immutability is your only consideration, keep it a class (especially now that I see others voicing this opinion). Immutability can be achieved regardless of being a struct, so the matter doesn't seem strongly related.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With