Is method hiding ever a good idea

前端 未结 8 1844
死守一世寂寞
死守一世寂寞 2020-12-01 09:29

In C# the new modifier can be used to hide a base class method without overriding the base class method.

I\'ve never encountered a situation where hidin

8条回答
  •  猫巷女王i
    2020-12-01 09:45

    I recently had a case where the 'new' keyword was quite useful. I was writing unit tests for methods in a legacy code base and some of the methods in classes I was writing tests for had external dependencies hidden inside the methods. Including a mocking framework to solve the problem seemed unnecessary at the time, so instead of using a mocking framework I inherited the class I wanted to test inside the unit test class. However, the parent method was not virtual so it could not be overridden. My first solution was to just simply add the virtual keyword to the original method to allow it to be overridden and the tests worked great. Even though it worked, I don't think that adding virtual keywords to method signatures only because of the need to "mock" it in a unit test is a good design decision (but I might be wrong). Instead the usage of 'new' keyword in the child class enabled me to 'get rid of' the parent methods dependencies by hiding the original method with a method with static return values, thus writing fast unit tests for rest of the methods worked as well as when changing non-virtual methods to virtual methods.

    In general, I am not sure this technique can be considered good practice. However, using this kind of technique might be very useful when writing a test suite to ease refactoring when working with legacy code with many dependencies and does not have an automated test suite to start with. The tests can most likely be improved when the refactoring work is completed.

    EDIT: Because method hiding only occurs in the private inherited class it should not cause any confusion that might occur in other use cases.

提交回复
热议问题