I have been writing both Java and Python code for some time now. I have noticed, many times, that objects in both languages often have seemingly inconsistent ways to call their methods. Take these Python code snippets for example. (The syntax is not important, just note the way the methods work with the data)
class Foo(object):
def __init__(self, num = 0):
self.num = num
def __str__(self):
return str(self.num)
def addOne(self):
self.num += 1
if __name__ == "__main__":
foo = Foo()
print(foo) # Outputs 0
foo.addOne()
print(foo) # Outputs 1
Versus:
class Bar(object):
def __init__(self, num = 0):
self.num = num
def __str__(self):
return str(num)
def addOne(self):
return Bar(num + 1)
if __name__ == "__main__":
bar = Bar()
print(bar) # Outputs 0
bar.addOne()
print(bar) # Still Outputs 0
bar = bar.addOne()
print(bar) # Now Outputs 1
Both of these examples are very similar, but the Foo class, when you call Foo.addOne(), changes the num variable inside of the class. The Bar class, however, its addOne() method returns a new object with the num variable updated. Which situation is preferable at what times, what do people expect, and does this differ much in between languages?
Java has certain classes that are immutable. You (as a Java developer) can also create such classes. You cannot change the internal state of any object from an immutable class even if you want to (e.g. you cannot add 1 to an
Integer
object without creating a newInteger
object, and you cannot append "a" to a String object without creating a newString
object even if you want to).Now, if a class is not immutable, you're free to take both approaches (change the internal state of the existing instance, or create a new instance). But whichever approach you take, you should document it so that your callers know what to expect. That's how it works in the Java world at least, as far as I'm aware.