Consider the following interfaces in C#:
public interface IUpgradeable
{
public void Upgrade();
}
public interface ISpeedUpgradeable : IUpgradeable
{
public int GetCurrentSpeed();
}
public interface IDamageUpgradeable : IUpgradeable
{
public float GetCurrentDamage();
}
And the following class that implements them:
public class SpaceShip : ISpeedUpgradeable, IDamageUpgradeable
{
public int GetCurrentSpeed()
{
return 0;
}
public float GetCurrentDamage()
{
return 0f;
}
public void Upgrade()
{
//Which Upgrade am I implementing? ISpeedUpgradeable? or IDamageUpgradeable?
}
}
Since both ISpeedUpgradeable and IDamageUpgradeable both extend IUpgradeable, shouldn't they both have implementations of Upgrade() each? or am I misunderstanding how inheritance in interfaces work?
There is only one meaning of IUpgradeable. The fact that multiple interfaces inherit it, and add meaning to themselves doesn't change the meaning of the original interface. Your class simply implements ISpeedUpgradeable, IDamageUpgradeable, and IUpgradeable: it doesn't implement a specific flavor of IUpgradeable.
The Upgrade() method should only mean what it means to the IUpgradeable interface. Think about your business model (or in this case probably a game model): is there an item floating around that "upgrades" anything upgradeable that it comes in contact with? Does upgrading the ship mean upgrading its speed, or damage, or both? If simply calling Upgrade doesn't provide enough information to match the way your business model works, you may need to re-think your interface design.
I have some interfaces that need some simple implementation, but I have a handful of them, like for instance (not actual code, just example)
interface ISelectable
{
public bool IsSelected;
public void Select();
}
public class Selectable : ISelectable
{
public bool IsSelected {get;set}
public void Select()=> IsSelected = true;
}
Then I might have IStorable, which allows storing stuff in the database, like:
public interface IStorable
{
public void Store();
...
}
public class Storable : IStorable
{
private stuff...
public void Store() { storing code }
}
The question is:
I have
elements that are IStorable but not ISelectable,
elements that are ISelectable and no IStorable,
and elements that are both.
Actually... I have MORE of these classes. So the combinations grow fast.
As far as I know, the only way to share the code is to have a base class implement the interface, then your class inherits from this base class. Like:
public class GameCard : Selectable { ....
But this would mean that the only way to have a class that inherits the code for Selectable, and the code for Storable is to have a base class doing both, something like public class StorableAndSelectable: IStorable, ISelectable But this makes no sense, especially when you want to have different storing methods...
What's the proper way to have your classes share the implementation code of the interfaces it implements? Having the implementation for each of them in one file, and feeding this "file" to all classes that need it?
I would consider if inheritance is the correct approach for such simple properties. There are some possible alternatives. Using inheritance to include functionality is called implemention inheritance and is generally frowned upon. For simple stuff like this it provides little benefit, and for more complicated logic it ties the derived class to the base class to tightly.
To store an object I would probably suggest the repository pattern, that way you do not need a special interface.
To handle things like if a object is selected, the easiest option is probably just to have a settable property in the interface: bool IsSelected {get;set;}. This is trivially implementable by all derived classes, there is no real advantage of a implementation of just that interface, at least not outside of testing/dummy objects.
In some cases you can use a Func<T, bool> to describe how to determine if some arbitrary type is selected. In some cases it might be useful to use composition, i.e. use a separate class to describe selection, and have your game objects contain a property of this class.
Starting from C# 8.0 you can have default method implementation in interface definition
interface IA
{
void M() { WriteLine("IA.M"); }
}
class C : IA { } // OK
IA i = new C();
i.M(); // prints "IA.M"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
According to your classes you can do something like this
interface ISelectable
{
public bool IsSelected;
public void Select() => IsSelected = true;
}
I have two interfaces implemented by one main class. How can i refactor my code in a way that on implementing each contract, the methods of each contract has a different value for a parameter such as DatabaseName.
Example :
Class1 Implements Interface1,Interface2
Interface1.GetData() has DatabaseName set to Database 1
Interface2.GetData() has DatabaseName set to Database 2
I can configure those value in the methods GetData() but i want a cleaner way of doing it.
Any pattern recommendation be that DI ,Domain driven ,even basic inheritance example which accomplishes the above is what i am looking for.
It sounds like all you need is explicit interface implementation:
public class Class1 : Interface1, Interface2
{
// Note the lack of access modifier here. That's important!
Data Interface1.GetData()
{
// Implementation for Interface1
}
Data Interface2.GetData()
{
// Implementation for Interface2
}
}
Obviously the two methods can call a common method with a parameter to specify the database name or similar.
Refactoring is usually motivated by noticing a code smell and the very fact that you ended up in a situation where you have to implement 2 abstraction which expose similar functionality is the code smell.
Without having more understanding of the problem I might not be able to provide you a conclusive answer but with limited understanding this is what I would propose. Have 2 different concrete implementation each implementing one interface and have a factory which would be injected to client and make the client make the deliberate decision which one of these implementation is needed. In case these concrete classes share common functionality you can always abstract that into a common parent class.
public interface ISQLReader
{
string GetData();
}
public interface IOracleReader
{
string GetData();
}
public abstract class Reader
{
protected void CommonFunctionaility()
{
}
}
public class MSSQLReader : Reader, ISQLReader
{
public string GetData()
{
return "MSSQL";
}
}
public class OracleReader : Reader, IOracleReader
{
public string GetData()
{
return "Oracle";
}
}
public interface IReaderFactory
{
OracleReader CreateOracleReader();
MSSQLReader CreateMSSQLReader();
}
public class ReaderFactory : IReaderFactory
{
public MSSQLReader CreateMSSQLReader() => new MSSQLReader();
public OracleReader CreateOracleReader() => new OracleReader();
}
public class ReaderClient
{
private IReaderFactory _factory;
public ReaderClient(IReaderFactory factory)
{
this._factory = factory;
}
}
Explicit interface implementation is technique that should restrict usage of the functionality until the client has made and explicit cast there by making a deliberate decision.
I'm starting to see this pattern appear often in my code:
class Foo { }
interface IBar
{
Foo Foo { get; }
}
class Bar<TFoo> : IBar where TFoo : Foo
{
public TFoo Foo { get; private set; }
Foo IBar.Foo
{
get
{
return Foo;
}
}
}
Some of its benefits are:
An easy way to check whether an object is of the wrapping type (if (something is IBar))
Strong-typed access to TFoo in closed-constructed Bar<>s
Polymorphic access to Foo in interfaced IBars
One could argue that this kind of pattern is everywhere in the framework (e.g. List<T> : IList), but I wonder if this is just a remnant of .NET 1.0, when generics didn't exist.
Off the top of my head, my main concern is that IBar is not necessarily a proper contract that defines what members a "bar" should provide; it's only a hack to access generically typed members.
Also, if I start adding interfaces for that purpose, I quickly end up with hard to maintain parallel inheritance hierarchies.
Should I be worried about spreading this pattern in my code base? If so, what alternative patterns would provide some or all of the 3 benefits listed above?
Because explicitly implementing abstract members is not allowed, this "ideal" solution is not possible:
class Foo { }
class Bar
{
public abstract Foo Foo { get; }
}
class Bar<TFoo> : Bar where TFoo : Foo
{
private TFoo foo;
Foo Bar.Foo
{
get
{
return foo;
}
}
public new TFoo Foo
{
get
{
return foo;
}
}
}
For me, the summary is you shouldn't think that you implement interfaces just for the sake of augmenting a generic type parameter with more typing.
AFAIK, you use interfaces to provide which are the contracts to work with a given API. Generics are just a language feature/tool to provide more typing where you would end up doing a lot of casts. Hereby, with generics you limit your API to expect arguments implementing one or more interfaces and also with some requirements using generic constraints.
For example, if you just want to accept implementations of given interface called IWhatever, would you use generics?
public void DoStuff<T>(T whatever)
where T : IWhatever
{
}
// versus
public void DoStuff(IWhatever whatever)
{
}
BTW, without generics, how you would check that an implementation to IWhatever is a class and has a public constructor? You would end up with reflection and you're code would smell compared to using generics:
public void DoStuff<T>()
where T : class, IWhatever, new()
{
}
In fact, a generic parameter can constraint that T must inherit a given class and implement one or more interfaces:
public void DoStuff<T>(T arg)
where T : A, IEquatable<T>, IWhatever, IWhichever, IWherever
{
}
And whether if T inherits a type with or without generic parameters or implements interfaces with or without generic parameters, it's not a good or bad design per se but, again, just a language tool that's suitable to specific cases.
Therefore, your statement...
Off the top of my head, my main concern is that IBar is not
necessarily a proper contract that defines what members a "bar" should
provide; it's only a hack to access generically typed members.
...describes a particular design flaw instead of an actual problem with typing generics using the wonders of interfaces.
Conclusion: if IBar isn't a proper contract, then you should revisit your architecture and re-think your solution.
More background on the topic
Actually I thought that my original answer implied that I found the whole solution has a design flaw.
In summary, you're using interfaces to expose an association on certain classes which provide the type of the whole association using a generic type parameter. And you argue that you do this to be able to access such association in a less typed context:
However, I sometime need a "less" typesafe context, hence my question.
And then it's when covariance enters in action! See the following code sample:
public class SuperClass
{
}
public interface IWhatever<out TAssociation>
where TAssociation : SuperClass
{
TAssociation Association { get; }
}
public class SomeImplementation<TAssociation> : IWhatever<TAssociation>
where TAssociation : SuperClass
{
public TAssociation Association { get; set; }
}
Now let's define a derived class of SuperClass:
public class DerivedClass : SuperClass
{
}
And see how this works like a charm:
SomeImplementation<DerivedClass> someImpl = new SomeImplementation<DerivedClass>();
// Covariance: you decide the degree of specialization of TAssociation
// interfaces' type parameter. In our case, we'll upcast TAssociation to
// the SuperClass type.
IWhatever<SuperClass> whatever = someImpl;
Clearly this is the way to go since C# 4.0.
I would say that the right way of expressing your requirement is you need a less specialized context instead of a less typed context. Covariance/contravariance is one of the most powerful features available in C# to cover this scenario when generics are involved in the equation.
This practice isn't a code smell per se. In my case, I go for it when I really need to access one or more associations somewhere where I just need to access certain members with a concrete purpose.
For example, if I'm building a tree-style hierarchy, I would define an interface like this:
public interface IHasParent<out TParent>
{
TParent Parent { get; }
}
Which enables me to do this:
IHasParent<object> withParent = someObject as IHasParent<object>;
if(withParent != null)
{
// Do stuff here if some given object has a parent object
}
But I don't create interfaces indiscriminately because some day I'll need less typed access to some properties. There should be a well defined purpose. Otherwise, you can end up turning a nice solution into a code smell.
You would say don't repeat yourself but I still feel that there's no definitive answer without analyzing your project code base and checking how you really use this kind of interfaces to solve concrete problems.
So, strictly talking, if you use the whole pattern when it's really required, it should be a good design decision.
Maybe you want to avoid the unavoidable
Based on some chat we've had both the OP and me, I feel that the best conclusion is that the OP wants to avoid the unaviodable.
In an object-oriented language like C# interfaces are the right tool to both define type contracts and expose a subset of a full type implementing some interface.
Also, the OP would love a feature in C# like protocols where a class that implicitly fullfils an interface is enough to consider that it implements the interface which would save up many code lines if C# could have this feature:
public interface IWhatever
{
void DoStuff();
}
public class X
{
void DoStuff();
}
public class Y
{
public void HandleStuff(IWhatever whateverImpls)
{
}
}
Y y = new Y();
// Protocols would support passing an instance of X which may not implement
// IWhatever but it implicitly fulfills IWhatever:
y.HandleStuff(new X());
BTW, C# lacks this feature. Therefore, it's a waste of time scratching your head thinking how sweet would be having such feature. You need to deal with what C# has to offer already.
Anyway, if you just need to expose some associations across your object graph and get them selectively, you can use the wonders of interfaces using a more simplified approach than yours. Did you know that you can explicitly implement the same interface more than once if its generic arguments vary?
Why don't you design an interface like this:
public interface IHasAssociation<out TAssociation>
{
TAssociation Association
{
get;
}
}
public interface IHasManyAssociation<out TEnumerable, out TAssociation>
where TEnumerable : IEnumerable<TAssociation>
where TAssociation : Entity
{
TEnumerable Association
{
get;
}
}
public class Entity
{
}
public class Company : Entity
{
}
public class CustomerProfile : Entity
{
}
public class Contact : Entity
{
}
public class Customer :
IHasAssociation<Company>,
IHasAssociation<CustomerProfile>,
IHasManyAssociation<IList<Contact>, Contact>
{
public Company Company
{
get;
set;
}
public CustomerProfile Profile
{
get;
set;
}
public IList<Contact> Contacts
{
get;
set;
}
Company IHasAssociation<Company>.Association => Company;
CustomerProfile IHasAssociation<CustomerProfile>.Association => Profile;
IList<Contact> IHasManyAssociation<IList<Contact>, Contact>.Association => Contacts;
}
Definitively this keep things simpler (KISS!) because you don't need a parallel interface object graph definition, you simply define an interface to being able to get an association of a given type:
var customer = new Customer();
customer.Profile = new CustomerProfile();
customer.Company = new Company();
customer.Contacts = new List<Contact>();
var withCompany = customer as IHasAssociation<Company>;
var withCustomerProfile = customer as IHasAssociation<CustomerProfile>;
var withContacts = customer as IHasManyAssociation<IList<Contact>, Contact>;
if (withCompany != null)
{
Company company = withCompany.Association;
Console.WriteLine("This object has an associated company!");
}
if (withCustomerProfile != null)
{
CustomerProfile profile = withCustomerProfile.Association;
Console.WriteLine("This object has a profile!");
}
if (withContacts != null)
{
IList<Contact> contacts = withContacts.Association;
Console.WriteLine("This object has contacts!");
}
Also, see covariance in action:
if(customer is IHasManyAssociation<IEnumerable<Contact>, Contact>)
{
Console.WriteLine("This object has an enumerable of contacts!");
}
Or here's how you would get all association values of an implementor of one or many IHasAssociation<out TAssociation> interface implementations:
var entityAssociations = typeof(Customer)
.GetInterfaces()
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHasAssociation<>))
.Select(i => i.GetProperty("Association").GetValue(customer));
foreach(var entityAssociation in entityAssociations)
{
Console.WriteLine($"{entityAssociation.GetType().FullName}");
}
This is the real beauty of generic programming! And remember: you won't need to implement IHasAssociation<out TAssociation>/IHasManyAssociation<out TEnumerable, out TAssociation> indiscriminately. That is, you implement on the classes to which associations need to be extracted in some place where you don't care who's the concrete owner of the association and you just need the association itself.
In your question, you express the need for a "generic" wrapper type (note I use the term "generic" here independently of any language).
Well, I don't see any problem with that. And if you ask me how to do it with .NET, I would just design this, once for all types, going one step further from you:
interface IWrapper<T>
{
T BaseObject { get; }
}
Then, a wrapper class would simply be:
class Bar<TFoo> : IWrapper<TFoo> where TFoo : Foo
{
public TFoo BaseObject { get; private set; }
}
I could go further again and define the non generic one, because it's ofen desirable to have both, as it's sometimes hard to work with generic-only clases/interface with meta/reflection code (but this is really optional):
interface IWrapper
{
object BaseObject { get; }
}
If you do this, it could be natural to have IWrapper<T> derive from IWrapper, like this:
interface IWrapper<T> : IWrapper
{
new T BaseObject { get; }
}
And the class would be this:
class Bar<TFoo> : IWrapper<TFoo> where TFoo : Foo
{
public TFoo BaseObject { get; private set; }
object IWrapper.BaseObject => BaseObject;
}
PS: as a side note, you can have a look at WCF's ServiceModel ChannelFactory<T> class that has a combined generic/non generic hierarchy somewhat relevant with your question.
I've found myself in a similar place after developing an API.
I have some questions for you and no answers.
But once you can answer those questions, maybe you know a bit more about how to address this situation.
I wonder how many classes implement IBar.
Are there enough to justify it?
Is this an API and you expose it to client code?
In how many code points do you leverage the polymorphism of the interface?
Just maybe... those answers can make you question the interface's usefulness.
How many times does this structure emerge?
And are you sure it actually does?
I mean, you say you did this:
implement lots of code (A);
refactor it in one place to clean it up;
implement more code (B);
refactor it to clean it up;
notice that B looks similar to A;
implement more code (C);
refactor it to clean it up;
notice that C looks similar to B (by transitivity also to A);
repeat...
Did the structure REALLY emerge, or is it your thinking that mold the code always in the same way?
Which comes first?
the emergence;
the thinking.
This "rinse" and "repeat" approach may be good to start, but just maybe... you've grown out of this methodology and should approach another one:
First design, then implement.
Is this your case? Have you grown that much, that you can finally approach design before implementation?
There's a saying that may apply here:
When you have a hammer, everything looks like a nail.
But let's assume this is not your case.
You don't fall into thought cycles and the underlying problem REALLY has this structure, thus your code reflects the problem's structure.
If you really came up with the same thing multiple times, but it's the problem, not your mind playing tricks, then the following may be a good advice.
Stop coding for a day, and think about it away from keyboard.
Which parts are the same, which different?
Can't you implement this in an even MORE abstract way (actual pattern) into which you inject the specialized code?
Maybe, underlying it all, is a something as simple as a composite pattern, and you could just implement that once and for all, and then reuse it all over the place.
What happened to me was similar, and I ended up with a dependency injection, an abstract factory, an abstract implementation of the composite pattern and an information expert, which took a configuration file and assembled the final object graphs I needed.
It was an excellent, humbling lesson in patterns and architecture, but I regretted actually using it.
Writing the documentation was near impossible and futile.
The code became extremely difficult to follow.
I always had to look things up and rethink about how to use it correctly.
The end result was not that astonishing.
So, if you want to learn and exercise, don't ever stop!
But if you want to just get it done and move on, don't overthink it.
Simple is better!
You may be in a place where you try to perfect your code but actually don't need it.
You're not writing a new API for M$, are you?
Just take this advice:
In a year or two, you won't be able to understand your own code. You must document it, if you make it that complex. If you can't document it, you'll never reuse it. So you don't need this perfection, it will be throw-away code.
In other words:
The real value is not the code, but the documentation that accompanies it. Without documentation there will be no reuse..
In retrospect, I've learned that the correct term for what I want is return type covariance, which is unfortunately not supported in C#, because the language design team does not consider the benefits of implementing the feature outweigh the cost, even though it preserves type safety. (A proposal has been drafted and completed, but it seems to be abandoned).
With return type covariance, the example code could be written as:
class Foo { }
class Bar
{
public virtual Foo Foo { get; }
}
class Bar<TFoo> : Bar where TFoo : Foo
{
public override TFoo Foo { get; }
}
The workaround proposed by Eric Lippert in that linked question is:
class Foo { }
abstract class Bar
{
protected abstract Foo foo { get; }
public Foo Foo => foo;
}
class Bar<TFoo> : Bar where TFoo : Foo
{
protected override Foo foo => this.Foo;
public new TFoo Foo { get { ... } }
}
It has the downside of duplicating not the inheritance hierarchy, but every covariant-simulated property per level of inheritance!
For further reading on how much clutter simulating covariant return types can bring to your code, consider that implementing ICloneable properly implies adding another virtual method per level of inheritance. I'll leave this as my humble plea for that language feature.
ok I'm little lost with generics in C#
I have this generic interface
interface IInvoiceStorage<T>
where T : class
{
void Persist(T Invoice);
}
with two classes implementing the interface
public class FacturaStorageForSQLServer:IInvoiceStorage<EVT>
{
public void Persist(EVT Invoice)
{
/*Implementation*/
}
}
public class FacturaStorageForMySQLServer:IInvoiceStorage<EVTFruit>
{
public void Persist(EVTFruit Invoice)
{
/*Implementation*/
}
}
The problem comes when I want to declare this in my service class
public class invoice_service
{
IInvoiceStorage Storage;
public invoice_service(IInvoiceStorage storage)
{
Storage=_storage;
}
}
C# tells me that I have to declare de type of the interface but if I do that then my service class is going to depend from the implementation and not from the interface.
Suggestions??
UPDATE 1:
Sorry If I declare the type the interface is going to depend only from the implementations using that type but what happens if I have two implementations using two different types for example EVT and EVTFruit.
I was thinking to use another interface to establish a relationship between EVT and EVTFruit but they can be two totally different objects so I'm not sure if it is a good idea.
You could change your class a little bit:
public class invoice_service<T> where T : class
{
IInvoiceStorage<T> Storage;
public invoice_service(IInvoiceStorage<T> storage)
{
Storage=_storage;
}
}
Which would allow you to use the interface correctly and keep it generic.
Depending on your needs, you could also defined non-generic version of that interface:
public interface IInvoiceStorage
{
...
}
And make classes inherit from this interface, too.
public class FacturaStorageForSQLServer : IInvoiceStorage, IInvoiceStorage<EVT>
public class FacturaStorageForMySQLServer : IInvoiceStorage, IInvoiceStorage<EVTFruit>
That way you can use non-generic version of interface in invoice_service class.
But, as I said, depending on your needs if you can make functionality of that interface independent of type (for example, List<T> also implements IList for list functionalities, without type).
After trying your suggestions and reading some blogs here is what I did and is fulfilling my requeriments at least for now. The problem was resolved when I realized that I shouldn't use the generic repository pattern as a repository itself but as a helper of the repository! At the end what I'm doing is wrapping the generic interfaces inside of another layer of non-generic interfaces.
a Service class calling for an IInvoiceRepositoryService implementation
public class InvoiceService
{
private IInvoiceRepositoryService RepositoryService;
public SQLInvoiceService(IInvoiceRepositoryService _RS)
{
RepositoryService=_RS;
}
}
and their respective implementation for EVT and EVTFruit.
public class EVTRepository:IInvoiceRepositoryService
{
private IInvoiceStorage<EVT> EVTStorage;
public EVTInvoiceRepository(IInvoice<EVT> _EVT)
{
EVTStorage=_EVT;
}
}
public class EVTStorageForSQLServer: IInvoiceStorage<EVT>
{
/*Implementation*/
}
public class EVTStorageForMySQLServer: IInvoiceStorage<EVT>
{
/*Implementation*/
}
public class EVTFruitRepository:IInvoiceRepositoryService
{
private IInvoiceStorage<EVT> EVTFruitStorage;
public EVTFruitInvoiceRepository(IInvoice<EVTFruit> _EVTFruit)
{
EVTFruitStorage=_EVTFruit;
}
}
public class EVTFruitStorageForSQLServer: IInvoiceStorage<EVTFruit>
{
/*Implementation*/
}
public class EVTFruitStorageForMySQLServer: IInvoiceStorage<EVTFruit>
{
/*Implementation*/
}
At the end this was just a design problem I think. I'm going to mark Ron Beyer's response as the answer because is valid and it was really straightforward