When to use 'Static Methods' in C# [closed] - c#

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 9 years ago.
Improve this question
I have a bunch (may be 10 to 15 ) methods in my C# code all of which are 'Static'. Obviously, all of them are called with the ClassName. All works well. But, are they any advantages/disadvantages of using them that way? or would I get any performance benefit if I do not use 'Static' for my methods?

Technically there is slight performance benefit when you are using static method, because you don't need to load instance reference to stack when executing method. But that is really minor optimization which you will not notice.
From programming point of view static methods are hard to mock and they introduce strong coupling with implementation in your code. Also you lose benefits of abstraction and polymorphism when use static methods.
You can make static private methods from instance methods which don't use instance data. But public static methods usually give you problems with mocking and dependency injection, so usually I avoid them. One exception is factory methods which used to create instances of class - Loan.CreateLongTermLoan (thus you can't have constructor with custom name in C#, but you want some descriptive name which describes details of created instance) or Loan.Parse.

If you're worrying about the performance benefit of static methods over instance methods then you're micro-optimizing and without doubt prematurely optimizing. You should worry about good class design before you worry about this sort of thing!
If you've got methods that don't operate on the state of an instance then they are good candidates for being static methods. For example, factory methods are an obvious use of static methods.
If you've got methods that operate on the state of the instance then they need to be instance (non-static) methods. For example, a method that changes a member variable could not be static.
FYI : At the IL level all instance methods are called via a CallVirt instruction, even if they are not virtual. This allows the runtime to generate a NullReferenceException if you call a method on a null reference. A static method is called via the Call instruction.

No performance benefit for being static or not.
If you don't need an instance of the class in a method, then it's a candidate for being marked as static.

The problem with static method comes the moment you need a sub-class.
Static methods cannot be overridden in sub-classes, hence your new classes cannot provide new implementations of the methods, making them less useful.

It's a conceptual question. Does the method …
belong to a specific instance? Then it's not static.
belong to the class rather than to a specific instance? Then it's a prime candidate for being static.
Note that static methods can't access instance members (non-static members) of an object.

Related

