mercredi 8 juin 2016

Java: Is it possible to always execute a certain function before other functions are called? (Like @Before in JUnit)

Is there a way to always execute a function before any other function of a class is called?

I have a class where I need to refresh some fields always before any function is called:

public class Example {

private int data;

public void function1(){

}

public void function2(){

}

//@BeforeOtherFunction
private void refresh(){
    // refresh data
}
}

Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.

JUnit has a solution for this with the @Before-Annotation. Is there a way to do this in other classes as well?

And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!

Aucun commentaire:

Enregistrer un commentaire