request switch statement with common block

Andre Artus andre.artus at gmail.com
Mon Aug 5 10:30:06 PDT 2013


>> Andre Artus:
>>
>> It may not always be the case, but in my experience this often 
>> leads to write-only code.
>> I'm pretty new to D, so I'm not quite up to speed with the 
>> metaprogramming abilities, but I'm under the impression that 
>> this is what mixin's are for.

> MattCoder:
>
> Well I'm not experienced too, but mixin's for what I know just 
> works in compiler time right?
>
> But anyway it would be possible to write my own switch version 
> with mixin? I really would like to see this.
>
> Matheus.

Yes, it takes any string that's valid D. I see people using it to 
embed domain specific languages (e.g. PEG via PEGGED) so you 
should easily be able to write a translator/preprocessor that 
takes  your switch and converts it to D code.

mixin("
switch (number)
{
	default: // valid: ends with 'throw'
		throw new Exception("unknown number");
	common_entry:
	  // some common entry code
		break;
	common_exit:
	  // some common exit code
		break;
	case 3:
		message ~= "three ";
		break;
	case 4:
		message ~= "four ";
		continue;
	case 6:
		message ~= "six ";
		break;
}
");

The preprocessor could rewrite to this string:

"
switch (number)
{
	case 3:
	case 4:
	case 6:
	  // some common entry code
	break;
}
switch (number)
{
	default: // valid: ends with 'throw'
		throw new Exception("unknown number");
	case 3:
		message ~= "three ";
		break;
	case 4:
		message ~= "four ";
		continue;
	case 6:
		message ~= "six ";
		break;
}
switch (number)
{
	case 3:
	case 4:
	case 6:
	  // some common exit code
	break;
}

"

**** I do not recommend anyone do  this ****

The reason I would not recommend this is that it leads to brittle 
code that is hard to debug and reason about.


The reason I use `switch`, and not `if` for the entry and exit 
code is because these should only fire under the same conditions 
as the cases in the original switch, otherwise you introduce hard 
to find bugs in your code.

Once again, I do not recommend people doing this: my preference 
is for code that makes the programmers intent clear and explicit.




More information about the Digitalmars-d mailing list