C# Attribute or Code Inspection Comment to Encourage or Discourage Call to Base Method from Virtual Method Override - methods

I'm working on a C# project in Unity with Rider.
I sometimes see a base class with an empty virtual method, and then a derived class that overrides that method. The method override has an explicit call to base.MethodName() even though the base method is empty.
public class A
{
public virtual void Method1() { }
public virtual void Method2()
{
// Important logic performed here!
}
}
public class B : A
{
public override void Method1()
{
base.Method();
// Do something else ...
}
public override void Method2()
{
// Do something here ...
}
}
When looking at the method in Rider's IL Viewer, the call to the base method is included, even though the method is empty.
Are there any method attributes or code inspection comments in C# or Rider that could:
Generate a compiler or code inspection warning when calling a base method that is empty.
Generate a compiler or code inspection warning when not calling a base method that is not empty.
For example:
public class A
{
[OmitCallFromOverride]
public virtual void Method1() { }
[RequireCallFromOverride]
public virtual void Method2()
{
// Important logic performed here!
}
}
I can imagine a scenario where multiple derived classes override a method and one or more mistakenly failed to call the base method, which might result in unexpected behavior. Or situations where there are unnecessary calls to an empty base method, which may be wasteful, but unlikely to break anything.
While I'm primarily inquiring about whether such attributes or code inspection comments exist, I am also curious to know of how people might handle these situations, such as simply always calling the base method from an override, keeping important logic out of base virtual methods, or using some other method of communicating whether a base method call is unnecessary or required.

Generate a compiler or code inspection warning when calling a base
method that is empty.
In c#, as far as I know, there is no warning for an empty method. So, I think there is no warning when calling a base method that is empty.
But you are free to write one for you: Write your first analyzer and code fix
Generate a compiler or code inspection warning when not calling a base
method that is not empty.
Not in C#, and I think is not a good idea to force a derived class to call a base method. I can understand that in your scenario, it would be great if all your derived classes method call always the base method, but it will be a very uncommon case. And generally when we need tricky (not intuitive) rules, that means our solution is not very clear, or it will be error-prone.
keeping important logic out of base virtual methods
If you need A.Method1 to be called, maybe let it as a virtual method is not a good idea. You have a virtual method when you want to give to your derived classes the opportunity to use it OR to overwrite it with a more adapted version.
I propose you a solution that maybe you can adapt to your scenario.
abstract class A
{
public abstract void Method1();
public virtual void Method2() { }
public void MustBeCalled()
{
// Here you can put the logic you had in Method1, you need to execute this code, so this method can't be overwrited.
}
public void TemplateMethod()
{
Method1();
MustBeCalled();
// Do something else ...
}
}

Related

Inheriting default methods with the same name in the class without any compilation error

