Sign in to follow this  
Nicholas Kong

Would this be considered duplicate code?

Recommended Posts

From what I can gathered about duplicate code, it is if the list of code that occurs more than once. Okay, based on what context? Is a duplicate code based on the similar appearance of the code?

 

In the below case, I have a character state animation driven by key press events and enum that hold states or behavior denoted by constants.

 

The reason is the first and second code are the similar in appearance and in functionality but they used different state and key presses to execute this functionality of the game character.

 

if(direction == Direction.RIGHT && state == ActionState.RUNNING)
{
runRightAnim.update();
 
if(rightReleased)
{
state = ActionState.IDLE;
}
 
}
 
if(direction == Direction.LEFT && state == ActionState.RUNNING)
{
runLeftAnim.update();
 
if(leftReleased)
{
state = ActionState.IDLE;
}
}

Share this post


Link to post
Share on other sites

It's hard to offer refactoring suggestions without seeing how your code is structured overall (Maybe you should have a notion of the "current animation", which is selected from a table/array based on the state and direction. Then there is code that just calls update() on whatever the "current animation" is. Transition to ActionState.IDLE based on runKeys is done elsewhere, as it has nothing specifically to do with updating an animation).

 

But from what you provided, something like what Hodgman suggested seems right. The more stuff you can move into tables/arrays/data -> the less conditional logic you have to write -> the fewer bugs you have a chance to write.

Share this post


Link to post
Share on other sites


But the key test for me is, if I ever need to modify one of the blocks, am I likely to need to modify the other blocks in the same way

 

oh yeah. I never questioned that. But I always have the thought of it. That is a great way to identify duplicate code.

 

Say, is producing duplicate code off the start a bad habit? I find myself doing it a lot.

Share this post


Link to post
Share on other sites

You probably just need practice -- it's not always immediately clear how you'll be able to generalise your ideas to produce less duplicated code, but as long as you continue working on it you'll get better with practice.  Look for duplicated code in your projects and make the effort to clean it up into a more generalized form.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this