if and refactor

Recommended Posts

I think condition is core of a code.
but code with condition is hard to split to small block code.
a function that have long if statement is hard to refactor.
more worse,a condition usually depends on many object.
forexample:
void function
{
....
if(..)
object.method();
if(..)
object2.method2();
else
if(...)
object3.method3();
else
ojbect4.method4();
.....
}
it is disaster to me.
are there some very good way to handle this?

Share this post

Link to post

Share on other sites

well, you should really separate all of those individual pieces into either a class, or at the very least separate functions to handle the different tasks.

For example, splitting all the texture stuff into a function called updateTextures( ) and have the view transform changes in a function called updateView or something like that.

Ideally, if you are using C++, I would suggest figuring out the core "pieces" of your program and make classes to represent them. That way you can encapsulate all the functionality instead of cramming it all directly in your main loop.

[edit]I also just noticed that you have a switch statement in which you are switching not only on actions of a model, but on what season it is? This is another example of your current mess of non-related things all being crammed together. Separate and encapsulate my friend.

This is the refactored code, according to functionality. After you separate the logic into functional units, you can focus on improving individual pieces (getMaterialForSeason, handleMovement, doTimeStep).

Next step would be also, to separate "action" into movementAction and worldAction, where first handles the JUMP and WALK, and worldAction handles season changes. This would simplify the corresponding methods.