I am preparing to share knowledge I learned at WWDC with my company in general. I just got done watching "Building Better Apps with Value Types in Swift” and said to myself that I don't remember ever getting in trouble with state like that. However, we're not writing frameworks for others. We don't have an intense model.
In what situations should we be careful to make sure we are using struct and other value types?
Find video at http://apple.com/wwdcand click on “Videos”
I can safely say that most bugs in software having something to do with state changing in unexpected ways. Just two examples that come right up to me:
- Multithreading is hard because you have to make sure that changes in state in one thread are handled correctly in another thread. (But that's just one reason why parallellisation is hard.)
- Object-oriented programming became popular because it encapsulates state in objects (among other paradigms).
If you've ever programmed in Haskell, you'll recognise this: when you develop in Haskell, you typically fight the compiler with its strong type system. Once the Haskell code compiles, it almost always does what you wanted.
Sadly, immutability can't be applied everywhere. But always try. ;-)
This is my personal rule: use value types everywhere except when instances must have identity (e.g., views in a view hierarchy, nodes in a graph, entities in an object graph …).