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 4 years ago.
Improve this question
I'm relatively new to C#. I was working on a few console app projects that rely on user input and fire off different functions depending on their input.
I thought that it might be simpler and a bit more flexible to map the possible inputs to a function in a dictionary.
I was told this may be a bad design choice, but wasn't given a clear explanation why.
class Request<T> : IRequest<T>
{
string Route { get; set; }
T Body { get; set; }
}
class Response<T> : IResponse<T>
{
string Route { get; set; }
T Body { get; set; }
}
class Router : IRoutable
{
Dictionary<string, Func<IRequest<T>, IResponse<T>> Routes { get; set; }
}
Can this make my design worse / more fragile? If so, why?
I was told this may be a bad design choice, but wasn't given a clear explanation why.
You should ask that person for clarification.
Can this make my design worse / more fragile? If so, why?
(I assume that your interfaces, which you have not shown, have the same surface area as the classes which implement them. If that's not the case, then you've omitted key details from your question and should update the question.)
Yes, absolutely. Your design allows anyone to change any aspect of the system at any time for any reason! That's a security nightmare.
Also, it exposes what ought to be an implementation detail in the interface. Suppose someone wanted to use a concurrent dictionary? Or an immutable lookup? Nope, they cannot; they are required to use a dictionary in your interface.
Let's step back. What are the basic parts?
A route is represented by a string
A request has a body and a route
A response has a body and a route
A server takes a request and returns a response
A router takes a route and returns a server.
So let's write those.
interface IRoute
{
string Route { get; }
}
interface IRequest<T>
{
IRoute Route { get; }
T Request { get; }
}
interface IResponse<T>
{
IRoute Route { get; }
T Response { get; }
}
interface IServer
{
IResponse<T> Process<T>(IRequest<T> request);
}
interface IRouter
{
IServer GetServer(IRoute route);
}
Remember, interfaces represent the bare minimum contract you need to expose to their clients. Is there any reason why you need to know that IRouter is implemented with a Dictionary? No. Then don't expose that. A router takes a route and gives you a server, end of story. Let the implementer decide whether they want to use a dictionary or not.
Is any possible string a route? Can any route be used as a string? If not, then don't represent routes as strings in the interface. Is it ever possible that someone mistakes a string expression that does not represent a route for one that does? Make the type system catch that bug! Make a type representing routes.
Similarly, don't let anyone write anything that they don't have business writing. Every property should be read-only in the interface unless it is a by-design feature of the type that the property be mutable by anyone.
Another question is: why interfaces at all? Are you going to have three or more implementations of each? If not, consider making them sealed classes or structs instead, preferably immutable types.
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 6 years ago.
Improve this question
Consider following code
class ProductDefinition {}
A:
class Product { public ProductDefinition Definition {get;set}}
B:
class Product { public ProductDefinition ProductDefinition {get;set}}
(B) will result in slight redundancy when using this property such as
product.ProductDefinition.Price
vs
product.Definition.Price
However it seems to be something that programmers are used to see.
Are there any further elaborations on this topic?
I prefer to use class Product { public ProductDefinition ProductDefinition {get;set}}.
Because maybe in the future you wish to add another Definition to your class, and then you could have incongruencies in your property naming, because you would have one Definition and one FooDefinition. I think it is better to have FooDefinition and BarDefinition.
It makes absolutely no sense to name your property ProductDefinition if your class is named Product. A property named Definition is of course the definition of Product (of what else?), so ProductDefinition would be redundand. And there is no practice of naming the proiperty like its type. C# allows that, but it does not mandate it.
The line...
product.Definition.Price
... is 100% clear and free of any redundancies. It's the price of the product's definition.
I would go with Microsoft recommended guidelines
✓ CONSIDER giving a property the same name as its type. For example,
the following property correctly gets and sets an enum value named
Color, so the property is named Color:
public enum Color {...}
public class Control {
public Color Color { get {...} set {...} }
}
So, in this case, I would structure it as:
class ProductDefinition {}
class Product { public ProductDefinition ProductDefinition { get; set; } }
EDITED:
Another point which I would take into consideration is having some other property which gives another definition to the Product object. For example (ProductOwnerDefinition):
class ProductDefinition { }
class ProductOwnerDefinition { }
class Product
{
public ProductDefinition ProductDefinition { get; set; }
public ProductOwnerDefinition ProductOwnerDefinition { get; set; }
}
Here the usage of Definition can lead to confusion. So it is better to name the Property as the name of the type.
Let's also consider another scenario, where we are using static code analysis tools like StyleCop. In this case, if we are not following the recommended patterns it will give suggestion on making modifications. This is not a big deal as we can suppress these rules. But, something to consider moving forward.
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 7 years ago.
Improve this question
If you have an enum where the values can be naturally grouped into subsets. For example:
[Flags]
public enum Instrument
{
Lute,
Guitar,
Flute,
Drum
}
[Flags]
public enum InstrumentType
{
Percussion,
String,
Wind,
}
there are many ways this can be accomplished
1) To combine this data into a separate Enum?
[Flags]
public enum ValidInstrument
{
Lute= Instrument.Lute| InstrumentType.String,
Guitar = Instrument.Guitar | InstrumentType.String,
Flute = Instrument.Flute | InstrumentType.Wind,
Drum = Instrument.Drum | InstrumentType.Percussion,
}
(assuming appropriate and none crossing values between the enums)
which would allow you to do
(ValidInstrument | InstrumentType.String) == InstrumentType.String
to determine if a instrument is string or not
2) to create some sort of mapping structure that does exactly the same thing?
public static InstrumentType GetInstrumentType(Instrument inst)
{
switch(inst)
{
case Instrument.Lute:
case Instrument.Guitar:
return InstrumentType.String
//etc.
}
}
3) Attributes?
public enum Instrument
{
[InstrumentType(InstrumentType.String)]
Lute,
[InstrumentType(InstrumentType.String)]
Guitar,
[InstrumentType(InstrumentType.Wind)]
Flute,
[InstrumentType(InstrumentType.Percussion)]
Drum
}
4) in a standalone class?
public class ValidInstrument
{
public InstrumentType Type{get;set;}
public Instrument Instrument{get;set;}
}
with a static runtime population
which of these methods is better, or if dependent on the situation what factors should influence the choice
As soon as you start talking about relationships between things, it feels like you are talking about inheritance. Best practice would be to represent this as a class structure.
class Instrument
{
void Play();
}
class StringedInstrument : Instrument
{
void Strum();
}
class Guitar : StringedInstrument
{
}
With factory classes/methods and a few other design patterns you should be able to handle the same things and an enum lets you, but also many more that you could never handle with an enum.
If you want to find all band members who play a stringed instrument, you would simply get all members where their instrument "is a" stringed instrument. This should be able to be done in C# with a Type.IsSubclassOf() call.
If a developer then creates a Flute class that inherits from StringedInstrument, as in your comment above, you should fire that developer! :) If you are talking about assigning a Flute object to a StringedInstrument instance, that would be prevented by C# because the cast is invalid. You can cast a Flute to WindInstrument or Instrument, but never StringedInstrument unless a developer incorrectly made it inherit from the wrong instrument type.
Because [Flags] indicates that enum values may be stored as bits, using comments for grouping rather than separate data structures is one way of balancing potential readability with potential performance...and why use [Flags] but for performance reasons?
If you are just trying to manage a simple relationship then
Dictionary<Instrument, InstrumentType>
If you need to strictly enforce then Inheritance
public class Guitar : StringInsturment
I get that could have enum hierarchy but I just don't get what real life solution it solves. So Guitar has a Description of String. By the time you wrap some code around that to do something with it you would be better off with class inheritance.
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.
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! :-)