JavaDeveloper
JavaDeveloper

Reputation: 5660

How to establish a strong before after relationship between two public functions

In the following code of A* algorithm here, I have 2 functions setG and calcF, such that -

  1. setG must be called before calcF &&
  2. calcF must be called after setG

in other words, simply calling setG without calling calcF later is incorrect. Also, simply calling calcF without calling setG before is incorrect. Calling calcF before setG is incorrect.

How can this rule be enfored to the client ?

A similar question exists here, but there is a minute difference. This question is more stricter in conditions.

Upvotes: 1

Views: 92

Answers (2)

venergiac
venergiac

Reputation: 7717

The answer of Markus is for me correct. Howvere if you want know the design pattern, you should use a pipe:

 public Holder setG(G g)

 public void calcF(F f, Holder H)

Upvotes: 1

Markus Malkusch
Markus Malkusch

Reputation: 7878

The first idea would be to merge those functions into one function setGAndCalcF():

private void setG(int g);

private void calcF(T destination);

public void setGAndCalcF(int g, T destination) {
    setG(g);
    calcF(destination);
}

If this is not feasible you can implement runtime checks (plus documentation) into setG() and calcF() which would throw an Exception (e.g. IllegalStateException).

Upvotes: 4

Related Questions