Having pairs of static and instanced methods that perform the same tasks?

instance, java, methods, refactoring, static

Solution

I think your concept of providing both static/immutable and instance/mutable methods is a good one. I think the distinction is easy to explain and will be easy for the API users to understand and remember.

I think your API implementation code will not have redundant business logic. You will find that that you repeat a pattern where the static implementation creates a new instance and calls the instance method on that new instance.

Given that I am lazy, I would look at building a bit of infrastructure that would auto-generate the static methods, their javadoc and their unit tests at compile-time. This would be overkill if you have 10 methods, but becomes a big win if you have 1,000 methods.

Problem

While developing a two-dimensional vector class as part of a math library, I'm considering having static and instance method pairs for stylistic and usability reasons. That is, two equivalent functions but one is static & non-mutating, and the other is instanced & mutating. I know I'm not the first person to consider this problem (See here, for example) but I haven't found any information that directly addresses it. Pros of having static and instance method pairs: - Some people prefer to use one or the other and in some cases being able to choose makes code easier to read. It is implied that static methods are not mutating when both static and instanced methods are provided. This can make the calling code much clearer, e.g.: ``` someVector = Vector2d.add(vec1, vec2); someVector = (new Vector2d(vec1)).add(vec2); // does the same thing although more convoluted. // similarly adding directly to a vector is simpler with a mutator method. someVector.add(vec2); someVector = Vector2d.add(someVector, vec2); ``` This is especially important when long chains of function calls are used, which is common with vectors. In-place operations can be faster computationally than creating a new instance for every operation. The user decides when performance is important. For users of a Vector class, performance may be important as vectors are frequently used in computationally expensive code. Pros of having only static or instance methods, but not both: No significant code redundancy. Easier to maintain. Less bloat. The javadocs will be almost half the size. Not necessary to inform users that static methods never mutate and non-getter instanced methods always mutate. How frowned upon is having static/instance method pairs? Is it used in any major libraries? Is the pattern "static methods don't mutate, instance methods do" widely known?

Original source