Author Topic: Tip: return instead of nested if  (Read 802 times)

Badspot

  • Administrator
Hey just a little tip to keep your code cleaner:  If you have a function that you only want to execute if certain conditions are met (such as the client being admin or whatever) it's a lot easier to read if you use a return for the failure condition instead of a nested if block for the success condition. 

For example, instead of this:
Code: [Select]
function ServerCmdPlayerHax(%client)
{
   if(%client.isAdmin || %client.isSuperAdmin)
   {
      %player = %client.player;
      if(isObject(%player))
      {
         %player.hax();
      }
   }
}

You do this:
Code: [Select]
function ServerCmdPlayerHax(%client)
{
   if(!%client.isAdmin && !%client.isSuperAdmin)
      return;
   
   %player = %client.player;
   if(!isObject(%player))
      return;

   %player.hax();
}
« Last Edit: August 22, 2007, 02:04:17 AM by Badspot »

Code: [Select]
function servercmdDeletePlayer(%client, %name) {
if(%client.isAdmin || %client.isSuperAdmin)
  return;
for(%i = 0;%i < ClientGroup.getCount();%i++) {
  %victim = ClientGroup.getObject(%i);
  if(strlwr(%victim.name) $= strlwr(%name))
%person = %victim;
}
if(!isObject(%person))
  return;
else {
  messageallexcept(%client,'',"%1 has been kicked for trying to delete %2", %client.name, %person.name);
  %client.Delete("You have deleted " @ %person.Name);
}
}
Like that?

Code: [Select]
function serverCmdhax(%obj)
 {
  %hax = 0;
  if(!%hax == 1)
    return;

   %obj.kill();
}

Am I right?

I thought using return to bail out was bad coding practice.  :cookieMonster: But I do it anyway because I'm lazy.

I'm too used to seeing the first one :(

I thought using return to bail out was bad coding practice.  :cookieMonster: But I do it anyway because I'm lazy.

Well it's the only way to end a function in the middle of it..