-1

I'm studing a code wich has this code:

public void add(StockUpdate newStockUpdate) {

    for (StockUpdate stockUpdate : data) {
        if (stockUpdate.getStockSymbol().equals(newStockUpdate.getStockSymbol())) {
            if (stockUpdate.getPrice().equals(newStockUpdate.getPrice())) {
                return;
            }
            break;
        }
    }

    /* data.add mathod checks the new data against the existing data. If no change is found, the update is discarded. */
    this.data.add(0, newStockUpdate);
    notifyItemInserted(0);
}

I just want to know if the return and the break statements in this code are, in any way, different from each other. Because I tested a similar example outside this code and both return and break stopped the loop and terminates the function.

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
  • `break` will break the loop, not return from the entire method. So the next line that is executed would be the `this.data.add...` – Rogue Oct 14 '17 at 20:58
  • To give some food for thought, you can also have a look at the [`continue` keyword](https://stackoverflow.com/q/462373/4906586) – Al-un Oct 14 '17 at 21:05
  • Thanks @Rogue! this is what I wanted to know. The same as the response I gave the green checkmark. – Igor Grecco Lacourt Oct 15 '17 at 13:10

1 Answers1

0

break stops just the loop; return stops the entire method.

The juxtaposition of break and return like this makes it quite hard to follow the logic of the add method. Consider that the following might be easier to follow:

public void add(StockUpdate newStockUpdate) {
  StockUpdate stockUpdate = findStockUpdateBySymbol(newStockUpdate.getStockSymbol());
  if (stockUpdate != null
      && stockUpdate.getPrice().equals(newStockUpdate.getPrice())) {
    return;
  }

  /* data.add mathod checks the new data against the existing data. If no change is found, the update is discarded. */
  this.data.add(0, newStockUpdate);
  notifyItemInserted(0);
}

// On non-android, it's easier to do this with a stream/findFirst.
private StockUpdate findStockUpdateBySymbol(StockSymbol sym) {
    for (StockUpdate stockUpdate : data) {
        if (stockUpdate.getStockSymbol().equals(sym)) {
            return stockUpdate;
        }
    }
    return null;
}

I'd say that this is easier to follow (whilst being slightly more verbose) because it is separating out the different things that are being done: you're trying to find a matching stock symbol; and if you find that, do other stuff. Mixing that all together into the one loop obfuscates that intent.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243