Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a public void method that must be run at least once

Suppose I have a class ClassA whose getters and setters I use multiple times in my program. Suppose at the end of the program it is critical that I run the public void checkErrors() within the instance of ClassA that I've been working with, which will throw an exception or log an error if there is an error.

Is there a way I can set up ClassA that will throw a RuntimeException if checkErrors() isn't called at least once by the main method?

For example, hoping that you have an imagination, it would be good to have a method like: public compulsory void checkErrors() where compulsory means it must be run once by the main method.

This is an event driven programming context.

In my problem, the instance of ClassA might be needed for a few calculations then not needed any more (with the state of the class, resulting from various internal calculations and setters, being used in other parts of the program). Thus, at the end of the instance's life in the program, I would like to checkErrors() before continuing the program (thus stopping error propagation to later stages of the program).

This compulsory thing would just be to stop the error on behalf of the programmer to call this method at least once.

like image 584
user2763361 Avatar asked Nov 18 '25 22:11

user2763361


1 Answers

I want make it compulsory for the main method to checkErrors() on ClassA before ClassB uses ClassA's state in an event driven programming case.

Then you shouldn't design the program this way. Instead, you should introduce a class ValidState and pass an instance of this class to ClassB. And ClassA should have a method

ValidState produceValidState() throws IllegalStateException

which would check for errors and, if none, produce the valid state.

That way, it's completely impossible for the main method to pass invalid state to ClassB. It has to ask ClassA to check for errors in order to get the valid state that ClassB needs to work.

like image 189
JB Nizet Avatar answered Nov 20 '25 13:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!