In the first part, “static methods do not mutate,” which are widely used in OOP. I have not heard this expressed explicitly. But common sense: "If you are changing an object, why a static method, if it can be an instance method?" Therefore, I completely agree that "static methods do not mutate."
The second part is "instance methods [mutate]", which are actually not as widely used. It rather depends on whether you decide that your project applies immutability or variability. Examples from the Java API: java.lang.String
immutable, java.util.Date
is mutable (most likely by accident / poor design), java.lang.StringBuilder
intentionally changes (which is its purpose). Mutability can lead to defensive cloning to protect code from mutational errors. Whether this is really a problem depends on several things:
- Will another API be used? You never know how they will use your code ... IMO, it is more important to protect the API code from mutational errors than regular code.
- How well is unit test covered? Can your units check for all mutation errors that can penetrate? If you are following TDD correctly (Uncle Bob 3 TDD Laws) and this is a non-API code, mutation errors are unlikely to penetrate without immediate detection.
- If you have code that needs to protect itself against mutation errors using protective cloning, how often is this code called? If defensive clones are created frequently, it may be better to use immutable objects than mutable objects. This is basically a call to the number of calls to read-only methods (which will ultimately be protected) to map classes compared to the number of calls to mutator methods in the class itself.
Personally, I prefer immutable objects, I'm a fan of final
(if I could change Java, I would make final
default value for all fields and variables and enter the var
keyword to make them non-final), and I try to do functional programming in Java, although it is not a functional programming language, as far as possible. In my experience, I know that I spend significantly less time debugging my code than others (in fact, I run the Java debugger, maybe twice a year). I don’t have enough empirical data and the right analysis to create any “causal relationships” between experience, immutability, functional programming and correctness, so I’ll just say that I believe that immutability and functional programming help in the correctness, and you have to come up with own judgment about it.
Finishing the second part, “instance methods make [mutate]” - a widely used assumption in case the object is changed anyway, otherwise the instance methods will be cloned.
source share