Jump to content
  • Advertisement
Sign in to follow this  
  • entries
    19
  • comments
    29
  • views
    11264

Getting rid of nasty code

Sign in to follow this  
mcguile25

141 views

You know, sometimes you just write a piece of code and say, "What the $*#@ was I thinking?" Well, I had that moment today. I was working on creating instances of my specific weapon types and had the following code:


// create 1 of each weapon type available for the player
for ( int i = 0; i < m_weaponTypes.size(); ++i )
{
// regular pistol
if ( m_weaponTypes[ i ].GetID() == RESOURCE_WEAPON_PISTOL )
{
CPistol *pistol = new CPistol;
if ( !pistol->Create( m_displayDevice, WEAPON_VIEW_FPS, PISTOL_TYPE_REGULAR ) )
{
delete pistol;
return false;
}
m_playerWeapons.push_back( pistol );
}
// pistol silencer
else if ( m_weaponTypes[ i ].GetID() == RESOURCE_WEAPON_PISTOL_SILENCER )
{
CPistol *pistol = new CPistol;
if ( !pistol->Create( m_displayDevice, WEAPON_VIEW_FPS, PISTOL_TYPE_SILENCER ) )
{
delete pistol;
return false;
}
m_playerWeapons.push_back( pistol );
}
// .........AND SO ON FOR CRocketLauncher, and any other dervied class types
}




This code violated my rule of cleanliness and efficiency. So I decided to scrap this for a psuedo weapon factory system. So the above code now becomes:


for ( int i = 0; i < m_weaponTypes.size(); ++i )
{
CWeapon *newWeapon = GetWeaponFactory()->Produce( m_weaponTypes[ i ].c_str(), WEAPON_VIEW_FPS );
if ( !newWeapon )
{
return false;
}

m_playerWeapons.push_back( newWeapon );
}





Much better, huh?
Sign in to follow this  


1 Comment


Recommended Comments

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
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!