简体   繁体   中英

Member Function returning/taking instance variable

Lets say I am implementing a calculator which adds two numbers.

Since we want to keep track of the partial result so far, we need to maintain two member variables, oldNum for the partial result, and newNum for the currently entered number.

Now at some point there will be an add method, which adds newNum to oldNum and stores the result in oldNum.

Since both newNum and oldNum are member fields, we don't need to pass or return anything in the add method.

On the other hand, if you read the source code and you encounter a void method add without any parameters this might look strange.

So my question is whether there are sometimes situations where you want to pass a member field to a member function.

It would look something like:

class Calc {

   int oldNum, newNum;

   public void add1() {
    oldNum = oldNum + newNum;

  }
public int add2(int n1, int n2) {
        return n1 + n2;
 }

There isn't anything strange about returning void here, you are changing the internal state of the object. You could either return this , void, or a copy of the result of the addition if you wanted to provide an output.

The add2(...) method you wrote doesn't use any member variables, which should be implemented as a static method, which doesn't require the object to be instantiated. However, I don't think you need that here.

Why not go for a fluent interface and have your add method return this?

public class Calculator {
  private int runningTotal = 0;
  public Calculator add(int value) {
    runningTotal += value;
    return this;
  }
}

Then your calling code can be quite elegantly written (IMO).

Update

This way your calling code can do the following:

Calculator calc = new Calculator();
int result = calc.add(x).subtract(y).divide(z).result();

I think what you do here is largely a question of how you want your calculator to behave. It sounds like you're going for a "stack-based" approach, where a person could enter commands like this:

12 11 +

If that's the case, your Calc class should probably have methods like:

void pushNumber(int number);
void add();

And that won't be confusing to typical developers who are working with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM