Style question

Maxim Fomin maxim at maxim-fomin.ru
Thu Jul 11 12:40:22 PDT 2013


On Thursday, 11 July 2013 at 18:22:11 UTC, Namespace wrote:
> I have a style question, because a friend of mine has a similar 
> problem currently and I have no good advice for him.
>
> Let's assume we have this classes:

The whole situation looks strange. If you can change both files, 
than it is unclear what made you to write such inconsistent code. 
If you can change only one of them, then it should be adjusted to 
another (meaning importing external file and using that enum 
instead of trying to define different type and passing it).

> ----
> class MyClass {
> public:
> 	enum A {
> 		Foo = 0,
> 		Bar = 1
> 	}
>
> private:
> 	A _a;
> public:
> 	this(A a) {
> 		this._a = a;
> 	}
>
> 	void test1() {
> 		MyStaticClass.test2(this._a);
> 	}
> }
>
> //----
>
> enum B {
> 	Foo = 0,
> 	Bar = 1
> }
>
> final abstract class MyStaticClass {
> public:
> 	static void test2(B b) { }
> }
>
> void main() {
> 	
> }
> ----
> Prints: Error: function enum_problem.MyStaticClass.test2 (B b) 
> is not callable using argument types (A)
>
> What should he do?

Judging by "MyStaticClass.test2(this._a)" it seems that the first 
imports the second which is also suspicious - you are importing 
module which contains main function. From where does the code 
come from?

> As far as I can see he has 3 options:
> 1. An external file with the enum information. Both classes 
> would import it and could use the same enum. But he cannot 
> change the API, so this is no real option.
>

It would be good to clarify which file cannot be modified, 
although it does not really matter - just use one version of enum.

> 2. Change test1 into this:
> ----
> void test1() {
> 	B b = cast(B) this.a;
> 	MyStaticClass.test2(b);
> }
> ----
> This works fine. But is it safe? And is it good style?

It is safe but not @safe (you will have complains if try to mark 
function as @safe). Of course this is a bad style, the whole case 
is strange.

> And how is this cast converted? Is it cheap?

Essentially nothing special is done. Of course it is cheap.

> 3. Change test2 so that it accepts (even) (u)int. But then he 
> lose the Type safety.

This is almost same as direct cast in #2. Instead of making 
test2() accept B or (u)int consider making it static void test2 
(MyClass.A a) and wipe out enum B entirely.


More information about the Digitalmars-d-learn mailing list