Best practices for restricting access to enum parameter in C# [closed] - c#

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
Consider for the question this String.Split overload, which takes a StringSplitOptions enum as a parameter.
Isn't it bad that the enum itself is public and accessible to everything that includes the System namespace? I mean, the enum is completely specific to options of the Split method, yet it's available outside of it's scope.
Perhaps there is a better way to model this, like putting the enum inside the String class itself, and accessing it by using String.SplitOptions for instance? I very rarely see this (I actually can't remember any such case now), so I assume it is not preferred for some reason. In general, I think reducing the scope of things is a best practice because you lower the chance of problems occurring by using a class/member in an incorrect scope, so to speak.
I'm using Split as an example here, but it is quite common for a Enum to be used only by a method or class in our code base too. I generally create the enum as a public type in a separate cs file like any other class, but I would love to hear other approaches to this 'problem'.
Update:
I just found this article that attacks this exact problem, with a Folder class and a Filter enum but again seems go against what I believe would be more correct in that case (placing the enum inside the class somehow). One of the comments in there from ToddM (which I happen to agree with) states:
...
But, even then, I feel your logic is wrong. Your main complaint
against embedding the enum inside of the class is that it will take
too long to type. Given how verbose C# tends to be, this is not really
a sensible argument. In VS, CTRL+SPACE is your friend.
Logically, I feel placing the enum inside of the class is far more
correct. Take your example: what is a MyNameSpace.Filter? Where does
it apply? I guess it's a filter for your namespace? It's impossible to
tell, especially if your namespace grows to contain dozens of classes.
Now consider MyNameSpace.Folder.Filter -- it is, in my mind, far more
intuitive that Filter applies in some way, shape, or form to the
Folder class. Indeed, another class can be added to the namespace with
its own concept of filter, one of whose members may be 'File'. Just
because you've introduced a new class into the namespace doesn't give
you the right to pollute that namespace with various 'helper' types.
If you are developing as part of a large development team, your style
is, well, rude.
...

It's an interesting idea to nest the enum in order to suggest that it has a reduced scope, or to give it better semantics. I have used this idea before in order to have both error codes and warning codes in a post-compiler I developed. This way, I could use the same enum name Code nested either in the Error class or the Warning class.
On the other hand, public nested types are generally discouraged. They can be confusing to clients who have to qualify them with the outer class name. Look at the related guidelines on MSDN. Some that are relevant:
DO NOT use public nested types as a logical grouping construct; use namespaces for this.
AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios.
DO NOT use nested types if the type is likely to be referenced outside of the containing type.
For example, an enum passed to a method defined on a class should not be defined as a nested type in the class.
I believe those guidelines were followed when developing the StringSplitOptions enum, and most of the others in the BCL.

String.Split() is public, so StringSplitOptions has to be public too. Both String and StringSplitOptions exist in the System namespace. Both have public scope. Neither is "available outside of [the other's] scope".

I think one of the reasons is that it would make every call using an embedded enum wider (the name of the class becomes a mandatory prefix).
I personally wouln't appreciate having to use ResultSetTransformer.ResultSetTransformerOptions every time I have to use this enum, it would make my line horribly long.
But as others pointed out, I don't think it's standard in the framework to embed enums in classes at all, possibly for this reason.

Related

Static and Non Static methods [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 6 years ago.
Improve this question
Good Morning,
I am working on WindowsForm. I came up with 2 solutions. I wanted to know which solution is good practice to follow?
Solution 1:
I have a written a common static methods for validation like phone-text box, mandatory_textbox-key press etc.I have many common methods like this. So what i did is i created a utility class and placed all these static methods in it. Then used these methods across the application.
Solution 2:
i got an idea, so what i did is i created a baseform-inherited Form class, Then i inherited this baseform in all the other forms(Multi-level inheritance).
In the baseform i moved all the validation methods from Utility class and made then non-static.
I also taught about UserControl. If i do that i have work with the alignment tasks again. So that only came up with the two solutions
So Can you suggest which to follow?
You can move the static methods inside non static classes, and pass concrete objects (maybe through interfaces) to the classes/methods who needs that functionality. This way you keep your code easy to test, and decoupled.
By example if you have a class PhoneNumberValidator implementing the interface IValidator which have a method bool Validate(string phoneNumber), and pass it where you need to validate a phone number.
I guess this wuould be the best practice to have a decoupled application.
There in no straightforward answer on whether one should declare methods as static or not. It depends on the context and functionality of your application.
Going with some assumptions for your situation, consider following thoughts on high level -
If the validation is related to one particular form only, and not applicable for other forms, declare it within your form class ans private method. If these validations do not require any class instance, you may declare them static.
If some validations are common for different form, you may declare them as static. Do take caution and do not pass controls to these methods, instead pass the values that you want to validate for better design.
Consider declaring validations in base form only if those are applicable to all or if not most of the forms, and again, if they do not use any instance object, you may mark them as static
A good discussion here.
Use User Control instead of a separate form, if these common controls are being used in every form. Static methods are supposed to be used for utils kind of requirements.
Some times ago I tried to use both solution described by you for different tasks. Every of this have own pluses and minuses.
So, in first case we have only one ststic class and one implementation of every static methods in memory. We can apply this methods to any quantity of other object instances. But we need access this class in every namespace where we will use it.
So, if we will make some changes in any code of this class, it will be applied to all object instances related this class. Sometimes it's convenient, sometimes not.
In second case we will got new instance of base form in memory (less efficient), but we also have one base implementation of methods for inherited forms like first approach. As additional benefit we always can override methods for special cases (if it's needed) for some specific instances only.
In any case, only you can make right decision based on your task context.

What is the danger of not using C# namespaces? [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 9 years ago.
Improve this question
I have proved to myself that the namespace is not required to compile and run an application. However, what are the dangers and pitfalls of not using a namespace? It creates layers that I am trying to avoid.
I know you're screaming but what about agile and abstraction so that 20 layers of abstraction exist between the code and the object. I'm not asking if it violates this or that flavor of the month agile thing. Just what, if any, real world issues come about by not using a namespace?
Edit:
Creating a stand alone class dll so no conflicts within the class project. Trying to avoid when I include it in other projects having to use full qualified name. myNamespace.myClass MyClass = new myNamespace.myClass();
From the comments it appears that naming conflicts are the biggest problem.
Guess I should use a using statement and buck up...
Namespaces have two principle uses:
First, they enable the consumers of your code to more easily understand, find and correctly use your code. There is a reason why the system diagnostic tools are in System.Diagnostics namespace. It's so that customers can know what the stuff in there is for.
Second, they are a mechanism for preventing name conflicts.
The first is actually by far the more important. Conflicts aren't that common. Still, they are possible and judicious use of namespaces prevents them.
If you don't care about your customers finding, understanding and using your code, and you don't have naming conflicts, then sure, skip using namespaces.
It creates layers that I am trying to avoid.
There are no real additional "layers" created. The namespaces purely allow a way for the types to be organized, and help prevent naming collisions as projects get larger and more libraries are used.
As far as the runtime is concerned, there are no namespaces - all types are fully qualified, and the namespace in C# just changes the type name. Leaving the namespace off just makes your type name more likely to conflict with other names, but will have no "real impact" on whether or not the code works, provided you don't use the same name more than once in your project, or use a name that's the same as a name of a type from a referenced assembly and imported via using.
Edit in response to comment:
What I mean by "it creates layers" is that when I create the object I have to add the namespace as a layer. (i.e. myNamespace.myClass MyClass = new myNamespace.myClass();) "
Note that this is only required if you don't have a using myNamespace; statement, or if you use multiple namespaces within the project. If you're always working within the project's default namespace, then you will not need to qualify the name.
It might be a good idea to compare what life without namespaces looks like. The C language does not support namespaces. And very early in its existence, the open() function was used to open files.
Which means that no C programmer may ever use the name "open" for their own function.
Painful isn't it?
Namespaces help you use short and descriptive names. They do not add layers, they only create longer names. That you can very easily write shorter, the using directive makes it easy.
You can end up with conflicts and isn't standard practice for C#. It won't truly hurt anything in the long run.
A conflict could arise if you named your class the same thing as another visible class. For instance, if you named your class Math and had a using System; using statement, there would be a conflict that would only be resolved by specifying System.Math.
Again, not the norm and not something that should be published outside of internal use, but it sounds like you already know that :)

Coding style with generics and inheritance [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to name C# source files for generic classes
We are currently re-evaluating how we do generic classes when we inherit from a general class. Currently we will put the following two class definitions in the same file
class Foo
{
// code for class
}
class Foo<T> : foo
{
// code for class
}
My question is a simple one, should we keep them in the same file, or split them into separate files?
So far the pros to keeping them in the same file is that you have all the code there right infront of you. The con is that when both classes get sufficiently large, it could become un-readable.
What I would like is good reasons as to why we should do one or the other. If you recommend separate file, I would also like you to include possible naming conventions, or a strategy to get around the fact that we can have only one file named Foo
This is a matter of opinion, but I'd keep them in the same file rather than try to maintain some naming convention for one or the other.
While I subscribe to one class, one file, I think there is value in having these together. We really treat these as one class, right? Typically, Foo will be abstract, and is just a way of using our generic types… well, more generically -- in places where the type parameters don't matter and can't be known at compile time.
If the classes become too large, it should be a red flag anyway that some responsibilities should be broken out.
Unless classes are utterly trivial, I never put more than one in a single file. It's much easier, IMO, to find exactly the class you seek when you have a predictable, unique file name, with namespaces based on folders, generally.
For naming your files, maybe this:
foo.cs
foo_t.cs
foo_tuv.cs // for a foo class with three generics
I'd recommend keeping the classes in the same file. It makes it easier to locate all Foo classes. Also, with code folding (regions) you can easily view only a single class by collapsing the other.
That said, I wouldn't say either way is wrong. In the end this is one of those things that will take some experience to come up with your personal preference and find what works for you in your particular project. And you may find that what works well for one project doesn't necessarily work for your next project.
Answered here:
I think the common solution to this problem is to name the file like
this:
{ClassName}`{NumberOfGenericParameters}
This would give you this filename:
Bag.cs and Bag`1.cs
This is the way Microsoft handle this issue in frameworks like Asp.net
Mvc.
Keep these classes small and you can keep them in one file. If you can't keep them small, divide them. If you prefer keeping them in separate files, it's okay too. But keep them small anyway. In case of separate file, I would use FooGeneric name but someone here How to name C# source files for generic classes recommends Foo`1 (for 1 parameter).

fields not allowed in C# interface

There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.
Does anyone has explanation why it is so?
A field is an implementation detail of a class and should not be exposed an its interface.
An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.
You can declare properties in interfaces instead.
UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.
I've rarely wanted to have an actual constant in an interface - they usually make more sense in classes. The practice of using a Java interface to just contain constants (in order to reduce typing in classes that use them) is nasty; I'd only put constants in interfaces where they were related to functionality within the interface itself.
However, on occasion I've thought it would be nice to be able to define an enum within an interface, if that's the only context in which the enum is anticipated to be used. Interestingly, VB allows this even though C# doesn't.
Effectively both of these would be a way of turning the interface into a "mini-namespace" in its own right. However, I can't say I've missed it very often when writing C#. As the C# team is fond of saying, features aren't removed - they're added, and the cost of adding a feature is very high. That means the feature really needs to pull its weight - there has to be a significant benefit before the feature is added. I personally wouldn't put this very high up on the list.
Related thought: it might be nice to be able to define a nested class within the interface, usually an implementation of the interface - either to express its contracts or to act as a "default" implementation for situations where there is such a thing.
and adding constants to interfaces is discouraged in Java too (according to Effective Java at least)
Adding constants to an interface is wrong and should almost never be done. In the past many people declared Interfaces with many constants and then made another class implement this interface so they could make use of the constants without qualifying said constant. This is of course another anti pattern and was only done because people were lazy. If you really want a constant in an interface define a method that returns that constant.

evaluating cost/benefits of using extension methods in C# => 3.0 [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 6 years ago.
Improve this question
In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ?
< full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" >
I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text.
A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands."
While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions.
Looking at MS's guidelines at link text, you find :
In general, you will probably be
calling extension methods far more
often than implementing your own. ...
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type. For more information,
see Inheritance (C# Programming
Guide). ... When the compiler
encounters a method invocation, it
first looks for a match in the type's
instance methods. If no match is
found, it will search for any
extension methods that are defined for
the type, and bind to the first
extension method that it finds.
And at Ms's link text :
Extension methods present no specific
security vulnerabilities. They can
never be used to impersonate existing
methods on a type, because all name
collisions are resolved in favor of
the instance or static method defined
by the type itself. Extension methods
cannot access any private data in the
extended class.
Factors that seem obvious to me would include :
I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ?
Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ?
How frequent use of Extensions would affect run-time performance or memory use : I have no idea.
So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing.
thanks, Bill
My greatest usage for them is to extend closed-off 3rd party APIs.
Most of the time, when a software developer is offering an API on Windows these days, they are leaning more and more toward .NET for that extensibility. I like to do this because I prefer to depend on my own methods that I can modify in the future and serve as a global entry point to their API, in the case that they change it.
Previously, when having to do this, and I couldn't inherit the API object because it was sealed or something, I would rely on the Adapter pattern to make my own classes that wrapped up their objects. This is a functional, but rather inelegant solution. Extension methods give you a beautiful way to add more functionality to something that you don't control.
Many other peoples' greatest usage for them is LINQ!
LINQ would not be possible without the extension methods provided to IEnumerable.
The reason why people love them is because they make code more readable.
I have noticed another MAJOR usage of extension methods (myself included) is to make code more readable, and make it appear as if the code to do something belongs where it is supposed to. It also gets rid of the dreaded "Util" static-god-class that I have seen many times over. What looks better... Util.DecimalToFraction(decimal value); or value.ToFraction();? If you're like me, the latter.
Finally, there are those who deem the "static method" as EVIL!
Many 'good programmers' will tell you that you should try to avoid static methods, especially those who use extensive unit testing. Static methods are difficult to test in some cases, but they are not evil if used properly. While extension methods ARE static... they don't look or act like it. This allows you to get those static methods out of your classes, and onto the objects that they really should be attached to.
Regarding performance..
Extension methods are no different than calling a static method, passing the object being extended as a parameter... because that is what the compiler turns it into. The great thing about that is that your code looks clean, it does what you want, and the compiler handles the dirty work for you.
I use extension methods as a way to improve the functionality for classes without increasing the complexity of the class. You can keep your classes simple, and then add your repetitive work later on as an extension.
The Min() and Max() extension methods are great examples of this. You could just as easily declare a private method that would calculate these, but an extension method provides better readability, makes the functionality available to your entire project, and didn't require making an array any more complex of an object.
Taking the sub-classing approach vs. extension methods requires a couple of things to be true
The type must be extendable (not-sealed)
All places the type is created must support a factory pattern of sorts or the other code will just create the base type.
Adding an extension method requires really nothing other than using a C# 3.0+ compiler.
But most importantly, an inheritance hierarchy should represent an is-a relationship. I don't feel that adding 1 or 2 new methods / behaviors to a class truly expressing this type of relationship. It is instead augmenting existing behavior. A wrapper class or extension method much better fits the scenario.
In some cases you can't use a subclass: string for instance is sealed. You can however still add extension methods.

Categories

Resources