The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)
BartC
bc at freeuk.com
Mon Mar 14 13:53:38 EDT 2016
On 14/03/2016 17:17, Mark Lawrence wrote:
> On 13/03/2016 20:12, Marko Rauhamaa wrote:
>> BartC <bc at freeuk.com>:
>>
>>> Exactly why having ready-made solutions is preferable to everyone
>>> hacking their own solutions to switch.
>>
>> A developer friend of mine once said insightfully that the point of OO
>> is getting rid of switch statements. IOW, most use cases for switch
>> statements are handled with virtual functions.
>>
>> The most significant exception in my experience is message decoding,
>> where switches/ifs cannot be avoided.
> http://c2.com/cgi/wiki?SwitchStatementsSmell
I get it. The author doesn't like switch statements!
But they can be a succinct and convenient way of expressing some code
patterns. Nobody is obliged to use them, but it would nice for a
language to give the /choice/. And since they mainly involve syntax, the
cost of providing them is small.
Here's one pattern:
switch X
when A,B then S1
when C then S2
when D,E,F then S3
else S4
end switch
The typical characteristics - when A to F are known at compile-time - are:
* X is only evaluated once
* None of A to F need to be evaluated
* Only a single test is needed, no matter how many case expressions
* Only one of S1 to S4 is executed (at most one when there is no else)
(When A to F are not known at compile time, then it might be implemented
differently. X is still evaluated once, but A to F are evaluated and
tested in sequence until a match or not is found. However, nothing need
change in the source.)
Here's another pattern, which can also be implemented with an underlying
switch:
X = (N |A, B, C, ... |Z)
This selects the N'th value from A, B, C (in Python, probably 0-based).
Z is the default if N is out of range. A, B, C can be any expressions.
The main characteristic is that only *one* of A, B, C or Z evaluated,
which is the difference between just using a list.
Really, it becomes difficult to see what people have against switch.
(Unless perhaps their favourite language doesn't have it and they're
trying to justify that.)
> http://c2.com/cgi/wiki?SwitchStatementsSmell
(Code-smell to me means code dominated by loads of classes, especially
for no good reason. But I'm not suggesting a language shouldn't have them.)
--
Bartc
More information about the Python-list
mailing list