Ramifications of Virtual Methods/Properties
Asked Answered
U

2

5

I have been using Moq recently in my development process and I like what I am able to achieve.

However, I find myself making my methods (and properties for the mostpart) virtual so that I can replace them with a mock in my tests.

Other than "you are making all your methods and properties overrideable", what real world ramifications are there to this course of action?

Unsuspected answered 21/11, 2009 at 7:40 Comment(2)
have you considered making your class implement an interface which defines all those methods? That way your Mock is based on the interface and you don't have to explicitly mark all your methods with the virtual keyword...Amyotonia
That would bring most disadvantages of being virtual as well. However, it does make the thing more flexible so at the end of the day, it might be the better choice after all.Counterattraction
C
11

Well, you prevent most kinds of optimizations. First, the JITter may not know which implementation is going to be called, (And he can't, since you may be using a Mock, right?) So, all these property accessors, that would have been inlined will be real calls now. Thx to inlining, simple properties will not add real overhead at runtime. Virtual properties won't be inlined, so they do.

That was the performance side of things, the other problem is, that you can't trust properties to work as you think they are working. Every property could be overridden. Even by yourself, because "this one time it really made sense, right?". So you'll find yourself checking the call tree more often than usual to check which implementations are applicable to the code you are working on.

Counterattraction answered 21/11, 2009 at 7:55 Comment(1)
Thanks for the response, Robert! +1Unsuspected
R
5

I don't think there are any serious ramifications. The chances of accidentally overriding a method/property that you didn't intend to are pretty slim.

I think that the ability to substitute one class of object for another (e.g. a mock object) is a good thing, and to do that you need a base class with virtual methods/properties. It reminds me of using abstract base classes to adhere to the Open Closed Principle.

Rhotacism answered 21/11, 2009 at 7:55 Comment(1)
It definately helps with the Open part of the OCP for sure; +1 thanks for the response :)Unsuspected

© 2022 - 2024 — McMap. All rights reserved.