C# - Creating a code file with common definitions/constants/enums etc? - c#

In C++ I'd often create a code file containing constants, enums, #define-s, macros etc.
What's the best practice for that in C#? Do I create a static class and fill it with that data? or is there some other way ?

You don't need a static class for enums - they can be top-level (meaning: namespace level). Yes, you need a class for constants (and a static class would suffice), but I would tend to have multiple classes - one per intent. There is no need to cram them all together.
In C#, any #define only apply to that file, so there is not much point having a class for them (put them in the project / build-script instead). And macros don't exist.

If you have some items you want to define Globally, like a set of strings, I would use a static class with Static properties. I would do that if you are going to use it in more than 1 place.
If you are going to use a defined string for example in just once place, then I would put it in the class that is referencing it.
It is very important to use properties and not expose members. I have found with C++ developers I have worked with when they move to C# they expose members because they have no need for "the special logic of a property". While that may be true when you initially are writing the code. If you expose it as a member and need to do special logic then you have to refactor in a major way. While if you begin as a property then you can add the logic with no refactoring.
For Enums I tpyically define an Enum.cs file inside the folder that represents the namespace. Rather than define them inside a static class.

Macros:
Macros don't exist in C#.
#Defines:
defines are very restricted and only really used for conditional compilation. You should define them by using the project properties (or in your msbuild script) instead.
Enums:
Enums should each go in their own separate file. They don't need to be within a class, they just go directly in the name space.
Constants:
Personally I try to keep constants to a minimum, and private within a class where possible.
If you do have to make them public and globally available, use a static class (or a normal class if they relate directly to one nicely). Try to group them into classes by their use.
If you are talking about string constants, you could consider using a resource file instead if they are localizable strings.

Usually there is a class or struct for which your enum etc. particular applies. I put it in that file, under the class. It's easy to get to the definition from anywhere it's used in code. When possible, I try to put all similar entities for a namespace (or other logical grouping) in the same place.

I'd already object to that practice in C++.
Define that stuff where you need it and not in a single "dump" file. This kind of file tends to accumulate huge amounts of unused stuff over time. And it's hard to clean up because who knows, which parts of your code is using it...

Related

Good practice using Enumerators - Please back it up with resources [duplicate]

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 have a class which uses an enumeration, the enum is currently in its own file which seems wasteful.
What is the general opinion on enums being placed within the namespace of a file that they are consumed in? Or should the enum really live in its own cs file?
Edit
I should mention that while the class in question uses these enumerations, so does external callers. In other words, another class can set these enumerations. So they are not used internally to the class, otherwise this question would be a no brainer.
I wouldn't say "wasteful" (how much does an extra file cost?), but it is often inconventient. Usually there's one class that's most closely associtated with the enum, and I put them in the same file.
This is really just a matter of preference.
I prefer to put each enumeration in its own file (likewise for each interface, class, and struct, no matter how small). It makes them easier to find when I'm coming from another solution or otherwise don't already have a reference to the type in question.
Putting a single type in each file also makes it easier to identify changes in source control systems without diffing.
This is entirely a matter of style. What I tend to do is to have a file called Enums.cs in the solution in which the enum declarations are collected.
But they are typically found through the F12 key anyway.
The question to ask yourself would be: is there anything about an enumeration type in C# that indicates I should treat it differently from all other types I create?
If the enumeration is public, it should be treated like any other public type. If it is private, declare it as a nested member of the class using it. There is no compelling reason to put two public types in the same file simply because one is an enumeration. The fact that it is a public type is all that matters; the flavor of type does not.
Another advantage of putting each type (class, struct, enum) in its own file is source control. You can easily get the entire history of the type.
I place mostly inside in namespace and outside of class so that it is easily accessible other classes in that namespace like below.
namespace UserManagement
{
public enum UserStatus { Active, InActive }
class User
{
...
}
}
Generally I prefer my enums to be in the same file as the Class that it will most probably be an attribute of. If for example I have a class Task then the enum TaskStatus will be in the same file.
However, if I have enums of a more generic nature, then I keep them contextually in various files.
It depends on what access is needed.
If the enum is only used by a single class, it's okay to declare it within that class because you don't need to use it anywhere else.
For enums used by multiple classes or in a public API, then I will always keep the definition in its own file in the appropriate namespace. It's far easier to find that way, and the strategy follows the pattern of one-object-per-file, which is good to use with classes and interfaces as well.
I think that depends on the scope of the enum. For example if the enum is specific to one class, for example used to avoid the magic constant scenario, then I would say put it in the same file as the class:
enum SearchType { Forward, Reverse }
If the enum is general and can be used by several classes for different scenarios, then I would be inclined to use put it in its own file. For example the below could be used for several purposes:
enum Result { Success, Error }
I tend to put enums in their own file for a very simple reason: as with classes and structs, it's nice to know exactly where to look if you want to find a type's definition: in the file of the same name. (To be fair, in VS you can always use "Go to Definition," too.)
Obviously, it can get out of hand. A colleague where I work even makes separate files for delegates.
One advantage of using a separate file for enums is that you can delete the original class that used the enum and write a new class using the enum.
If the enum is independent of the original class then putting it in a separate file makes future changes easier.
If you are using the USysWare File Browser add-in for Visual Studio, you can very quickly find files of particular names in your solution. Imagine looking for an enum that is not in its own file but instead buried in some file in a gigantic solution.
For small solutions, it doesn't matter, but for large ones, it becomes all the more important to keep classes and enums in their own files. You can quickly find them, edit them, and more. I highly, highly recommend putting your enum in its own file.
And as was stated... How wasteful is a file that ends up only being a couple of kb anyways?
Very simple huge advantage to separate file. When any object is in its own MyObjectName.cs file... you can go to solution explorer and type MyObjectName.cs and be shown exactly 1 file. Anything that makes debugging better is nice.
Another advantage on a similar note, if you search all files (ctrl+shft+F) for a name, you may find 20 references to the name in the same file... and that found name will be part of different objects. In the Find Results window all you can see is the line number and the file name. You would have to open the file and scroll to figure out which object the found reference was in.
Anything that makes debugging easier, I like.
If you have multiple projects in one solution. Then better create another project Utilities. Then create a Folder \Enumerations and create a nested static class. And then assign each static class where you will create enum that corresponds to the name of your projects. For example you have a project named DatabaseReader and DatabaseUsers then you may name the static class like
public static class EnumUtility {
#region --Database Readers Enum
public static class EnumDBReader {
public enum Actions { Create, Retrieve, Update, Delete};
}
#endregion
#region --Database Users Enum
public static class EnumDBUsers {
public enum UserIdentity { user, admin };
}
#endregion
}
Then entire enum that can be used in the entire solutions per projects will be declared on it. Use #region to separate each concern. By this, it is easier to look for any enums
I like to have one public enums file named E containing each seperate enum, then any enum can be accessed with E... and they are in one place to manage.

