Pergunta

I'm stuck on a problem that is:

-how to set a precondition for all the methods in class so that any method is invoked, these preconditions are checked and if they are met, the invocation begins. If not, an exception is thrown.

What I need that for? I've assumed that any instance of my class is in some state. And I simply want not to allow some methods to be invoked if the state is not correct.

For example: If my class is Player and his state is DEAD I wouldn't want his level to be increased while in this state.

That example shows exactly what I need. Something like a filters on actions in PHP or something similar.

My point is not to check manually, at the begining of all methods, if the conditions for being in the right state are met. Is there any solutions that meets my expectations? Maybe some design patterns or something?

Foi útil?

Solução

The only solutions will be relatively complicated; you're better off calling a check method at the start of every method where you want to do the check. It's just simpler, self-documenting, and makes more sense.

Outras dicas

You can wrap your methods in a try-catch control statement.

try{
...}
catch(preconditions){
...}

Try using Aspect Oriented Programming (AOP)

You may define pointcuts for every method in class and check your state there. If condition is meet just invoke that method, if not - just throw an exception.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top