Should a concrete class that implements an interface have extra public methods for testing? [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 3 years ago.
Improve this question
When implementing an interface on a concrete class, is it appropriate to have extra public methods exposed to help facilitate unit tests?
For example, let's say I have the following concrete class:
public class MyClass : IMyInterface
{
public int InterfaceMethod(ComplexObject complexObject)
{
return NonInterfaceMethodOne(complexObject)
+ NonInterfaceMethodTwo(complexObject);
}
public int NonInterfaceMethodOne(ComplexObject complexObject)
{
//Do complex logic that needs to be unit tested
}
public int NonInterfaceMethodTwo(ComplexObject complexObject)
{
//Do more complex logic that needs to be unit tested
}
}
If I wrote my class this way, I could have unit tests for both non-interface methods, but I feel like this pattern is not correct. Is there a better way?
What you have there looks perfectly acceptable to me. A general answer to your question is "it depends," because there could be scenarios where you want to hide those methods, and there could be scenarios where you want to expose them.
It's reasonable to consider your test suite as the first client of your code base, and it makes sense to support the needs of your client--you would still want to give careful consideration to what functionality you want to expose and hide.
In spite of the fact that NonInterfaceMethodOne and NonInterfaceMethodTwo are both public, if you inject this implementation into a parameter of the interface type, the client will still only have access to the interface method and will have no knowledge of the other 2 methods.
A client that is using the implementation will of course have access to all 3 methods, but will still not know how the interface method is implemented.
If it would be useful to expose those methods for unit testing and if you can determine that no damage is done by keeping the methods public, then keep them public.
But, it could still be appropriate to write your tests to ensure that NonInterfaceMethodOne and NonInterfaceMethodTwo work the way you want, then cover your interface method with another test(s), and then you may possibly no longer have a need for the unit tests covering NonInterfaceMethodOne and NonInterfaceMethodTwo--in which case you could remove these tests, and then make NonInterfaceMethodOne and NonInterfaceMethodTwo private--because your unit test(s) covering the interface method covers the other 2 methods.
and if you find that this approach doesn't hide any functionality that your test suite needs, I would lean toward this approach, because it's normally good to limit the functionality you expose
You can get something similar to this, but without having to make the members public, by using the InternalsVisibleToAttribute.
Let's say your assemblies/projects are named ProductCode.dll and TestFixtures.dll. You can make the internal types and members in ProductCode.dll visible to TestFixtures.dll, but no other assemblies, by declaring the following in the ProductCode project (typically in AssemblyInfo.cs):
[assembly: InternalsVisibleTo("TestFixtures")]
Then you can declare these exposed-for-testing-only methods as internal instead of public, but the unit tests can still call them.
If you only run your tests in a Debug configuration, not in the Release configuration, you can make this access control exemption only happen in the Debug configuration by surrounding the attribute like this:
#if DEBUG
[assembly: InternalsVisibleTo("TestFixtures")]
#endif

Static fields - if only one instance created from the class [duplicate]

This question already has answers here:
Static vs non-static class members
(7 answers)
Closed 5 years ago.
I have been having a hard time deciding when I should declare a class filed as static.
I got the idea that a static field is shared among all objects created from a class, unlike a regular non-static field, which is held by each of the objects.
Then if it is known that only one object will be created from a class (because I have seen such cases many times), what is the meaning of a static field?
If the definition of "static" is "shared among all instances," does a static field serve the same role as a regular non-static field, provided there is only one object created from the class?
I got this old project from my boss to study C#, and I see some fields declared as static in a class, but there is only one object created from the class, and I am a bit confused what the point is if it does not have multiple instances.
You should not decide to use static just because there´s only one single instance. As you´ve already mentioned there is an instance.
The question if something should be static depends on if your member depends on an internal state, that is do you need to set some property befpore you can incoporate with this member. So even if there´s just one single instance existing this instance shares a set of members defining its state. Only when your member could omit all those information from that single instance it should be marked static.
However making some member static makes many things - e.g. mocking - quite hard as you create a heavy dependency on your class holding that member

Making interface from class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having some troubles making an interface for my class. I tried with a simple public void and that worked. But i cannot get it to work with the public static voids in the code below. I think it has something to do with the enum as a parameter in the method. But How do i fix this?
This is the class:
And this is my interface:
Interfaces are contracts. They specify the method signatures for all methods within the contract.
In your interface, you have:
void FFT(/*stuff*/)
Yet, in your implementation, you have defined
static void FFT(/*stuff*/)
Now, why can't we use static? From Joel Spoelsky
Because an interface is a "contract" or an agreement between the consumer (caller) and the provider (callee). An interface describes what and how the calle will provide functionality. There is no need for static members provided by a third party. Static members cannot be overridden by a provider so they do not belong in an interface.
Interface is a contract between caller and callee. Static member belong to class not to the object, so its no point of making method static.
To explain why this really doesn't make sense, the reason to make an interface is so you can pass an object of your class as a reference to the interface type, so the consumer doesn't need to know which underlying type the object is. For example, you might pass an IEnumerable<Foo> to a method that doesn't need to know or care if this is an array or a list or a hashset, etc., it just wants a sequence of Foos.
Static methods are not associated with an instance, so there is no object to reference. There isn't the concept in C# of a static interface which could be used to reference a class rather than an object.
If you had other classes that you wanted to use interchangeably, you could get rid of the static and make these singletons.

Should a class with only static methods be static? [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
I have a class with only static methods. Should the class itself be made static too? Does it matter?
Does it matter?
Making a class static ensures that it can never be instantiated by generating a compiler error should the user attempt to do so. If the class, consisting of only static members, is simply not intended to be instantiated, there is no reason not to make it static. You can choose not to do so, but instances of such a class aren't going to be very useful, and users creating these instances are going to be left quite confused.
On the other hand, if you intend for instances of this class to be created but you expect derived classes to implement their own instance members, chances are that this class should be abstract, rather than static (and perhaps those instance members should be stated upfront via abstract definitions or an interface).
In general: Yes.
You can prevent the programmer to create object instances of a certain class by making the class static. If this is what you intend, then do it. This prevents mistakes, by showing (other collegues, etc.) that the class is not intended to be instantiated.
public static class A
{
// Some static member
}
A a = new A(); // Compilation error

need clarification for Constructors in c# [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 9 years ago.
Improve this question
I want to know whether my understanding on the constructors is correct or not. I just tried to attempt a quiz for constructors but confused whether my understanding is correct or not
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, the compiler automatically provides a default constructor.)
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.)
--> A static constructor in a non­static class is called once on each object creation. – False (If a static constructor has been called once, compiler will not call it again, it will get called once only .The execution of a static constructor is triggered by the first of the following events to occur within an application domain: 1. An instance of the class type is created. 2. Any of the static members of the class type are referenced.)
-->You can specify on the constructor which classes of interfaces that class is inheriting
( i don't know please clarify )
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, > > the compiler automatically provides a default constructor.)
- Your understanding is Correct
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a
special instance constructor. It is generally used in classes that
contain static members only. If a class has one or more private
constructors and no public constructors, other classes (except nested
classes) cannot create instances of this class.)
- You can have a private constructor, in which case other classes cannot create instance of it (but why will you do that?)- People do that to put some control in object's instantiation, as what they do commonly in some design patterns. In a nutshell, you can still create an instance of a class with private constructor thru some other means (e.g. from static methods).
--> A static constructor in a non­static class is called once on each object creation. – False (If a static constructor has been called
once, compiler will not call it again, it will get called once only
.The execution of a static constructor is triggered by the first of
the following events to occur within an application domain: 1. An
instance of the class type is created. 2. Any of the static members of
the class type are referenced.)
- Your understanding is Correct
-->You can specify on the constructor which classes of interfaces that class is inheriting ( i don't know please clarify )
- False, You specify in the class declaration itself the interfaces or classes that the class is going to inherit not in the constructor

Categories

Resources