I posted this question on stackoverflow and it got a poor reception. In reality, the problems I'm facing are minor and any workaround can be considered impractical. However, I believe it might be of general interest in the abstract computer science domain, so I'm giving it a go here.
I'm working with Drupal's automated testing in PHP. It's a class that has two methods I'm concerned about: pass() and fail(). Each one produces a separate line on a results page indicating whether a particular operation passed or failed, e.g.
if ( $value == "expected_value" ) {
$this->pass("Name of Test");
} else {
$this->fail("Name of Test");
}
(The reason drupal does it this way is so that in the results, you can see "Name of Test" in a green bar if it passed, and in a red bar if it failed. In other words "Testing Feature A: failed" or "Test of Feature A: passed". Of course you can put two different messages in there, but in my situation, I want to put the same message in)
What I notice about the above is that it seems verbose, in that I repeat the same message twice. It seems to me that there should be a way of expressing this where I only declare the message once. Of course I could put it in a variable, but that takes up extra space and I pass it twice, also.
I'd like to do something like ternary assignment, only instead where I decide which function to call. Is there a way I can define this logic while only expressing Name of Test one time?
Something like:
$function = ($value == "expected_value") ? "pass" : "fail" ;
$this->$function("Name of Test");
Is this the most concise, elegant way I can phrase this logic? I tried
$this->(($value == "expected_value") ? "pass" : "fail")("Name of Test");
But I got a parse error. Is there a way to get it down to one line, like ternary assignment?
Edit Here's the best formulation of my question to date: "What's a syntax I can use, in any language or pseudo-code , to express this without saying Name of test twice?"
I feel like I should be able to express this logic without saying Name of Test twice (anywhere -- including within another function that I call elsewhere in code). It seems that PHP does not allow me to express this in this way, so I'm looking for examples in other languages (and people have already posted C, javascript, and python examples) that allow you to concisely express this without repeating yourself.
(value == expected_value ? pass : fail)("Looking for expected value."), assumingpassandfailaren't macros. In C, function pointers are first-class values, but functions can't close over arguments. – Joey Adams Oct 18 '11 at 1:59if-elseblock is unnecessary. – Ankit Soni Oct 18 '11 at 9:29