We are having issues with a pattern, that is emerging in our C# solution.
Initial idea:
We have a set of features (mostly calculations), that are needed in several projects. We imagined our solution to be modular - each feature implemented as a class library which can than be referenced as a .dll in other projects.
First Issue:
What happened was, that libraries had classes, that specified the input data needed for doing the math. As a single library could be used in a number of projects we ended up coding mappings for each project, that ported the projects domain objects to the input data classes. This was tedious, as we were mostly doing a one-to-one conversion - the classes were basically the same.
Idea:
We figured that we would solve our problem with using interfaces instead of classes to specify our input data. That way we could simply label our domain classes with interfaces and we wouldn't have to do the mappings anymore.
Current Issue:
We now have a complete mayhem with interface definitions and the use of these interfaces in calculation methods. E.g.
public interface ILevel2Child
{
}
public interface ILevel1Child<TLevel2Child>
where TLevel2Child : ILevel2Child
{
List<TLevel2Child> Children { get; }
}
public interface IParent<TLevel1Child, TLevel2Child>
where TLevel1Child: ILevel1Child<ILevel2Child>
where TLevel2Child: ILevel2Child
{
List<TLevel1Child> Children { get; }
}
When we end up using the IParent interface in a method or interface, we keep dragging these insanely long signatures along.
Questions:
Was our idea of using interfaces bad to begin with?
If not, is something wrong with the way we specify our interfaces?
If still not, is there any way we can stop this insane signature pattern?
Additional explanation:
We started with
public interface ILevel2Child
{
}
public interface ILevel1Child
{
List<ILevel2Child> Children { get; }
}
public interface IParent
{
List<ILevel1Child> Children { get; }
}
but that prevented us from doing
public class Level2Child : ILevel2Child
{
}
public class Level1Child : ILevel1Child
{
List<Level2Child> Children { get; }
}
public class Parent : IParent
{
List<Level1Child> Children { get; }
}
and that was not acceptable.
Related
Starting with the use case.
Let's consider the base for this questions is a big framework and implementations of business objects of some software.
This software hast to be customized quite regularly, so it would be preferred that most of the C# objects are extendable and logic can be overriden. Even "model data".
The goal would be to be able to write code, create objects with input parameters - that may create more objects etc - and you don't have to think about whether those objects have derived implementations in any way. The derived classes will be used automatically.
For ease of uses a typesafe way to create the objects would be preferred as well.
A quick example:
public class OrderModel
{
public int Id { get; set; }
public string Status { get; set; }
}
public class CustomOrderModel : OrderModel
{
public string AdditionalData { get; set; }
}
public class StockFinder
{
public Article Article { get; }
public StockFinder(Article article)
{
Article = article;
}
public virtual double GetInternalStock() { /*...*/ }
public virtual double GetFreeStock() { /*...*/ }
}
public class CustomStockFinder : StockFinder
{
public bool UsePremiumAvailability { get; }
public CustomStockFinder(Article article, bool usePremiumAvailability)
: base(article)
{
UsePremiumAvailability = usePremiumAvailability;
}
protected CustomStockFinder(Article article) : this(article, false) { } // For compatibility (?)
public override double GetFreeStock() { /*...*/ }
}
In both cases I wanna do stuff like this
var resp = Factory.Create<OrderModel>(); // Creates a CustomOrderModel internally
// Generic
var finderGeneric = Factory.Create<StockFinder>(someArticle);
// Typesafe?
var finderTypesafe1 = Factory.StockFinder.Create(someArticle); // GetFreeStock() uses the new implementation
var finderTypesafe2 = Factory.StockFinder.Create(someArticle, true); // Returns the custom class already
Automatically generating and compiling C# code on build is not a big issue and could be done.
Usage of Reflection to call constructors is okay, if need be.
It's less about how complicating some code generation logic, written code analyzers, internal factories, builders etc are, and more about how "easy" and understandable the framework solution will be on a daily basis, to write classes and create those objects.
I thought about tagging the relevant classes with Attributes and then generating a typesafe factory class automatically on build step. Not so sure about naming conflicts, or references that might be needed to compile, as the constructor parameters could be anything.
Also, custom classes could have different constructors, so they should be compatible at each place in default code where they might be constructed already, but still create the custom object. In the custom code then you should be able to use the full custom constructor.
I am currently considering several different cases and possibilities, and can't seem to find a good solution. Maybe I am missing some kind of design pattern, or am not able to look outside of my bubble.
What would be the best design pattern or coding be to implement use cases like this?
I have a model that looks like this :
public class Task : ITask
{
public int DocumentId { get; set; }
public virtual Document Document { get; set; }
public TaskType TaskType { get; }
public string Value { get; }
}
Now, this class is directly registered as a DbSet in the DbContext.
This means that the Document property must be of concrete type. I want to make this code easily testable, so I want to have the property as an interface which is required by the ITask interface. What is the general way to approach this problem?
One way that comes to my mind is to put all such classes in a separate assembly but that seems a bit off.
Edit: The ITask interface is defined in a different assembly so it should not know about the Document type.
I would use EF models only for the data access layer and create a separate model for the business layer. The data access layer would be responsible for mapping the EF model to the business layer model and hand it to the business layer.
The business layer model can then also be immutable, which can have advantages. Also you can require all the properties to be e.g. not-null in you constructor and you can then rely on this throughout the whole business layer.
Of course you could argue that it's almost twice as much code to write. That's true, but IMO it results in cleaner code and therefore this is my preferred approach.
Interfaces can have properties defined in them, So your ITask can specify the document, like this:
public interface ITask {
Document Document { get; set; }
}
But you also say that you want the Document property as an interface and this becomes tricky as you need a concrete type in the Task class. Generic interfaces will help here.
// The interfaces
public interface ITask<TDocument> where TDocument : IDocument, new() {
TDocument Document { get; set; }
}
public interface IDocument {
int Number { get; set; } // Example property
}
//The classes
public class Document : IDocument{
public int Number { get; set; } // Example property
}
public class Task : ITask<Document> {
public Document Document { get; set; }
}
// See if it works
public class Test {
private Task myTask = new Task();
public void TestMethod() {
myTask.Document.Number = 1;
}
}
Remember, use the concrete types in DBContext.
As to where the interfaces should be located, same assembly or their own, there's quite a few viewpoints on that. Personally, I put them in their own assembly away from the implementing classes. This question is worth a read:
Should I have a separate assembly for interfaces?
One more comment, the class name Task is used in the .Net threading library, so maybe worth thinking about changing it to avoid potential confusion.
I am working on a mini-framework for "runnable" things. (They are experiments, tests, tasks, etc.)
// Something that "runs" (in some coordinated way) multiple "runnable" things.
interface IRunnableOf<T> where : IRunnable
// Provide base-class functionality for a "runner"
abstract class RunnerBase<T> : IRunnableOf<T>
class SequentialRunner<T> : RunnerBase<T> // Same interface, different behavior.
class ConcurrentRunner<T> : RunnerBase<T>
// other types of runners.
class ConcurrentBlockRunner : SequentialRunner<Block>
class SequentialBlockRunner : ConcurrentRunner<Block>
Now, how can I reconcile ConcurrentBlockRunner and SequentialBlockRunner? By this I mean:
Refer to them by a common ancestor, for use in a collection. (IEnuerable<T> where T = ??)
Provide additional base class functionality. (Add a property, for example).
I remedied #1 by adding another interface that just specified a type parameter to IA<T>:
interface IBlockRunner : IRunnableOf<Block> { }
And modified my ConcurrentBlockRunner and SequentialBlockRunner definitions to be:
class ConcurrentBlockRunner : SequentialRunner<Block>, IBlockRunner
class SequentialBlockRunner : ConcurrentRunner<Block>, IBlockRunner
Since ConcurrentBlockRunner and SequentialBlockRunner both use Block for their type parameter, this seems to be a correct solution. However, I can't help but feel "weird" about it, because well, I just tacked that interface on.
For #2, I want to add a couple pieces of common data to ConcurrentBlockRunner and SequentialBlockRunner. There are several properties that apply to them, but not to their only common base class, which is all the way up at RunnerBase<T>.
This is the first time while using C# that I've felt multiple inheritance would help. If I could do:
abstract class BlockRunnerBase {
int Prop1 { get; set; }
int Prop2 { get; set; }
class ConcurrentBlockRunner : SequentialRunner<Block>, BlockRunnerBase
class SequentialBlockRunner : ConcurrentRunner<Block>, BlockRunnerBase
Then I could simply add these extra properties to BlockRunnerBase, and everything would just work. Is there a better way?
I know I will be recommended immediately to consider composition, which I began to work with:
class BlockRunner : IBlockRunner {
IBlockRunner _member;
int Prop1 { get; set; } // Wish I could put these in some base class
int Prop2 { get; set; }
// Lots of proxy calls, and proxy events into _member
void Method() { _member.Method(); }
event SomeEvent
{
add { _member.SomeEvent += value; }
remove { _member.SomeEvent -= value; }
}
}
The problem I encountered (driving me to write this question) was that once you compose, you lose type compatibility. In my case, _member was firing an event, so the sender parameter was of type SequentialBlockRunner. However, the event handler was trying to cast it to type BlockRunner, which of course failed. The solution there is not use add/remove to proxy the events, but actually handle them, and raise an event of my own. So much work just to add a couple properties...
Composition over Inheritance, FTW!
To be more explicit:
class SequentialRunner<T> : RunnerBase<T>
should implement IRunnableOf<T> and proxy the RunnerBase<T> without inheriting it.
class SequentialRunner<T> : IRunnableOf<T>
{
private readonly RunnerBase<T> _runnerBase;
...
}
You can use extension methods to create mixin-like constructs, even with property-like elements.
I've also created an experiment with trait-like constructs in C#, NRoles.
But, all of these require non-standard coding, and will not be ideal for APIs that are meant to be exposed to third parties. I think you should try to rearrange your classes and use composition with delegation using interfaces if possible.
I'm looking to learn how to use interfaces and base classes effectively. I'm not exactly sure where to put common properties? Do only behaviors belong in an interface? If properties such as: Color and MinSpeed shouldn't go in the interface, where should they live? In an abstract class?
public interface IVehicle
{
void Speed();
void Clean();
void Stop();
}
public class Bmw : IVehicle
{
// Because these pertain to every vehicle no matter of maker,
// should these propertes go in the interface? Or in an abstract class?
public string Color { get; set; }
public int MinSpeed { get; set; }
#region IVehicle Members
public void Speed()
{
}
public void Clean()
{
}
public void Stop()
{
}
#endregion
}
Interfaces can be thought of as a contract that must be satisfied by any implementing class. Use it if you want to guarentee that all classes do the same thing—satisfy the same API—but you don't care how they do it. If properties are a part of that API, then by all means include them in your interface.
From your example above, if you want all cars to be guaranteed to have a color and minSpeed, then those properties belong in the interface. If those properties are specific to BMWs alone, then they belong in the BMW class. If those properties belong to some classes but not others, you could create a new interface extending the original one:
public interface IVehicleWithColorAndMinSpeed : IVehicle
{
string Color { get; set; }
int MinSpeed { get; set; }
}
(just don't get carried away with this)
Abstract classes are similar, but allow you to provide a default implementation for your sub classes.
Abstract classes tend to be easier to version, since you can add something new to your API, and provide a default implementation that your existing subclasses will automatically pick up; adding something to an interface immediately breaks all existing classes which implement that interface.
The 'right' answer is entirely dependent on your domain model. What is the problem you're trying to solve? There is no 'right' answer other than the one which solves the particular problem at hand with the greatest:
understandability
maintainability
brevity
isolation
performance
You can probably consider most of those properties to be in order of importance, but they mean different things to different people and there's probably a lot of debate implied there too.
Can you tell us any more about the particular application you imagine these classes to serve?
Yesterday 2 of the guys on our team came to me with an uncommon problem. We are using a third-party component in one of our winforms applications. All the code has already been written against it. They then wanted to incorporate another third-party component, by the same vender, into our application. To their delight they found that the second component had the exact same public members as the first. But to their dismay, the 2 components have completely separate inheritance hierarchies, and implement no common interfaces. Makes you wonder... Well, makes me wonder.
An example of the problem:
Incompatible Types http://www.freeimagehosting.net/uploads/f9f6b862f1.png
public class ThirdPartyClass1
{
public string Name
{
get
{
return "ThirdPartyClass1";
}
}
public void DoThirdPartyStuff ()
{
Console.WriteLine ("ThirdPartyClass1 is doing its thing.");
}
}
public class ThirdPartyClass2
{
public string Name
{
get
{
return "ThirdPartyClass2";
}
}
public void DoThirdPartyStuff ()
{
Console.WriteLine ("ThirdPartyClass2 is doing its thing.");
}
}
Gladly they felt copying and pasting the code they wrote for the first component was not the correct answer. So they were thinking of assigning the component instant into an object reference and then modifying the code to do conditional casts after checking what type it was. But that is arguably even uglier than the copy and paste approach.
So they then asked me if I can write some reflection code to access the properties and call the methods off the two different object types since we know what they are, and they are exactly the same. But my first thought was that there goes the elegance. I figure there has to be a better, graceful solution to this problem.
My first question was, are the 2 third-party component classes sealed? They were not. At least we have that.
So, since they are not sealed, the problem is solvable in the following way:
Extract a common interface out of the coinciding members of the 2 third-party classes. I called it Icommon.
public interface ICommon
{
string Name
{
get;
}
void DoThirdPartyStuff ();
}
Then create 2 new classes; DerivedClass1 and DerivedClass2 that inherit from ThirdPartyClass1 and ThirdPartyClass2 respectively. These 2 new classes both implement the ICommon interface, but are otherwise completely empty.
public class DerivedClass1
: ThirdPartyClass1, ICommon
{
}
public class DerivedClass2
: ThirdPartyClass2, ICommon
{
}
Now, even though the derived classes are empty, the interface is satisfied by the base classes, which is where we extracted the interface from in the first place.
The resulting class diagram looks like this.
alt text http://www.freeimagehosting.net/uploads/988cadf318.png
So now, instead of what we previously had:
ThirdPartyClass1 c1 = new ThirdPartyClass1 ();
c1. DoThirdPartyStuff ();
We can now do:
ICommon common = new DerivedClass1 ();
common. DoThirdPartyStuff ();
And the same can be done with DerivedClass2.
The result is that all our existing code that referenced an instance of ThirdPartyClass1 can be left as is, by just swapping out the ThirdPartyClass1 reference for a ICommon reference. The ICommon reference could then be given an instance of DerivedClass1 or DerivedClass2, which of course in turn inherits from ThirdPartyClass1 and ThirdPartyClass2 respectively. And all just works.
I do not know if there is a specific name for this, but to me it looks like a variant of the adaptor pattern.
Perhaps we could have solve the problem with the dynamic types in C# 4.0, but that would have not had the benefit of compile-time checking.
I would be very interested to know if anybody else has another elegant way of solving this problem.
If you're using .Net 4 you can avoid having to do alot of this as the dynamic type can help with what you want. However if using .Net 2+ there is another (different way) of achieving this:
You can use a duck typing library like the one from Deft Flux to treat your third party classes as if they implemented an interface.
For example:
public interface ICommonInterface
{
string Name { get; }
void DoThirdPartyStuff();
}
//...in your code:
ThirdPartyClass1 classWeWishHadInterface = new ThirdPartyClass1()
ICommonInterface classWrappedAsInterface = DuckTyping.Cast<ICommonInterface>(classWeWishHadInterface);
classWrappedAsInterface.DoThirdPartyStuff();
This avoids having to build derived wrapper classes manually for all those classes - and will work as long as the class has the same members as the interface
What about some wrappers?
public class ThirdPartyClass1 {
public string Name {
get {
return "ThirdPartyClass1";
}
}
public void DoThirdPartyStuff() {
Console.WriteLine("ThirdPartyClass1 is doing its thing.");
}
}
public interface IThirdPartyClassWrapper {
public string Name { get; }
public void DoThirdPartyStuff();
}
public class ThirdPartyClassWrapper1 : IThirdPartyClassWrapper {
ThirdPartyClass1 _thirdParty;
public string Name {
get { return _thirdParty.Name; }
}
public void DoThirdPartyStuff() {
_thirdParty.DoThirdPartyStuff();
}
}
...and the same for ThirdPartyClass2, then you use the wrapper interface in all your methods.
Add an interface. You could add one wrapper (that implements the interface) for each of the 3rd parties.
Anyway, if you have the code of those 3rd parties, you could skip the wrapper thing and directly implement the interface. I'm quite sure you don't have the source, though.