How a class can implement two interfaces with the same default method in Java 8.
I was not able to get the concept behind the same default method from different interfaces getting inherited in the sub class.Please explain the issue.
interface House {
default String getAddress() {
return "101 Main Str";
}
}
interface Bungalow extends House {
default String getAddress() {
return "101 Smart Str";
}
}
class MyHouse implements Bungalow, House {
}
public class TestClass {
public static void main(String[] args) {
House ci = new MyHouse(); //1
System.out.println(ci.getAddress()); //2
}
}
In the above code default method getAddress() in interface House is present.another method with the same name is declared as default in the extending interface Bungalow
How class MyHouse can implement both the interfaces without any compilation error(because it doesn't know which method has the preference in that case implementing should fail.)
If i call new MyHouse().getAddress(); gives compile error but it should give compilation error even without method calling from MyHouse class.
It seems that the answer is here, where there is a different example, but sort of makes sense and is really close to yours.
Ask me the exact same thing in 1/2 a year and I'll say it will fail at compile time and point me to this answer, so that I could read the JLS again. I guess this is how they decided to implement it. Without thinking too much, I, personally (may be wrong) think that this is at least counter intuitive...

static vs default method - Functional interfaces

I am creating functional interfaces and want to reuse default methods with anonymous implementation.
public class JavaInterfaceTest {
public static void main(String[] args) {
FunctionalIntf fi = () -> {
System.out.println("In ananymus impl, trying to call default method");
// doInternal()
return "Hello";
};
fi.doFunction(); // How this line valid ?
fi.doInternal();
FunctionalIntf.doSomething();
}
}
#FunctionalInterface
interface FunctionalIntf {
String doFunction();
default void doInternal(){
System.out.println("In doInternal");
}
static void doSomething(){
System.out.println("In doSomething");
}
}
How fi.doFunction(); is valid, if I go thru anonymous implementation.
How can I re-sue default method or static method if I want from implementation?
3. Is returning something valid/best practice in my case as I can not handle the returned value.
When you are creating the anonymous class, you actually provide an implementation for your abstract method doFunction() from FunctionalIntf interface. So when you are using this line of code:
fi.doFunction();
It means that you are calling doFunction() method from the anonymous class. This is another example on how functional interfaces work:
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("I'm Runnable!");
}
};
r.run();
In this case we override run() method from Runnable interface, which is also a functional interface.
You cannot provide another implementation for the static method because you cannot override a static method. Static methods are not inherited in Java at all. You can instead provide another implementation for the default method by overriding as mentioned in my above example.
Regarding the returned value, you need to define your method to return the exact value you need. There is no best practice in that.
When you implement a functional interface, you have 2 options:
Use lambdas, as you have
Use inner classes.
If you use lambdas, like you have, you have the default implementation of the static/default methods along with the implementation of the abstract method.
If you use an inner class, the normal rules of overriding applies.

Why is generated override code for generic method incorrect?

I have an abstract generic class
public abstract class Foo<TType>
with an abstract method
public abstract object DoSomething(TType arg = default(TType)) {}
Now, the inherited class
public class BabyFoo : Foo<string>
when I want to override DoSomething and start typing "override " to get the intellisense/generator to write a method skeleton I expected
public override object DoSomething(string arg = default(string))
or even
public override object DoSomething(string arg = null)
but it literally comes up with
public override object DoSomething(string arg = default(TType))
My initial thought is it is a VS2010 bug since optional params are new to c#, but can anybody tell me if there is perhaps a real reason why (reference types vs value types??) the IDE generates this code?
Just to clarify:
public abstract class Foo<TType>
{
public abstract object DoSomething(TType arg = default(TType));
}
public class BabyFoo : Foo<string>
{
// Expected:
public override object DoSomething(string arg = default(string))
// Actual:
public override object DoSomething(string arg = default(TType));
}
Unless there's something I'm missing, it's quite simply a bug in the Visual Studio IDE / code-gen. Changing the method signature to the "expected" one results in code that will compile, as the "actual" one refuses to compile thanks to being clearly invalid.
Having tried a few different types for TType as well as things like the where TType : new() constraint, I couldn't get VS to generate valid code with your DoSomething method.
Congratulations - you've (probably) found a bug in Visual Studio =)
There are always edge cases when it comes to code generation, I logged one for Visual Basic 2005/2008 a long time ago that was resolved WONT FIX as it was a really obscure one comparatively. Hopefully this one'll be fixed though!

Are "passive" objects considered a good design practice?

