What's a good approach to DRY with the block code of a case-statement?

Jack jckj33 at gmail.com
Mon Apr 26 20:39:55 UTC 2021


I have a block of code that the only thing that change is the 
type passed in one of the template functions called so I'd like 
to make a DRY for this. But I'm not just replacing by a function 
due to control-flow, for example, there are if-statements where 
one just break and the other return 0. I think I could do 
something with mixin() that would kinda mimic C's macro but I 
still find it messy. Any alternatives?

```d
static int doSomething()
{
	switch(val)
	{
		case VAL_FOO:
			auto obj = getObject!MyType(someData); // this is the type
												   // that changes
			if(obj.shouldExit()) break;
		
			auto m = Message(...);
			if(obj.doSomethingElse(m)) return 0;
		break;

	   // ...
	
	   default:
	}

	return doSomethingY();
}
```

Maybe my least resort, if I went to replace by a function, I 
could do something like this:

```d
enum OP { BREAK, RETURN }
pragma(inline, true):
OP foo(T)()
{		
	auto obj = getObject!T(someData); // this is the type
										   // that changes
	if(obj.shouldExit()) return OP.BREAK;

	auto m = Message(...);
	if(obj.doSomethingElse(m)) return OP.RETURN;

	return OP.BREAK;
}
```

then:

```d
static int doSomething()
{
	switch(val)
	{
		case VAL_FOO:
			auto r = foo!MyType();
			if(r == OP.BREAK) break;
			if(r == OP.RETURN0) return 0;
		break;

	   // ...
	
	   default:
	}

	return doSomethingY();
}
```

I still find this not much elegant. If anyone knows a better way 
to do this, help are very welcome


More information about the Digitalmars-d-learn mailing list