Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Are there design guidelines for the use of interfaces in the scenario below?
I could declare IDescription in DerivedClass or in the interface ISomeInterface or both. 3 choices, what guidelines would help me decide which is best.
public interface IDescription
{
String Description { get; }
}
public interface ISomeInterface
{
String Name { get; }
String Description { get; }
}
public class DerivedClass : Base, ISomeInterface, IDescription
{
public String Description { get; private set; }
}
It depends on the concrete interfaces and their logical relations. There is no universal solution for every case. 2 options you mentioned will be right at some cirtumstances:
If interfaces are not related (for example IDisposable and IEnumerable), then it's better that class implement two unrelated interfaces.
If interfaces are related. For example IClientAPI and IAdminAPI, then admin interface may derive from client's interface, because administrator can do everything normal user can, plus some additional operations.
The case when interfaces derived and at the same time class implements both parent and children interface is rare if at all possible in well-written code. You can always avoid it. I don't see any problems if you specify interface second time for class itself. At the same time there is no profit as well. So better don't do it.
Important note: Don't build inheritance hierarchy based on just matching property names - they can be same by coincidence. Always think if this is coincidence or fixed relation before creating base class or interface. Otherwise you'll end up with tons of interfaces like IDescription, IName, IID, etc that doesn't mean anything and only complicates the code.
If the description property is meant to represent the same semantic object in both cases, I would have ISomeInterface implement IDescription for clarity. If they are not necessarily the same thing in your design, then no.
Design guidelines basically depend on the requirement in this case. If you declare the Description in ISomewhere, then you will be forced to implement its other properties(which in this case is Name) even in the classes, which do not need the Name property.
On the other hand, if the Name and Description properties are required by all the classes where you will use ISomewhere, then it will be better to use it in single place ISomeWhere.
To get more precise answer, you need to analyze the where these interfaces will be used.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a hard time to figure out, how I can implement seemingly easy patterns with the strict typing system that C#'s generic system is restricted to. Coming from a mostly Java background, I am used to wildcards for generic types. Since C# does not allow such things I need your help to figure out the most elegant way to implement the following (my implementation is for a Unity3D project but that's really not important I think):
I have Content Providers that can provide various types of content (s.a. objects of the type "Texture", "String",...)
Therefore I created an abstract generic class and an interface such that my architecture look like this
Furthermore I have Content Receivers that are able to handle the content of a certain type and a managing class with a set of such Content Receivers. I want the logic for what receiver has to deal with the content of a given provider in a style something like this:
public void accept(IUIContentProvider provider){
//1. Check if a receiver for the generic type of the provider exists
//2. Ignore the call if no such receiver exists, otherwise pass the provider to this class and
//let it deal with it in some specific manner.
}
But due to the strong type system of C# it seems to be impossible to do anything elegant using Polymorphism. I also can not explicitly convert the IUIContentProvider apparently. I can not even use an abstract base method like:
public abstract object provideContent()
and to override it with e.g.:
public override Texture provideContent(){...}
At this point I start to wonder if it is even wise to use generics for this purpose in C#...
You said in your abstract/generic class UIContentProvider<T> you wanted to have such method :
public abstract object ProvideContent();
And you want to be able to have this override in your concrete implementation TextProvider :
public override string ProvideContent(){...};
But I think you miss the point of the generic in your abstract class... What is the point of having a type parameter T if you don't use it?
Isn't it what you want ?
public interface IUIContentProvider<T>
{
T ProvideContent();
}
public abstract class UIContentProvider<T> : IUIContentProvider<T>
{
public abstract T ProvideContent();
}
public class TextProvider : UIContentProvider<string>
{
public override string ProvideContent()
{
return "";
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In an interface definition, is it better to declare a member of a type of the desired Class or Interface equivalent? For example, let's say we have an interface called IFoo that is implemented by the class Foo. If we are declaring another interface IBar, and we need a representation of the *Foo thing in IBar which is better?
interface IBar {
IFoo member { get; set; } // interface
}
or ...
interface IBar {
Foo member { get; set; } // class
}
There seems to be equally valid arguments for both camps. What are your thoughts?
Using an interface makes it easier to swap out the initial implementation for a new one - without having to update references since they deal with the abstraction offered by the interface.
It can also help you out with unit testing since you can easily mock based on the interface.
A common example where your code is more flexible if using an interface is IList.
Interfaces not only provide more flexibility, It also allows you to build better abstractions.
It will also force you to think of things like - If the class implements multiple interfaces, then you have to know what abstraction (Interface) is most suitable, as part of this other interface definition..
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
public class MyTokenStore: ITokenStore
{
public IToken CreateRequestToken(IOAuthContext context)
{
...some code here...
}
public IToken CreateAccessToken(IOAuthContext context)
{
...some code here...
}
}
Which one of below is better ?
Option1 - ITokenStore x = new MyTokenStore(); OR
Option2 - MyTokenStore x = new MyTokenStore()
What are the advanatges of both ?
Can I restrict user from using Option 2 ?
Users decide for themselves which version they use. The advantage of option 1 is that the user can really instantiate any class that implements the interface. Say you have a helper class that contains a method
DoSomethingVeryUseful(ITokenStore store)
then again that method becomes more useful because it can be called with any object that implements said interface.
The advantage of using option 2 is that your class may contain methods that are not part of the interface, and thus those methods can only be used with option 2.
There is no general good response to this, as it fully depends on you concrete case.
ITokenStore x = new MyTokenStore()
mades a "slice" over concrete MyTokenStore instance where not all members are inside ITokenStore, so you missing access to some additional information that may be present in MyTokenStore and is not present in ITokenStore.
On other hand you create an abstraction layer, so gain a flexibility.
The purpose of an interface is to expose functionality that is common to all implementer's and is agnostic of the concrete implementation. If you are trying to pass around multiple concrete objects to a consumer that needs to access an interface method, then cast it as an interface.
However, if you need a specific member on the concrete implementation, use that.
This is not which is better question but more what are you going to do with it ? Somethings to consider
Are you going to have multiple objects implement the interface ?
Are you going to be doing unit testing ?
Are you going to be doing any in Dependency Injection ?
If you can answer yes to at least one of the questions the using a interface is a good idea but if your using a interface just to use a interface you might want to rethink the solution
My suggestion is the below option. Instead creating "new" object, we can go with contructor injection.
public class MyTokenStore{
private readonly ITokenStore;
public MyTokenStore{ITokenStore TokenService)
{
this.TokenStore=TokenService;
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In my program, I have defined a couple of interfaces, like IInterface1, IInterface2, IInterface3, IInterface4, IInterface5, if I need implement all five interfaces in a concrete class, do you implement those interface directly like the following
public class EntityClass: IInterface1,IInterface2, *** IInterface5
{
}
or would you create an interface which inherits from those interface firstly, and then implement that interface?
public interface IEntity: IInterface1,IInterface2, *** IInterface5
{
}
public class EntityClass:IEntity
{
}
Inheritance of interfaces expresses the "is-a" relationship. You would inherit IEntity from IInterface1 if every implementation of IEntity must also be an IInterface1.
Yes: public interface IPanda : IBear
Probably not: public interface IAccountant : IObsessiveCompulsiveDisorder
It depends on your use case.
If your IEntity always contains the other interfaces then it would be a lot easier to make it implement the others.
If this is not the case, you'll have to abstract it in a way that no class has to implement methods it doesn't need, while also needing as few implements as possible.
That being said: if you'll only use this for one or two classes, you could just as well use a list of interfaces instead of grouping them in intermediate interfaces.
Both approaches are valid in the context of good practice. However, it depends purely on your design. I find the best way to approach inheritance is to try and talk back what you are inheriting and make sure it makes sense.
For instance, "Is every EntityClass an IEntity?", which may be true. However, asking "Is every EnetityClass an Interface1, AND an Interface 2 etc.", which may be true for some instances, and not for others, but all are implemented on IEntity.
The problem with aggregating many interface implementations into one interface can be when you implement more classes off the interface that has many interfaces in itself is when the implementation needs only a few of the interfaces, in which case you need to re-work your design to ensure that the tree of inheritance makes sense.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I will try to explain my question more clearly because the title is a little bit blurry. I have base class that has some properties. Let's say something like this:
public class BaseClas
{
public int Property1 { get; set; }
public bool Property2 { get; set; }
..............................
}
And I have approximately 70 classes that inherit from the base class, most of these classes just add one or two fields, for example:
public class DerivedClas1 : BaseClass
{
public bool PropertyNew1 { get; set; }
}
public class DerivedClas2: BaseClass
{
public bool PropertyNew2 { get; set; }
}
My problem is that I have 70 classes that each of which has just one new field of type bool or int or datetime, etc. My question is: Is it a good architecture design to combine these classes somehow? And if so how should I combine them? I could use some kind of Dictionary<string,object> but this is not such a good idea. Any suggestions?
(I am using .Net 2.0)
Edit: These classes are used for filtering queries for reporting purposes.Base class defines base filters and every class defines filters specific for the report.
It all depends on your Architecture. I can think of at least one class in the core framework that has dozens, possibly hundreds of derived classes, many of which only add one or two fields, and many which don't even do that and only subclass in order to provide a nicer name or a base class for it's own application-specific abstractions. The name of this class? System.Exception
Another Example could be System.Web.Mvc.Controller, although that's stretching it even more than System.Exception (and I purposely left out System.Object and System.ValueType already).
You don't provide any real examples, so the answer is that yes, it can be appropriate, but maybe it isn't. If you are trying to do a generic data entry where you have "Manager" and "Employee" which derive from "Person", which in turn derives from "DataObject", that may be appropriate, but I would look at other ways, e.g. getting rid of "DataObject" and having multiple, specialized Services that provide database operations, but again, it depends on the picture as a whole.
Edit: You just clarified it's for filtering. In this case, can't you use a system where you only define the types of filters?
public abstract class Filter {
}
public class OrFilter : Filter {
public string Clause1 {get; set;}
public string Clause2 {get; set;}
}
public class ItemMustExistFilter : Filter {
public string ItemName {get; set;}
}
public class Report {
// For the sake of the example, I know that public setters on Lists are not
// best practice
public IList<Filter> Filters {get;set;}
}
That way, you only need concrete classes for Filters itself, and each report would have a list of them. Combine that with the use of Generics (see ram's answer) and you should have a pretty 'lightweight' system. Shame you're on .net 2, otherwise Dynamic LINQ would be useful. Sure that you can't use .net 3.5, which still runs on the 2.0 CLR?
Don't know the exact nature of your problem. It is not a question of whether you need 70 classes, its more a question of accurate description of the problem at hand, good design and maintainability. Does generics help ?
public class BaseClass
{
/* some basic properties go here*/
}
public class BaseClass<T>:BaseClass
{
T SomeSpecificProperty {get;private set;}
}
So when you need a "specific" class, you will have
var myObj = new BaseClass<Bool>();
You should also look into Decorator pattern if you want to "Decorate" your classes. Take a look at DoFactory Example
My 2 cents, hope it helps
What you are describing sounds fine to me - each of your reports has a class that describes the filters specific to that report and so if you have 70 reports then you are going to have 70 classes.
Like you say the alternative would be to do something like having a dictionary instead, which has its own set of drawbacks (to start with it isn't strongly typed).
Its tricky to suggest other alternatives without knowing more about the archetecture (does each report have its own class for displaying / retrieving the report? If so perhaps you could refactor so the properties are on that class instead, using attributes to identify filter parameters).
In short - if you don't have an alternative then it can't be bad design! :-)