I find myself very often creating an object that has no public methods and is self-contained. It typically handles events of arguments passed to its constructor in its private methods and does not raise any events or expose any public methods.
I am calling this type of objects "passive" objects - objects that do not have any public methods defined. All interaction occurs inside them in private methods and events of arguments passed in constructor.
Typically it is some utility class, like one that assures that two forms will be sticked together:
public class StickyForm : IDisposable
{
private readonly Form form;
private readonly Form parentForm;
public StickyForm(Form form, Form parentForm)
{
this.form = form;
this.form.StartPosition = FormStartPosition.Manual;
this.parentForm = parentForm;
this.parentForm.LocationChanged += new EventHandler(parent_LocationChanged);
this.parentForm.SizeChanged += new EventHandler(parent_SizeChanged);
SetLocation();
}
void parent_SizeChanged(object sender, EventArgs e)
{
SetLocation();
}
void parent_LocationChanged(object sender, EventArgs e)
{
SetLocation();
}
private void SetLocation()
{
//compute location of form based on parent form
}
public void Dispose()
{
this.parentForm.SizeChanged -= parent_SizeChanged;
this.parentForm.LocationChanged -= parent_LocationChanged;
}
}
But sometimes it is also some kind of controller, providing interaction between two views:
public class BrowseController
{
private IBrowserView view;
private IFolderBrowser folderBrowser;
public BrowseController(IFolderBrowser folderBrowser, IBrowserView view)
{
this.view = view;
this.folderBrowser = folderBrowser;
this.folderBrowser.NodeOpened += folderBrowser_NodeOpened;
}
private void folderBrowser_NodeOpened(object sender, Core.Util.TEventArgs<IPictureList> e)
{
this.Browse(e.Value);
}
public void Browse(IPictureList content)
{
//stripped some code
AddItemsToView(content);
}
private void AddItemsToView(IPictureList browser)
{
//call methods on view
}
}
Are such "passive" objects considered a good design practice?
Is there a better name for this kind of class?
Seems like fine design to me. I'm not sure about the name passive though. Those classes do seem pretty active. They react to events and do stuff. I would think a class is more passive if you have to call methods on it to get it to do stuff, but normally it wouldn't do anything unless poked.
How about the name "controller". "controller" is the more usual name for a class used in a UI that causes interaction between a view and data, and they quite often don't need to have public methods.
I'm sure there's other ideas for names.
I don't see anything wrong with that. If it results in clean, readable code, go for it!
I wouldn't call the objects that react to notifications and update their state completely passive.
One other thought, if the objects simply adjust their state to reflect changes in the outside world without providing much of their own, you may slice their "functionality" and put it into other more active "components". There may be not enough reason for these objects to exist.
If this organization however makes you code structure better, clearer and more maintainable, then use it and don't worry about it.
I think that there's one important criteria to meet with this design: can you test it? The designs you have seem to be testable, but you may have to be careful as I can see this leading to some rather untestable code.
In regards to the name, I think this may be an example of the Mediator pattern.
Conceptually this appears to be an implementation of strategy pattern. Although in this particular case the reasoning is different from strategy pattern', it still yields very readable and nicely granulated code. Go for it.
UPDATE: to make a little clearer what I mean consider two (or more) classes derived from StickyForm
public class VeryStickyForm : StickyForm
{
//some implementation here
//but interface is completely inherited from StickyForm
}
public class SomewhatStickyForm : StickyForm
{
//some implementation here
//but interface is completely inherited from StickyForm
}
And you decide which one to use dynamically depending on run-time state... you implement a strategy.
As I said your solution is conceptually similar to strategy: you select some behavioral aspect of your application that can be well abstracted into policy and move the implementation of the policy into separate class, that does not know about the rest of the application, and your application does not know much about guts of the policy. Even though you do not use it polymorphically, resemblance to strategy is clear.

RhinoMocks: Correct way to mock property getter

I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.
I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.
This is what I'm doing so far:
public void CreateSomethingIfUserHasAdminPermissions()
{
User user = _mocks.StrictMock<User>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.
Can someone explain how I can achieve my goal here?
One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this:
public class FakeUserType: User
{
//overriding code here
}
Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type.
As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as aaronjensen mentioned as follows:
public class User
{
public virtual Boolean IsAdministrator { get; set; }
}
This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior.
Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this:
public interface IUser
{
Boolean IsAdministrator { get; }
}
public class User : IUser
{
private UserSecurity _userSecurity = new UserSecurity();
public Boolean IsAdministrator
{
get { return _userSecurity.HasAccess("AdminPermissions"); }
}
}
public void CreateSomethingIfUserHasAdminPermissions()
{
IUser user = _mocks.StrictMock<IUser>();
SetupResult.For(user.IsAdministrator).Return(true);
// do something with my User object
}
You can get fancier if you want by using dependency injection and IOC but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway.
I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.
Make sure IsAdministrator is virtual.
Also, be sure you call _mocks.ReplayAll()
_mocks.ReplayAll() will do nothing. It is just because you use SetupResult.For() that does not count. Use Expect.Call() to be sure that your code do everything correct.

Resources