Whether to use static class or not [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.

Refactoring: Nested class or separate classes?

I'm currently doing some refactoring (+ adding new features) to some of our framework classes. The situation is that we have a single (god-like) class which does a bunch of logic we'd like to split up. The class represents something like a validation rule for fiscal codes. So it does validation of the names of the person, birthdate etc..
What I am going to do is to split it up in single rules, basically a rule which validates the person's firstname against the fiscal code, another one for the birthdate and so on. For the programmer at the end it looks nearly the same. Instead of invoking the huge constructor of the FiscalCode rule, he'll do something like FiscalCode.GetRules(...) and pass the parameters here. The GetRules(...) will then internally construct the single rules and pass them back as an array. That's perfectly fine and correct for us.
So much for your background. Now my question is the following. The FiscalCode class (which is our current mighty god-class) has a lot of utility methods which will be needed by more of the single "rule classes" I'm going to create. What I know is that I will somehow still need the FiscalCode class, for doing the GetRules(...) thing (this is to remain constant somehow for the programmers, not that they have to do a completely new thing).
I have two options which come to my mind:
Create my new rule classes and access the public static utility methods of the FiscalCode class
Create my new rule classes as inner nested classes of the FiscalCode class s.t. I have already access the utility methods (and therefore no need for exposing my utility methods)
I have already a favorite, but I'd like to hear the opinion of some of you first.
Thx
As your methods became 'utility methods' you need to make them static and public, but probably you need to rename your FiscalCode to FiscalCodeUtil. So it will be obvious what kind of methods it contains.
I would also suggest a review of the Specification Pattern, which gives some direction on how to approach this type of problem. This post also gives some examples in C#.
The suggested Specification Pattern would steer you towards your option #1.
What dependencies do these utility methods have on the FiscalCode class or the rule classes? Is there state kept by them?
If there aren't any dependencies I'd suggest moving those utility methods to a seperate class, and have the FiscalCode class or rule class call into those methods as appropriate.
For the options you give, the only difference between 1) and 2) is whether the rule classes are visible to classes that don't use them. I don't think thats really an important objective. I used to worry about that all the time when I did c++... it was a waste of time.
IMO you should go for the first option because that way, you can expose the newly created classes to outside world, and can write code that is reusable elsewhere as well. If you go with the second option, you are creating very specialized classes. Your outside code may not even know of its existence, but that might be good for encasulation. Still, at some point you may decide to use the specialized rules outside the scope of your larger class, and for that scenario, you are better served with the first option. What is your pick though?
If the class will not be used outside the FiscalCode class, then make it nested. The important thing is to pull the responsibility of this new class out of FiscalCode; where it resides then becomes a mere question of choice. When the new class gets more dependents, you could make it an outer class.
I would go with it like this (I'm not that good at OOP so take it with a grain of salt):
Rule classes (nested in FiscalCode) implement an IRule interface exposing rule methods (like Validate(), with whatever return type floats your boat). FiscalCode
has an AddRule() method which manages an internal collection of rules and returns a reference to self in order to permit method chaining:
FiscalCode fc = new FiscalCode();
fc.AddRule(new RuleClass1(<params specific to RuleClass1>)
.AddRule(new RuleClass2(<params specific to RuleClass2>)
...
Also, FiscalCode has a Validate() method which iterates through each rule's Validate() and manages errors.
IMO this is quite handy to use and still permits to nested rule classes access FiscalCode's utility methods.

do interfaces belong in files of their own

As as rule of thumb I generally put classes in a file of their own. Visual studio seems to encourage this but what is appropriate with regards to interfaces?
e.g.
I have Class Foo that implements interface Bar
public interface IBar
{
}
public class Foo : IBar
{
}
it seems natural to group these within the same file until another class implements the interface but to dedicate a file to 2 lines code seems excessive but correct.
What is appropriate?
I would split them into 2 files. I often found classes starting to go unmanageable when they are not in their own files.
Imagine trying to find class Foo in a file named IBar.cs or vice versa.
Since the purpose of an interface is to define a "contract" for (potentially) multiple implementing classes, I'd say putting the interface definition in its own file makes more sense. i.e. What happens if you also want to make Baz implement Foo?
Depending on the situation I either split each interface into its own file, or alternatively have an Interfaces.cs file, where I group interfaces in a given namespace together.
I'd never put an interface in the same .cs file as a class that implemented it.
I have only two situations where I find myself putting multiple top level types in a single file:
If you're defining multiple delegate types. Each is only going to be a single declaration, so it makes sense to have a Delegates.cs file.
Sometimes it makes sense to declare that a whole bunch of autogenerated partial types implement a bunch of interfaces. Again, that's one line per type:
// Actualy code is in the autogenerated file
public partial class Foo : ICommon {}
Other than that, I use one file per top-level type, which goes for interfaces, classes and enums.
You should certainly put the interface in it's own file. You may even consider putting the interface in it's own class library. If the interface will be used by two different classes in two different libraries, it makes sense to put the interface in a third library, so you don't have to include any specific implementation if you want to add the interface to a new project. In the third library you might also place classes that work with classes that implement the interface (public void Cook(IBar x), for instance).
Yes, having an interface implies that you are going to have more than one class with the same methods and properties definitions. Having it in one file for the moment is convenient as it is easy to modify without changing files. As time goes on you will and other classes use it, and if you have to make a change to it down the road you will have to hunt and peck for the right file.
I always put them into separate files. Having more than one type per file is just distracting IMO. I might make a folder "Interfaces" for them though.
Also i think you shouldn't modify them as often as your actual implementations, anyway, so having them separated at least promotes that a bit.
In terms of encapsulation, each object, whether a class or an interface, should be in its own file. Even if the interface only contains one abstract method, the fact that it's in a different file allows for better organization and better encapsulation. You can store those different interfaces in a folder, give it an appropriate namespace, and therefore a cleaner solution.

When to use static variables?

I'm currently doing a project in C# with a lot of rendering, and throughout almost all the classes there's a constant value of the type integer being used for scaling of the rendering. I know I could define this constant in one place as a normal variable and then pass it around, but this seemes really cumbersome. When is it acceptable to use static variables in C#? The easiest solution to my problem would be to create a class containing the static variable that all the other classes could reference - would that be bad design?
How constant is the value? static is fine for things that are readonly, but you can quickly get into a mess if it isn't readonly - especially if you have multiple threads. The scaling factor doesn't sound like a hard constant to me - i.e. it isn't:
public const double ScaleFactor = 1;
I wouldn't hesitate to use a static variable for something I load once and leave alone. Other than that, I'd probably encapsulate (in your case) some kind of RenderContext with this value and any other utility methods - and pass the RenderContext between methods; this can also help you abstract away from the underlying implementation if you need to unit test, etc.
As you find you need more properties (and you inevitably will), you just extend the RenderContext class - nothing else changes.
(edit)
Also - consider the future: will you ever be doing more than one render at once? Since we all have lots of cores now, etc... static is good if all the threads share a value. There is [ThreadStatic], but that is a bit messy by comparison.
Not bad design at all. In fact, having a Common or Utility namespace and class that exposes static methods and static values centralizes these values in one place so you can ensure that every module in you application is using the appropriate values. It's low cohesion, but acceptable for the benefit. I see no problem with it.
No, that would actually be a perfect candidate for static variables. You can even go one step further and make the class static, so that it can't be instantiated. You can then add all your constants to that class as well as some helper methods if necessary.
The answer is that if the program works and is maintainable, do it.
Static variables aren't a sin, it is just good to know when to use them. :)
If all your classes have to understand this value + do something else, then (unless it's something like pi) you probably should check that your classes have a single concern. Perhaps that 'value' needs to become an object that can do the operations that are currently being done all over your codebase?

Categories

Resources