I'm trying to design a class hierarchy in C# to properly model my application model.
The problem is I'm not sure which is the right way to do it.
Let's say I have an Order class which is supposed to be the base (abstract) class for all order types and the reference type I'm working with when using orders. The order class has only a single 'important' method: let's call it order.PlaceOrder(), but there are multiple (orthogonal) requirements that an order might have to do (or not do): log the placing of the order, place the order asynchronously (PlaceOrder method returns immediately) and others.
Now, I want to make actual concrete classes which can support any number of these requirements. For example:
class GoogleOrder : LoggedOrder, AsyncOrder, etc
class AppleOrder: AsyncOrder
class MicrosoftOrder : Order
The question is: if I want to create such a class by deriving from all the "strategies", then they all (but one) have to be interfaces, whereas I wish to inherit actual implementation and avoid copy/pasting of code, and I'm not sure how to do it.
I come from a C++ background, where I could just derive from multiple base classes (or possibly use a policy based design, like Andrei Alexandrescu describes in his book), but in C# I'm not sure how to do it, even though this seems like a very general question, one which I should know by now.
Any help is greatly appreciated!
It seems like your design calls for "Decorator pattern", Decorator pattern gives flexibility to add responsibilities/roles dynamically and with different combinations however you like instead of using inheritance.
here are example on how to implement decorator:
http://alagesann.com/2013/08/16/decorator-pattern-made-easy/
http://en.wikipedia.org/wiki/Decorator_pattern
hope that helps.
here is the sample code for your scenario. see if it helps.
public abstract class Order
{
public abstract void PlaceOrder(); // log the placeing of the ordr, place the order asynchronously
}
public class MicrosoftOrder : Order // default order
{
public void PlaceOrder()
{
// default implementation for placing order.
}
}
public class AppleOrder : Order // for asycn functionalities.
{
private Order order;
public AppleOrder(Order order)
{
this.order = order;
}
public void PlaceOrder()
{
// Implement async functionalities.
// you can also call default order as
// order.PlaceOrder();
}
}
public class GoogleOrder : Order // logged order
{
private Order order;
public GoogleOrder(Order order)
{
this.order = order;
}
public void PlaceOrder()
{
// Implement logged order
// you can also call default order as
// order.PlaceOrder();
}
}
class Program
{
static void Main(string[] args)
{
Order order = new MicrosoftOrder();
order.PlaceOrder(); // Default Order;
Order orderWithAsync = new AppleOrder(order);
orderWithAsync.PlaceOrder(); // Place order with asycn
Order orderWithAsyncAndlogging = new GoogleOrder(orderWithAsync);
orderWithAsyncAndlogging.PlaceOrder(); // order with asynch and logging.
}
}
Related
I'm trying to model a production system with "facility" as Class and some subclasses down to "Activity". The facility has a name as only parameter (at the moment), and I'd like to create an instance of the class reading the name as an input from a textbox. Since "activity" is inherit the properties from it's "parent classes" I'll create an instance of the class "activity" and not it's parent.
The problem is that I don't know where to create the class and how to pass it so that when I add the first subclass "Workstation" I can edit the properties of the same "activity" I created earlier.
I don't really have any code to add at this point unfortunately, but please tell me if there's anything special you'd like to see and I'll try to add it to the post.
And by the way, it's in the shape of a WinForm application with a GUI I'm trying to do this.
There are a couple things to note here. First, you'll want to use the Composite pattern to encapsulate the relationships between your classes. (For those who don't understand the OP's type hierarchy, it does make perfect sense in a factory context. There are many activities going on, which can be grouped into workstations and at a higher level into facilities.)
So, you should probably have a base Activity class (that supports the Composite pattern by exposing a collection of child activities), and then your "levels" (like Facility and Workstation) will inherit from Activity. Each of these classes will have unique properties.
The following classes should be created in their respective files, e.g. Activity.cs, Factory.cs, Workstation.cs:
class Activity
{
// An attribute that every Activity may need: a displayable name.
// This might be useful if you have a TreeView, e.g., showing all the activities.
public string Name { get; private set; }
// Every Activity could have child activities - this is the Composite pattern.
// You can loop through these to navigate through the hierarchy of your data.
// (This is often done using recursion; see example below with GetAllWorkstations().)
public List<Activity> ChildActivities { get; private set; }
public Activity()
{
ChildActivities = new List<Activity>();
}
public override string ToString() { return Name; }
}
class Factory : Activity
{
public string City { get; private set; }
public string Address { get; private set; }
}
class Workstation : Activity
{
public string WorkstationNumber { get; private set; }
}
The responsibility of loading your model then has to be handled somewhere. A good place to do it is in your main form. For example, you might write code like this:
class MainForm : Form
{
private readonly List<Factory> topLevelFactoryActivities;
public MainForm()
{
// ... other code
topLevelFactoryActivities = LoadTopLevelFactoryActivities();
}
private IEnumerable<Factory> LoadTopLevelFactoryActivities()
{
var factories = new List<Factory>();
// TODO: Load the factories, e.g. from a database or a file.
// You can load all the child objects for each factory here as well,
// or wait until later ("lazy-loading") if you want to.
// NOTE: If this becomes complex, you can move the LoadTopLevelFactoryActivities()
// method to its own class, which then becomes your "data access layer" (DAL).
return factories;
}
}
Now, if you want to find all the workstations that are part of a particular factory, you would write a method like the following on the Factory class:
class Factory : Activity
{
// ... other code
public IEnumerable<Workstation> GetAllWorkstations()
{
return GetWorkstationsRecursive(this);
}
private IEnumerable<Workstation> WorkstationsIn(Activity parentActivity)
{
foreach (var workstation in parentActivity.ChildActivities.OfType<Workstation>)
{
// Uses a C# feature called 'iterators' - really powerful!
yield return workstation;
}
foreach (var childActivity in parentActivity.ChildActivities)
{
// Using recursion to go down the hierarchy
foreach (var workstation in WorkstationsIn(childActivity))
{
yield return workstation;
}
}
}
}
You would call it like so, e.g. in your main form:
class MainForm : Form
{
// ... other code
public MainForm()
{
// ... other code
// Assume this is assigned to the factory that you want to get all the workstations for
Factory myFactory;
var workstations = myFactory.GetAllWorkstations();
// Now you can use 'workstations' as the items source for a list, for example.
}
}
As an example use case, you might want to show a second form (that belongs to the main form) which shows a list of all the workstations. (In practice you probably shouldn't create too many windows; prefer building a nonoverlapping layout. But just to show how you might pass the model instances around...)
class WorkstationListForm : Form
{
private IEnumerable<Workstation> workstations;
public WorkstationListForm(IEnumerable<Workstation> workstations)
{
this.workstations = workstations;
//TODO: You can now use 'workstations' as the ItemsSource of a list view in this form.
}
}
You could, of course, make topLevelFactoryActivities public on your MainForm and pass the variable this of the MainForm to the WorkstationListForm constructor instead. Then you could access the member on MainForm like this:
public WorkstationListForm(MainForm mainForm)
{
var topLevelFactoryActivities = mainForm.topLevelFactoryActivities;
// Now WorkstationListForm has full access to all the data on MainForm. This may or
// may not be helpful (it's usually best to minimize sharing and public fields).
}
Second, you'll want to use a proper separation between your view (user interface code/classes) and your model (the Activity hierarchy).
Third, if there's going to be any kind of live data being pushed to the user interface then you'll need a databinding mechanism to automatically update the view whenever the model changes.
In general, #2 & #3 are popularly addressed via the Model-View-ViewModel pattern. There is an excellent tutorial here for building an MVVM app using WinForms/C#.
That should get you started, at least. Also see an answer to a similar question. (Sorry about promoting my own answer, but I don't want to type out the whole example twice. Please forgive me. :))
I have a class which takes multiple collections, and then needs to perform calculations on these collections in a particular order. E.G.
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void CalcCols(){
//here, I will 'zip' col1/col2 to create List<double> for each
}
public void CalcStep2(){
//this is dependent on the results from CalcCols()
}
public void CalcNonDependent(){
//this can be called at any stage
}
}
The constructor forces the client to supply the relevant data, so there's an obvious ways to do this, by calling the methods in the constructor, this way, I know that everything will be populated. But, this doesn't seem like a clean solution, especially when I want to unit test parts of the code.
If I want to unit test CalcNonDependent(), I need to fully initialize the object, when I might not even require the result of the other two calculations.
So, my question, is there a pattern that can be used for this particular scenario; I have looked at Chain of Responsibility & Command Pattern, but wondered if anyone has any suggestions
Have you looked at Template? Not sure if it applies to your situation 100% but you would have a base class which defines 3 abstract methods and then calls them in the correct order.
class SomeBaseClass
{
public abstract void CalcCols();
public abstract void CalcStep2();
public abstract void CalcNonDependent();
public void DoAllCalculations()
{
CalcCols();
CalcStep2();
CalcNonDependent();
}
}
Then you inherit from this class and provide concrete implementations of your calculation methods.
I recommend concentrating on code coverage rather than method coverage. This way you can make the methods private and expose a single method that calls all 3 methods providing 100% coverage for the class. If you are concerned with dividing the tests for performance reasons then you can further subdivide the tests into groups which perform nightly long running tests vs daily/with every checkin tests.
The command pattern isn't going to solve much in the way of making the class more test-able. I would use such a pattern if you needed runtime workflow adaptation (E.G. M1(), M2(), then M2(), M1(), then M2(), M3() etc).
For example,
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void DoWork()
{
//Run methods in order.
}
private void CalcCols(){
//here, I will 'zip' col1/col2 to create List<double> for each
}
private void CalcStep2(){
//this is dependent on the results from CalcCols()
}
private void CalcNonDependent(){
//this can be called at any stage
}
}
You seem to be making a complicated problem out of nothing. Just change the class to:
public class ClassCalc
{
public ClassCalc(double varEm,
List<List<double>> col1,
List<List<double>> col2)
{
//set fields etc.
}
public void CalcCols()
{
//here, I will 'zip' col1/col2 to create List<double> for each
CalcStep2();
}
public void CalcNonDependent()
{
//this can be called at any stage
}
private void CalcStep2()
{
}
}
If for CalcStep2 it is necessary that CalcCols has been executed, why not keep a flag to keep track of it, and include in CalcStep2 something like
if (!CalcColsHasBeenDone)
CalcCols();
Of course, don't forget to set CalcColsHasBeenDone to true at the end of CalcCols :)
You might want to extract an interface for your public operation, and expose only a single public method through it.
Using this in conjunction with e.g. P.Brian.Mackey's answer will make the other methods invisible from a clients perspective, while they can still be public in the implementing class, thus allowing for unit testing if needed.
This class injects all dependencies in the constructor, but only one of the dependencies are used at a time. Is this considered bad design?
public class OrderPayment
{
ICreditCardPayment _ccPayment;
ICashPayment _cashPayment;
public OrderPayment(ICreditCardPayment ccPayment, ICashPayment cashPayment)
{
_ccPayment = ccPayment;
_cashPayment = cashPayment;
}
private void PrepareOrder(Order order)
{
// Do stuff with the order
}
public PaymentResult PayByCreditCard(Order order)
{
PrepareOrder(order);
return _ccPayment.Pay(order);
}
public PaymentResult PayByCreditCard(Order order)
{
PrepareOrder(order);
return _cashPayment.Pay(order);
}
}
An alternative is this:
public class OrderPayment
{
private void PrepareOrder(Order order)
{
// Do stuff with the order
}
public PaymentResult PayByCreditCard(Order order, ICreditCardPayment ccPayment)
{
PrepareOrder(order);
return ccPayment.Pay(order);
}
public PaymentResult PayByCreditCard(Order order, ICashPayment cashPayment)
{
PrepareOrder(order);
return cashPayment.Pay(order);
}
}
This one complicates the function call somewhat. Would you use the first, cleaner looking one, even though not every constructor parameter is used? Considering a DI framework has to instantiate potentially heavy classes even though they may not all be used, I'm not sure how good this is.
So which one would you use? Or maybe a different implementation?
I would refactor or extract a common interface from ICashPayment and ICreditCardPayment. Your code sample indicates your methods are both invoking xPayment.Pay, which looks like a good candidate for your common interface method.
public interface IPayment
{
PaymentResult Pay(Order order);
}
Your more specialized interfaces can inherit from and build upon it.
In general, I would avoid having constructors (or any method) accept arguments that go unused, or if one argument is used, the other is not. That's normally an indication that you are either not operating at the proper level of abstraction, or that your class/method has too many responsibilities.
You need an operation that requires all of the following:
the payment method
the amount being paid
the order that is being paid for
What processing needs to be done prior to payment, based on the order, and amount being paid
You are trying to define some order of operation independent of what is being performed in the operation. Dependency injection can be used at the method level too.
you need a method like this one:
public PaymentResult Pay(Amount amount, Order order, IOrderService orderService,
IPaymentService paymentService) {
var updatedOrder = orderService.Process(order); // don't alter the original in
// case you need to roll back
var result = paymentService.Pay(amount, updatedOrder);
return result; // this result should include the updated order, so that the system
// can determine what to do upon successful payment
}
I previously posted this, but I guess it was too verbose and irrelevant. My question is also like this. One poster in the second link said the answer (of why you can't do the code below) was a problem of design, specifically "bad use of inheritance". So I'd like to check this issue again with the experts at StackOverflow and see if this is really an issue of "bad inheritance" - but more importantly, how to fix the design.
Like the poster, I'm also confused about the Factory method and how I can apply it. It seems the factory method is for multiple concrete classes that have the exact same implementation as the abstract base class and do not add their own properties. But, as you will see below, my concrete classes build upon the abstract base class and add extra properties.
The Base Class We Build Upon:
public abstract class FlatScreenTV
{
public string Size { get; set; }
public string ScreenType { get; set; }
}
Extension Class Examples:
public class PhillipsFlatScreenTV : FlatScreenTV
{
// Specific to Phillips TVs. Controls the backlight intensity of the LCD screen.
public double BackLightIntensity { get; set; }
}
public class SamsungFlatScreenTV : FlatScreenTV
{
// Specific to Samsung TVs. Controls the time until the TV automatically turns off.
public int AutoShutdownTime { get; set; }
}
Let's say there are more extension classes for more brands of flat screen TVs. And then, let's say we stick them all into a generic List:
public static void Main()
{
List<FlatScreenTV> tvList = new List<FlatScreenTV>();
tvList.Add(new PhillipsFlatScreenTV());
tvList.Add(new SamsungFlatScreenTV());
tvList.Add(new SharpFlatScreenTV());
tvList.Add(new VizioFlatScreenTV());
FlatScreenTV tv = tvList[9]; // Randomly get one TV out of our huge list
}
The Problem:
I want to access the specific properties of whatever 'original' brand TV this variable belongs to. I know the brand because if I call tv.GetType(), it returns the correct 'original' type - not FlatScreenTV. But I need to be able to cast tv from FlatScreenTV back to its original type to be able to access the specific properties of each brand of flat-screen TVs.
Question #1: How can I dynamically cast that, properly - without makeshift hacks and huge if-else chains to brute-guess the 'original' type?
After browsing around similar design issues, most answers are: you can't. Some people say to look at the Factory Pattern, and others say to revise the design using interfaces, but I don't know how to use either to solve this problem.
Question #2: So, how should I design these classes so that I can access the original type's specific properties in the context above?
Question #3: Is this really bad inheritance?
Your design violates the "Liskov Substitution Principle". In other words, the code that deals with items from your list of FlatScreenTV shouldn't know or care what derived type is.
Say your code needs to create a custom remote control GUI. It might be enough to simply know the names and types of the properties of each TV to auto-generate the UI. In which case you could do something like this to expose the custom properties from the base class:
public abstract class FlatScreenTV
{
public FlatScreenTV()
{
CustomProperties = new Dictionary<string,object>();
}
public Dictionary<string,object> CustomProperties { get; private set; }
public string Size { get; set; }
public string ScreenType { get; set; }
}
public class PhillipsFlatScreenTV : FlatScreenTV
{
public PhillipsFlatScreenTV()
{
BackLightIntensity = 0;
}
// Specific to Phillips TVs. Controls the backlight intensity of the LCD screen.
public double BackLightIntensity
{
get { return (double)CustomProperties["BackLightIntensity"]; }
set { CustomProperties["BackLightIntensity"] = value; }
}
}
public class SamsungFlatScreenTV : FlatScreenTV
{
public SamsungFlatScreenTV()
{
AutoShutdownTime = 0;
}
// Specific to Samsung TVs. Controls the time until the TV automatically turns off.
public int AutoShutdownTime
{
get { return (int)CustomProperties["AutoShutdownTime"]; }
set { CustomProperties["AutoShutdownTime"] = value; }
}
}
If you really do need to be working directly with the derived types, then you should instead consider moving to a plugin based architecture. For example, you might have a factory method like this:
IRemoteControlGUI GetRemoteControlGUIFor(FlatScreenTV tv)
which would scan your plugins and find the one that knew how to build the UI for the particular type of FlatScreenTV you passed in. This means that for every new FlatScreenTV you add, you also need to create a plugin that knows how to make its remote control GUI.
Factory Pattern would be the best way to go
I can offer a partial answer:
Firstly read up on Liskov's Substitution Principle.
Secondly you are creating objects that inherit from FlatScreenTV, but apparently for no purpose as you want to refer to them by their SubType (SpecificTVType) and not their SuperType (FlatScreenTV) - This is bad use of Inheritance as it is NOT using inheritance lol.
If your code wants to access properties particular to a given type, then you really want this code encapsulated within that type. Otherwise everytime you add a new TV type, all the code that handles the TV list would need to be updated to reflect that.
So you should include a method on FlatScreenTV that does x, and override this in TV's as required.
So basically in your Main method above, instead of thinking I want to be dealing with TVTypeX, you should always refer to the basetype, and let inheritance and method overriding handle the specific behaviour for the subtype you are actually dealing with.
Code eg.
public abstract class FlatScreenTV
{
public virtual void SetOptimumDisplay()
{
//do nothing - base class has no implementation here
}
}
public class PhilipsWD20TV
{
public int BackLightIntensity {get;set;}
public override void SetOptimumDisplay()
{
//Do Something that uses BackLightIntensity
}
}
"the factory method is for multiple concrete classes that have the exact same implementation as the abstract base class [interface] and do not add their own properties."
No, speaking more practical, than theorical, the factory method can provide you with objects of concrete classes, in which the concrete classes, must have some common methods and interfaces, but, also some additional specific attributes.
Sometimes I use a method that creates the same class object every time I called, and I need to call it several times, and sometimes I use a method that create several different class objects, and that maybe be confusing, maybe another question.
And, your further comment about a switch sentence, with many options, when using the factory pattern, you usually provide an identifier for the concrete class / concrete object. This can be a string, an integer, an special type id, or an enumerated type.
You could use an integer / enum ID instead, and use a collection to lookup for the concrete class.
You can still leverage a factory. The point of a factory IMO is to put all the heavy lifting of constructing your various TVs in one place. To say categorically "a factory is for multiple concrete classes that have the exact same implementation as the abstract base class" is forgetting about polymorphism.
There is no law that says you cannot use a factory pattern because the sub classes declare unique properties and methods. But the more you can make use of polymorphism, the more a factory pattern makes sense. Also as a general guideline, IMHO, the more complexity that must go into constructing from the base the better off you are in the long run using a factory because you are "encapsulating change" - that is, constructing concrete classes is likely to change due to differing requirements and inherent construction complexity (a design analysis decision, to be sure) . And that change is in a single class - the factory.
Try this: Define everything in the abstract class and then for a given TV subclass either write concrete-specific code, and for those that don't apply write some standard "I don't do that" code.
Think about all the things your TVs do in generic terms: turn on, turn off, etc. Write a virtual method shell in the base class for all the generic things a TV does - this is a simple example of the template method pattern by the way. Then override these in the concrete classes as appropriate.
There are other things you can do in the base class to make it more fundgeable (that's a technical term meaning "reference subclasses as the base class, but do sub-classy things").
Define delegate methods (very powerful yet under-utilized)
use params[] for dynamic method parameter lists
Make Property delegates
Static methods
Declare Properties and methods "abstract" - forces sub-class implementation, vis-a-vis "virtual"
Hide inherited stuff in the sub class (generally using "new" keyword to communicate that it's on purpose)
If construction parameters are numerous or complex, create a class specifically designed to pass configuration to the factory's build method.
public class TVFactory {
public TV BuildTV(Brands thisKind) {
TV newSet;
switch (thisKind) {
case Brands.Samsung :
Samsung aSamsungTV = new Samsung();
aSamsungTV.BacklightIntensity = double.MinVal;
aSamsungTV.AutoShutdownTime = 45; //oops! I made a magic number. My bad
aSamsungTV.SetAutoShutDownTime = new delegate (newSet.SetASDT);
newSet = aSamsungTV;
break;
. . .
} // switch
}
//more build methods for setting specific parameters
public TV BuildTV (Brands thisKind, string Size) { ... }
// maybe you can pass in a set of properties to exactly control the construction.
// returning a concrete class reference violates the spirit of object oriented programming
public Sony BuildSonyTV (...) {}
public TV BuildTV (Brands thisKind, Dictionary buildParameters) { ... }
}
public class TV {
public string Size { get; set; }
public string ScreenType { get; set; }
public double BackLightIntensity { get; set; }
public int AutoShutdownTime { get; set; }
//define delegates to get/set properties
public delegate int GetAutoShutDownTime ();
public delegate void SetAutoShutDownTime (object obj);
public virtual TurnOn ();
public virtural TurnOff();
// this method implemented by more than one concrete class, so I use that
// as an excuse to declare it in my base.
public virtual SomeSonyPhillipsOnlything () { throw new NotImplementedException("I don't do SonyPhillips stuff"); }
}
public class Samsung : TV {
public Samsung() {
// set the properties, delegates, etc. in the factory
// that way if we ever get new properties we don't open umpteen TV concrete classes
// to add it. We're only altering the TVFactory.
// This demonstrates how a factory isolates code changes for object construction.
}
public override void TurnOn() { // do stuff }
public override void TurnOn() { // do stuff }
public void SamsungUniqueThing () { // do samsung unique stuff }
internal void SetASDT (int i) {
AutoShutDownTime = i;
}
}
// I like enumerations.
// No worries about string gotchas
// we get intellense in Visual Studio
// has a documentation-y quality
enum Brands {
Sony
,Samsung
,Phillips
}
I have some classes inherit from existing Windows Controls like TextBox and DateTimePicker, ..etc
I want to add custom functionalities for these classes like (Read, Alert, ...etc)
these added functionalities are the same in all these classes
The problem is: these classes inherited from difference parents so I can't put my added functionalities in the parent class,
What's the best practice in this case:
repeat the code in each inherited
class
Use a separated class have the
functionalities as Static Methods
with parameter from an interface, implement this interface for the classes and
then pass them.
Use a separated class like the second approach but with Dynamic parameter (which added in C# 4.0)
or other !!
Thanks in advance
I'd consider option 4: composition.
First, define your set of functionality. We'll assume that your partial list is exclusive, so "Read" and "Alert."
Second, create a single class that implements this functionality, something like MyCommonControlBehaviors. I'd prefer this implementation not be static if possible, though, it may be generic.
public MyCommonControlBehaviors
{
public Whatever Read() { /* ... */ }
public void Alert() {}
}
Third, use composition to add an instance of this class to each of your custom control types and expose that functionality through your custom control:
public class MyCustomControl
{
private MyCommonControlBehaviors common; // Composition
public Whatever Read() { return this.common.Read(); }
public void Alert() { this.common.Alert(); }
}
Depending on specifics, you can get creative to the degree necessary. E.g., perhaps your custom behaviors need to interact with private control data. In that case, make your control implement a common ICommonBehaviorHost interface that your common behaviors need. Then pass the control into the behavior class on construction as an instance of ICommonBehaviorHost:
public interface ICommonBehaviorHost
{
void Notify();
}
public class MyCommonControlBehaviors
{
ICommonBehaviorHost hst = null;
public MyCommonControlBehaviors(ICommonBehaviorHost host)
{
this.hst = host;
}
public void Alert() { this.hst.Notify(); } // Calls back into the hosting control
// ...
}
public class MyCustomControl : ICommonBehaviorHost
{
private MyCommonControlBehaviors common = null;
public MyCustomControl() { common = new MyCommonControlBehaviors(this); }
public Whatever Read() { return this.common.Read(); }
public void Alert() { this.common.Alert(); }
void ICommonBehaviorHost.Notify() { /* called by this.common */ }
}
Use Composition instead of Inheritence!
If you must, what I would probably do is create extension methods for each class and then reference the actual coded needed for these in some other object all the extension methods can call.
This way the code isn't duplicated, and the extension methods make it look like the methods should be in the object.
It's the same essentially by creating a static method and doing: Functions.DoSomething(my_Object);
But I always like: my_Object.DoSomething() better in an OO language.
I would suggest defining an interface for the behaviors, and then (to keep from repeating yourself) create extension methods on that interface definition for your shared methods. (Kinda like your second option, only with extension methods instead of totally static methods).