Separate class for enums? [closed] - c#

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)
{
}

Related

Guaranteeing immutability in c# [closed]

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 5 years ago.
Improve this question
After reading a lot about immutability in C#, and understading it's benefits (no side effects, safe dictionary keys, multithreading...) a question has come to my mind:
Why there is not a keyword in C# for asserting that a class (or struct) is immutable? This keyword should check at compile time that there is no way you can mutate the class (or struct). For example:
public immutable class MyImmutableClass
{
public readonly string field;
public string field2; //This would be a compile time error
public readonly AnyMutableType field3; //This would be a compile time error
public string Prop { get; }
public string Prop2 { get; set; } //This would be a compile time error
public AnyMutableType Prop3 { get; } //This would be a compile time error
}
I think the compiler work would be quite easy, as it would need to check just a few things:
All public fields are readonly.
All public properties only have getters.
All public fields or properties have immutable types as well (simple value types, or immutable classes/structs).
All public functions or public property getters only depend on immutable fields or properties (public fields/props as described before, or private fields/props which comply to the same restrictions). This of course includes Equals(), GetHashCode() and ToString().
Some possible problems come to my mind with this design:
For the compiler to know that a compiled class/struct is immutable, it would probably be necesary to make changes in the intermediate language.
Readonly generic collection (such as IEnumerable<T>) immutability would depend on the immutability of the type <T>. The proposed immutable keyword would not be useful in this context, as you could not declare that IEnumerable<string> is immutable, even though it is.
Are the reasons stated before enough for this keyword to not exist?
Am I missing any other drawbacks?
Is this just not necessary enough for such big changes in the language?
The short version would be: because nobody has proposed, spec'd, designed, implemented, tested, documented, translated and supported that feature.
The longer version would relate to why to do it, given that it can be achieved indirectly with the readonly field - what benefit would it add.
For classes, it turns out to be relatively minor. Note that there is an [ImmutableObject(true)] attribute that can be used, but no features or frameworks really have a use for it, so ... nobody uses it.
There was a proposal to add "readonly structs" in a future version of C# (related to ref locals, Span<T>, etc) - but: it died a death and evaporated. However, the ref readonly stuff lives on, which is intended to prevent reassignment of this in struct instance methods.

Grouping Enums best practice [closed]

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.

Naming conventions in C# - Global Variables [closed]

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.
I know there is a debate/opinion about using this keyword or underscore in regards to private fields/properties (and I'll mention, I'm stuck on .NET 2.0)
Personally, I prefer this, but there are times you can't use it, for example when you need to reference a global variable from within a static method. Well, then we are forced to use the underscore (assuming we only have 2 choices, this or underscore). This means if my class uses any static methods I can't use this throughout the document.
Now, I've read the naming guidelines and used StyleCop, both would rather I don't use the underscore, but my Resharper pretty much insists on using _.
I don't feel it is right to have one class use the _ and the next class use this simply to accommodate for when the classes mixes non-static and static methods! The advice here on SO is to keep to one implementation/style but I don't know if that means I should ignore Microsoft (and I know MS don't always follow their own rules)!
It has been suggested to prefix with something else, similarish to Hungarian but prefix with globVariableName where glob indicates global. I hate this idea, it's too bespoke and won't be obvious to any other developer outside my team.
So, my question is, what is the best way to define global variables consistently? Since they are naming guides, may be I can just ignore (at least _ can be used consistently but it feels wrong to ignore the advice from the language creators).
Just use the class name in the same way you'd use "this", in a static class. Example follows:
public static class MyStatic
{
public static object Global;
public static void SomeMethod()
{
var theGlobal = MyStatic.Global;
}
}
public class MyNonStatic
{
public object Global;
public void SomeMethod()
{
var theGlobal = this.Global;
}
}
Note: I can't actually think of any other way to do it.
By global variables, I assume you mean const or static fields
I thing StyleCop used to encourage you to use ClassName.staticField for static and const fields, but it seems to have dropped that rule, at least by default. That is still a nice way to do it though.
Also, you can configure Resharper to play nicely with StyleCop.
I always use underscore for both static and instance variables.
For instance variables i use this.variable
For static variables i , sometimes, prefix them with the name of class, e.g., ClassName.variable
this is just my personal opinion;
I believe using this for every private variable is very useful; it has a positive effect on readability of the code. Also, when you are employing some DI constructor injection method, it enables you to use same variable without any confusion, which seems very proper.
public void SomeMethod(int someVariable)
{
this.someVariable = someVariable;
}
I prefer this instead of underscore; underscore seems pretty at first glance; but refering to the previous examples it has negative effect on readability.
I name static variables with the same way I name class variables; usage of this keyword lowers the risk of confusion between private and static variables.

Using Interfaces vs. Func or Action [closed]

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.
I have been writing C# code for 10 years, but I am woefully weak on knowing exactly when to use an interface vs. using a Func or Action. It seems to me that in many places where a method on an interface is called, a Func or Action would work just as well. So, I guess my question is this. If I have an interface with just a single method, or perhaps a couple methods, is there any disadvantage to using a Func or Action instead? Using a Func or Action seems cleaner to me.
Thanks very much.
I guess you can compare an Action or Func with an interface containing one method, with the difference that you can supply any Action or Func that meets the parameter / return value requirements, where when using interfaces, the supplied object must implement that interface.
Perhaps you could call Action and Func "anonymous single method interfaces".
If you look at the design perspective though, your class model would be a drawing of blocks without any lines between them.
You should use delegates and lambda expressions if the implementations are expected to be very short (one or two lines), and especially if the implementations are expected to need local variables (closures).
I have to admit, I was a bit confused by this question. Like #deepee, I agree that a code example would have been good here to show why you think you would use one approach over the other.
The reason for my confusion is that I wouldn't have thought to ask this question since they serve different purposes. Interfaces are used mainly for polymorphism; so that one can treat different implementations all in the same way.
Jon Skeet has a good example of using Func and Action.
Interfaces allow you to do this:
IAnimal animal = AnimalFactory.GetAnimal();
animal.Run();
Using the above code, you don't know or care what kind of animal it is. You just know it can run and you want it to run. More importantly, the caller doesn't know how the animal runs. That's the difference between an Action and interfaces/polymorphism. The logic for doing something is in the concrete class.
An Action will allow you to do the same thing for each instance, when the actual logic is known by the caller, instead of having each concrete instance do something:
animals.ForEach(x => x.Run());
Or:
animals.ForEach(x => /* do something completely different here */);
The above line of code is action that only the caller decides what should happen, instead of delegating the logic to the actual instance by simply calling a method on it.
They solve different problems, so I'm curious to see how folks think they're interchangeable in certain situations.
You would use an Interface when you don't really care what kind of object you're working with...
Let's go with the textbook example
public class Animal;
public class Dog : Animal, IRunningAnimal { }
public class Cheetah : Animal, IRunningAnimal { }
public class Fish : Animal, ISwimmingAnimal { }
public class Gator : Animal, ISwimmingAnimal, IRunningAnimal { }
public interface IRunningAnimal
{
public void Run();
}
public interface ISwimmingAnimal
{
public void Swim();
}
public abstract class Animal
{
/// ...
public abstract void Move();
}
then somewhere in code...
RunningAnimal runner = getAnimal();
//make him run
runner.Run();
each running animal might run in a different way but they all can run.
or better
if(getAnimal() instanceof RunningAnimal) getAnimal().Run();
else getAnimal().Move();

Software architecture design: Number of classes [closed]

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! :-)

Categories

Resources