开发者

Java/C# Interface wiring

Is it possible in Java or C# to wire an interface method to a particular general purpose method?

In other words can I do the following without the stub methods which call the actual method:

public interface IInterface1
{
    object DoSomething(object withThis)开发者_JS百科;
}

public interface IInterface2
{
    object DoSomethingElse(object withThis);
}

public class SomeClass : IInterface1, IInterface2
{
    object DoesNothing(object withThis)
    {
        return withThis;
    }

    object IInterface1.DoSomething(object withThis) // stub method
    {
        return DoesNothing(object withThis);
    }

    object IInterface2.DoSomethingElse(object withThis) // stub method
    {
        return DoesNothing(object withThis);
    }
}

I hope that the compiler would be smart enough to realize that all it has to do is wire IInterface1 and IInterface2 to the DoSomethingElse method and not be jumping through the stub methods...?

Cheers, J


The compiler doesn't strip them out at compile time (would make for some very challenging to read stack traces.) However, modern run times for both languages have Just In Time Compilers that perform in-lining. The JIT can and will strip out many degenerate method calls and move the actual code around to avoid allocating registers for references to the method arguments and the other overheads associated with allocating a method space.

Whether any particular method is actually eligible to be inlined is very specific to the language and version of the runtime. This is why, for example, chains of degenerate getters and setters in java beans don't actually translate to huge heaping piles of wasted register space at runtime.


To me, it doesn't make sense to have two different methods executing the exact same piece of code. I'd start with refactoring what the interfaces are defining


No, this isn't something you can do without adding the stub methods. What if you had a DoesNothing2 method in the class that has the same signature as DoesNothing? How would the compiler know which one to use? It seems very specialized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