Mutability selection when coding

When should something be mutable/immutable? Learning to code (first language) and I'm not sure when it be beneficial to have mutability vs leaving something immutable. Thanks and sorry for the noobish question.

You will need to be way more specific than that. In general, something should be mutable if you need to mutate it. Otherwise, it should be immutable because immutability is easier to reason about in general.

1 Like

Sorry for lack of specifics, still learning. How should I identify if something needs to be mutable I guess would be a better question?

Edit: Trying to get this out of the way now because I want to learn "best practices" while I'm learning when possible.

That depends entirely on the specific situation, use case, algorithm, etc. I don't believe it is possible to answer this question in general. One can cite examples, but compiling an exhaustive list is certainly not reasonable. You might want to build up a data structure incrementally, for example, or change some state that is reflected in the UI. There is a vast amount of possibilities.

That is almost certainly not how learning works. You can't learn best practices upfront, before knowing the fundamentals. Best practices will be accumulated over time, they come with experience.

I suggest that you learn by writing some code. Just start coding. Once you are stuck, or if you believe you have got a correct solution, you can post your code here. You can be sure people will inform you of best practices and they will help you improve your code in specific cases.


By default make everything immutable. When you realize you want to mutate something, change it -- at that point you will know why it needs to be mutable.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.