Avoiding the for/case WTF



  • I've seen instances of hte for/case idiom posted as a massive WTF.  I think that the following is an instance, but I cannot think of a good alternative mechanism.  Code is PHP, but could reasonably be any language.  Thoughts?

     

    // Ids are actually returned by API, and ordering (and relative ordering) are unknown beforehand
    // Name is a human readable string (or label) that is not necessarily known beforehand
    // Result is some value that needs to be exposed or passed on
    $structToSearch = array(
    	array( 'id' => 3, 'name' => 'Alpha', 'result' => 5 ),
    	array( 'id' => 5, 'name' => 'Bravo', 'result' => 1 ),
    	array( 'id' => 1, 'name' => 'Charlie', 'result' => 4),
    	array( 'id' => 2, 'name' => 'Delta', 'result' => 6),
    	array( 'id' => 4, 'name' => 'Echo', 'result' => 3)
    	);
    
    $resultData = array();
    	
    // Need to search for ids 1,3,5 only
    // Synthetickey is used by consumer of this data
    for ($i = 0; $i < count($structToSearch); $i++) {
    	$syntheticKey = '';
    	if ($structToSearch[$i]['id'] == 1) {
    		$syntheticKey = 'charlieResult';
    	} else if ($structToSearch[$i]['id'] == 3) {
    		$syntheticKey = 'alphaResult';
    	} else if ($structToSearch[$i]['id'] == 5) {
    		$syntheticKey = 'bravoResult';
    	}
    	if ($syntheticKey != '') {
    		$resultData[$syntheticKey] = $structToSearch[$i]['result'];
    	}
    }
    
    print_r($resultData);
    

  • ♿ (Parody)

    I don't think this really fulfills the classic anti-pattern, since you're looking for 1, 3, 5 in the values of the array, not at the values of elements 1, 3, 5 of the array.



  • @sinistral said:

    Thoughts?



    in such situations i tend to avoid ifs by using structs:

    $iray = array( 1 => 'charlieResult', 3 => 'alphaResult', 5 => 'bravoResult' )
    
    for ($i=0;$i<count($structToSearch);++$i) {
      if (array_key_exists($structToSearch[$i]['id'], $iray)) {
        $resultData[$iray[$structToSearch[$i]['id']]] = $structToSearch[$i]['result'];
      }
    }
    


  • I agree with boomzilla. This is just a plain linear search, not a case of 'index into array by using iteration'. You could build a map from id to entry. This would look better and be reasonable if you perform many repeated lookups for the same key. But in your stated example it would have significant overhead. I would do the same as you. No WTF to see here people, carry on!


Log in to reply