Tzu ng
Tzu ng

Reputation: 9244

Trigger a function when another function is called

public void ScoreFirstBall(int pinsKnockedDown) {
  if (IsStrike(Frame, pinsKnockedDown)) {
    Score = "X";
    ScoreMessage = "Good Job";
  } else if (IsGutterBall(pinsKnockedDown)) {
    Score = "0";
    ScoreMessage = "You'll do better next time";
  }
  PinsTotal += pinsKnockedDown;
}

public void ScoreSecondBall(int pinsKnockedDown) {
  PinsTotal += pinsKnockedDown;
}

Questions:

  1. In this case I want PinsTotal += pinsKnockedDown to be called every time ScoreSecondBall(...) or ScoreFirstBall(...) runs. So I want to put it in a function (it may expand to many lines in the future).

  2. Is it efficient to do this? Because we have a thread to listen when functions are called.

Thanks for reading my question, if it's not clear, just comment and I will fix it :)

Upvotes: 0

Views: 643

Answers (2)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262929

You could refactor that code to use only one ScoreBall() function that takes an additional argument:

public void ScoreBall(int pinsKnockedDown, bool first)
{
    if (first) {
        if (IsStrike(Frame, pinsKnockedDown)) {
            Score = "X";
            ScoreMessage = "Good Job";
        } else if (IsGutterBall(pinsKnockedDown)) {
            Score = "0";
            ScoreMessage = "You'll do better next time";
        }
    }
    PinsTotal += pinsKnockedDown;
}

Then either call it directly or, if you want to keep your existing functions, have them delegate to the common implementation:

public void ScoreFirstBall(int pinsKnockedDown)
{
    ScoreBall(pinsKnockedDown, true);
}

public void ScoreSecondBall(int pinsKnockedDown)
{
    ScoreBall(pinsKnockedDown, false);
}

This way, you don't have to worry about putting the incrementation of PinsTotal into its own function.

As for efficiency, function calls do have a cost, but it's usually negligible compared to the other bottlenecks that might exist in the code.

Upvotes: 1

Samuel Slade
Samuel Slade

Reputation: 8613

From my understanding of your question, yes you can put the code PinsTotal += pinsKnockedDown in it's own method. This is common practice when calling a piece of code or logic that is common to more than one place. It also allows for easier maintainability of the logic if it were to change, as the code calling it would remain unchanged (assuming the change is internal to the method).

Upvotes: 1

Related Questions