JDoeDoe
JDoeDoe

Reputation: 371

Same result with methods of type void and int, which to use?

I have the following main class:

public class Test {

    public static void main(String[] arg) {
        Counter counter1;
        Counter counter2;
        counter1 = new Counter();
        counter2 = new Counter();

        counter1.increment();
        counter2.increment();
        counter2.increment();

        System.out.println(counter1.getValue());
        System.out.println(counter2.getValue());
    }
}

And the class Counter:

public class Counter {

    private int count;

    public Counter() {
       count = 0;
    }

    public void increment() {
        count++;
    }

    public int getValue() {
        return count;
    }
}

I got the result (from counter1 and counter2, respectively):

1   
2   

But if I instead change the method increment to type int, i.e.

public class Counter {

    private int count;

    public Counter() {
        count = 0;
    }

    public int increment() {
        return count++;
    }

    public int getValue() {
        return count;
    }
}

I got the same result:

1   
2   

I know void doesn't return any value, however, is there any purpose of using void over int (or vice versa) in this example?

Upvotes: 0

Views: 59

Answers (2)

GhostCat
GhostCat

Reputation: 140457

You write code to do two things:

  • solve some problem (like implementing a counter and providing access to the internal state of that counter)
  • communicate your intentions to human readers

You can decide to use void to indicate that calling increment() is not meant to give you any insights into the current counter count. You could use the int return type to tell your readers that the method also provides that information. But in the second case you might also slightly change the method name, to "incrementAndGet()" for example.

When you check out classes like https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html you will find that pattern "do something and return the new state" quite often.

And yes, one could see it as a violation of srp to return a value from result, but as my example shows, sometimes it is helpful or actually mandatory to deviate slightly...

Upvotes: 2

M..
M..

Reputation: 85

There is no point in using "int" here because you are getting the value of count with another method. If you wouldn't have the "getValue" method you would need to use "int" to get the value. But because you have the "getValue" method you should not use "int" because is it a violation of the "single responsibility principle".

Upvotes: 0

Related Questions