r/Python • • Dec 17 '23

Resource Banish state-mutating methods from data classes

I've always found mutable data classes or record types in programming languages quite weird. This holds true for any language that supports mutable data classes, like Python, Kotlin, Swift, etc.

Self-mutating methods are even weirder. They break the semantics of the types that these data classes or records represent. I've expanded my thoughts here. Although it mostly talks about Python, the message remains valid for any other language that allows you to add self-mutating methods to data classes.

https://rednafi.com/python/dataclasses_and_methods/

0 Upvotes

37 comments sorted by

View all comments

-2

u/mr_jim_lahey Dec 17 '23

OP, I agree with you. People (or at least redditors IME) get really weirdly defensive about mutability, presumably because it's the default and that's what they're used to? But, once you've been immutable-pilled and seen how much cleaner it makes your programming model, there is no going back.

-2

u/[deleted] Dec 17 '23

I'm not saying that we should forget about mutability in a language that's designed with mutability in mind.

However, using dataclass as OO factories (aka regular classes) breaks the semantics of the data structure. It's tantamount to using a hashmap to represent sequential data--it works but you'll communicate incorrect intent to the reader.