Does editing an object within a function mean I need to return it back to update the value

Viewed 29

If I edit the data of an object in a function do I need to return the object back to update it in java.

Say I have something like this:


  public void foo1() {
    Foo foo = new Foo();
    someFunction(foo);
    // Is the state of foo changed here or not?
  }

  public void someFunction(Foo foo) {
    foo.doSomething();
  }

I know objects are passed by reference in java. Will this mean the object is updated/changed at the end of the foo1() function or not?

1 Answers

Does foo change? It's possible but it depends on what the method does.

Here's an example where foo does not change:

public class NoChange {
    public static void main(String[] args) {
        Foo foo = new Foo();
        foo.noChange();
    }
}

class Foo {
    private int n = 0;
    public void noChange() {
        System.out.println(n);
    }
}

If you run this code, the call to foo.noChange() will print out "0", and nothing in foo will change.

Here's a slight modification of that example which introduces a doChange() method on class Foo. The new method does change something in an instance of Foo – specifically, it takes the value of n and increments it by one.

public class YesChange {
    public static void main(String[] args) {
        Foo foo = new Foo();
        foo.doChange(); // increment n by one
        foo.noChange(); // print out n
    }
}

class Foo {
    private int n = 0;

    public void noChange() {
        System.out.println(n);
    }

    public void doChange() {
        n++;
    }
}

When you run that second example code – which first calls doChange(), then calls noChange() to print out current "n" – the output is "1".

So, the behavior depends on whether the method changes state (for example, by changing setting a value such as incrementing a number) or has side effects (the method might call some other method which in turn does change state). If the method does none of these things, it would be a "pure function".

Related