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.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:
public static class HasDefaultConstructor<T> where T : new() { }
public class CheckAttribute : Attribute
{
public CheckAttribute(Type type) { }
}
[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
public MyClass() { }
}
But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.
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 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.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the general consensus towards a separate class in the business layer to store the definition of enums? Is this bad practice? Does this conform to good n-tier design? At the moment my enum definitions are dotted around different, what I would deem as, relevant classes - but I feel as though they should be in one place. Is this, in fact, a subjective question and relative to how I've structured the rest of the solution?
I don't really understand why you would place an enum in a class - perhaps you meant file?
Personally I have a separate file for each enum with the name of the enum.
I place this file close to where the enum is being used and namespace it accordingly.
If an enum is to be shared across assemblies/namespaces, I will use the lowest shared namespace, so it is visible to the using namespaces.
Having enums close to where they are used will make separating code out into projects that little bit easier (if needed).
I don't see the point in having them all in one file - navigation wise, Visual Studio has more than enough navigation capabilities that this is not needed.
Keeping enums in separate class
In this case you're tossing unrelated definitions into one class, for almost no benefits.
Defining enum as nested type for class it relates to
When you hold enums within a class, you may run into naming troubles:
class Foo
{
public enum SomeType { /* ... */ }
public SomeType SomeType { get; set; }
}
This would give an error that SomeType is already defined.
It probably just boils to personal taste, but most often I put my enums along with the class that they are related to, without nesting them:
public enum SomeType { }
public class Foo { }
I was tempted many times to have them nested (we're talking about public enums of course), but the naming issues weren't worth it, for example:
class Foo
{
public enum Enumeration { }
}
Then I can use such enum outside of Foo class, as: Foo.Enumeration, but following declaration (in same namespace):
enum FooEnumeration { }
class Foo { }
gives similar result as you just don't have to type '.' when you are referencing enum: FooEnumeration. Moreover, the latter allows you for this:
class Foo
{
public FooEnumeration Enumeration { get; set; }
}
which would cause aforementioned naming conflicts in previous case.
Summary
When using IDE with powerful GoTo capabilities, it seems to me that naming issues are far more important than 'physical' localization of the enum definition.
I would prefer having separate classes for all constants and Enums in my projects.It improves readability of the code. You should do it especially if you have a Comman proj you are referencing in your business layer and other layers. But if you'd be adding unnecessary references just for the sake of a Constant/Enum class then having them inside the same project makes more sense.
public class Enumerations
{
public enum Gender{
Male = 0,
Female = 1,
Unknown = 2
}
}
And when you consume you could do it like
GetPerson(Enumeration.Gender gender)
{
}
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! :-)