views:

664

answers:

8

Every so often, I run into a case where I want a collection of classes all to possess similar logic. For example, maybe I want both a Bird and an Airplane to be able to Fly(). If you're thinking "strategy pattern", I would agree, but even with strategy, it's sometimes impossible to avoid duplicating code.

For example, let's say the following apply (and this is very similar to a real situation I recently encountered):

  1. Both Bird and Airplane need to hold an instance of an object that implements IFlyBehavior.
  2. Both Bird and Airplane need to ask the IFlyBehavior instance to Fly() when OnReadyToFly() is called.
  3. Both Bird and Airplane need to ask the IFlyBehavior instance to Land() when OnReadyToLand() is called.
  4. OnReadyToFly() and OnReadyToLand() are private.
  5. Bird inherits Animal and Airplane inherits PeopleMover.

Now, let's say we later add Moth, HotAirBalloon, and 16 other objects, and let's say they all follow the same pattern.

We're now going to need 20 copies of the following code:

private IFlyBehavior _flyBehavior;

private void OnReadyToFly()
{
    _flyBehavior.Fly();
}

private void OnReadyToLand()
{
    _flyBehavior.Land();
}

Two things I don't like about this:

  1. It's not very DRY (the same nine lines of code are repeated over and over again). If we discovered a bug or added a BankRight() to IFlyBehavior, we would need to propogate the changes to all 20 classes.

  2. There's not any way to enforce that all 20 classes implement this repetitive internal logic consistently. We can't use an interface because interfaces only permit public members. We can't use an abstract base class because the objects already inherit base classes, and C# doesn't allow multiple inheritance (and even if the classes didn't already inherit classes, we might later wish to add a new behavior that implements, say, ICrashable, so an abstract base class is not always going to be a viable solution).

What if...?

What if C# had a new construct, say pattern or template or [fill in your idea here], that worked like an interface, but allowed you to put private or protected access modifiers on the members? You would still need to provide an implementation for each class, but if your class implemented the PFlyable pattern, you would at least have a way to enforce that every class had the necessary boilerplate code to call Fly() and Land(). And, with a modern IDE like Visual Studio, you'd be able to automatically generate the code using the "Implement Pattern" command.

Personally, I think it would make more sense to just expand the meaning of interface to cover any contract, whether internal (private/protected) or external (public), but I suggested adding a whole new construct first because people seem to be very adamant about the meaning of the word "interface", and I didn't want semantics to become the focus of people's answers.

Questions:

Regardless of what you call it, I'd like to know whether the feature I'm suggesting here makes sense. Do we need some way to handle cases where we can't abstract away as much code as we'd like, due to the need for restrictive access modifiers or for reasons outside of the programmer's control?

Update

From AakashM's comment, I believe there is already a name for the feature I'm requesting: a Mixin. So, I guess my question can be shortened to: "Should C# allow Mixins?"

+1  A: 

You just described aspect oriented programming.

One popular AOP implementation for C# seems to be PostSharp (Main site seems to be down/not working for me though, this is the direct "About" page).


To follow up on the comment: I'm not sure if PostSharp supports it, but I think you are talking about this part of AOP:

Inter-type declarations provide a way to express crosscutting concerns affecting the structure of modules. Also known as open classes, this enables programmers to declare in one place members or parents of another class, typically in order to combine all the code related to a concern in one aspect.

Benjamin Podszun
The OP wants to add a method OnReadyToFly() to his class, which must obiously be callable at compile-time. AFAIK you can't achieve this with PostSharp.
jeroenh
I understood his question as "a way to add the delegation to the behavior to all classes", which could be done by a pointcut. Reading it again I'm not sure if I got that right though - not my native language and it doesn't seem to be clear. Thanks for pointing that out.
Benjamin Podszun
Benjamin, I believe @jeroenh is correct. The key to my question is that `OnReadyToFly()` and `OnReadyToLand()` are `private`. They must be implemented within every class that follows the pattern. I believe that, with C# as it is today, this cannot be enforced. I could forget to implement one or both of these methods and I would receive no error or warning. I also can't "auto implement" these methods, as I could if they were part of an interface.
DanM
Well, a compile-time weaver _could_ in theory add them (again, using the AOP idea). I do have to admit that my research after the initial answer showed, that AOP in the .Net world is seriously lacking. I guess this isn't of much use then, sorry.
Benjamin Podszun
@Benjamin, My question really wasn't to find a solution to my problem, it was to ask whether C# should be improved. Maybe aspect-oriented features should be added to C# as well.
DanM
+2  A: 

Visual Studio already offers this in 'poor mans form' with code snippets. Also, with the refactoring tools a la ReSharper (and maybe even the native refactoring support in Visual Studio), you get a long way in ensuring consistency.

[EDIT: I didn't think of Extension methods, this approach brings you even further (you only need to keep the _flyBehaviour as a private variable). This makes the rest of my answer probably obsolete...]

However; just for the sake of the discussion: how could this be improved? Here's my suggestion.

One could imagine something like the following to be supported by a future version of the C# compiler:

// keyword 'pattern' marks the code as eligible for inclusion in other classes
pattern WithFlyBehaviour
{
   private IFlyBehavior_flyBehavior;

   private void OnReadyToFly()
   {
      _flyBehavior.Fly();
   }

   [patternmethod]
   private void OnReadyToLand()
   {
      _flyBehavior.Land();
   }     
}

Which you could use then something like:

 // probably the attribute syntax can not be reused here, but you get the point
 [UsePattern(FlyBehaviour)] 
 class FlyingAnimal
 {
   public void SetReadyToFly(bool ready)
   {
      _readyToFly = ready;
      if (ready) OnReadyToFly(); // OnReadyToFly() callable, although not explicitly present in FlyingAnimal
   }

 }

Would this be an improvement? Probably. Is it really worth it? Maybe...

jeroenh
Regarding your edit: I don't think extension methods solve anything. They are _static_ for one and the behavior is a private field. You cannot access the behavior in a static method on the type (and would need several of them, in the sample for Animal and PeopleMover at least). What am I missing?
Benjamin Podszun
I agree with @benjamin about extension methods--they won't work for this case--but +1 for your proposal for how a `pattern` might be implemented. Thanks.
DanM
A: 

If I understand correctly you want types of different inheritance hierarchies have the same implementation for a certain interface method.

This can be done by using extension methods:

public static class FlyBehaviorExtensions
{
    public static void Fly(this IFlyBehavior thing)
    {
        if (thing.IsFlying) throw new InvalidOperationException();
        thing.TakeOff();
    }
}

Does this solve your problem?

Steven
+2  A: 

Cant we use extension methods for this

    public static void OnReadyToFly(this IFlyBehavior flyBehavior)
    {
          _flyBehavior.Fly()
    }

This mimics the functionality you wanted (or Mixins)

Cheers

Ramesh Vel
"Mixin" is the word that came to my mind, too. Ruby has them. C++ can do them using the Curiously Recurring Template Pattern and multiple inheritance. Doesn't C# do multiple inheritance?
xtofl
@xtofi, C# doesnt support multiple class inheritance, but support interface level multiple inheritance..
Ramesh Vel
Ignoring the typo in both variable names: This fails to take into account that the classes are using composition: Your Bird is no IFlyBehavior, it just _has_ one. Which takes you back to the start: You'd need to add a delegating method on each class (or expose the behavior directly).
Benjamin Podszun
+3  A: 

Hi DanM,

The problem you describe could be solved using the Visitor pattern (everything can be solved using the Visitor pattern, so beware! )

The visitor pattern lets you move the implementation logic towards a new class. That way you do not need a base class, and a visitor works extremely well over different inheritance trees.

To sum up:

  1. New functionality does not need to be added to all different types
  2. The call to the visitor can be pulled up to the root of each class hierarchy

For a reference, see the Visitor pattern

Dries Van Hansewijck
Dries, are you certain about that? This pattern looks very useful, but I believe I would still need to implement `OnReadyToFly()` and `OnReadyToLand()` for every single class, because they are declared as `private`. How do I enforce that implementations are provided for both of these methods?
DanM
A: 

I will use extension methods to implement the behaviour as the code shows.

  1. Let Bird and Plane object implement a property for IFlyBehavior object for an interface IFlyer

    public interface IFlyer {
    public IFlyBehavior FlyBehavior }

    public Bird : IFlyer { public IFlyBehaviour FlyBehavior {get;set;} }

    public Airplane : IFlyer { public IFlyBehaviour FlyBehavior {get;set;} }

  2. Create an extension class for IFlyer

    public IFlyerExtensions {

    public void OnReadyToFly(this IFlyer flyer) 
    {
        flyer.FlyBehavior.Fly(); 
    }
    
    
    public void OnReadyToLand(this IFlyer flyer) 
    {
        flyer.FlyBehavior.Land(); 
    }
    

    }

Sachin
You forgot to use the IFlyer instance: *flyer*.FlyBehavior.Fly()
jeroenh
Thanks jeroenh!! Make the correction
Sachin
should read the question fully. private methods, dude. private.
Sky Sanders
@SkySanders : The question is whether mixins would be useful. My answer is Yes. Above, I am showing the best way of achieving behaviour with c# 3.5. Yes I am using public methods but you can avoid repititive code and add additional behaviour.
Sachin
A: 

Could you get this sort of behavior by using the new ExpandoObject in .NET 4.0?

Nick
Interesting, Nick. I don't have .NET 4.0 yet, so I can't experiment with it, but it sounds like what it does is change the "shape" of objects at runtime. That's very cool (I look forward to playing with it), and it very well might work, but it's not really what I'm attempting to do here. I mean, if I were going to go this route, I wonder if I wouldn't be even better off just doing some code-generation. I know the exact code I need at runtime, I just don't want to type it (or copy/paste it) a hundred times.
DanM
A: 

Scala traits were developed to address this kind of scenario. There's also some research to include traits in C#.

Jordão