C# static constructor in instance class -- Pros & Contras - c#

I use static constructor in instance class to make this class initialization with some Resource constants. My more experience colleague remark, that it is bad C# style as any static in code. More reliable with his opinion is external public readonly class for this.
However, VisualStudio C# provide run of internal static constructor at first address to common resource, vs external class, which i should call from higher program level. Isn't it a source for additional errors? Am i correct with this logic?

The question you ask is about coding style. Some prefer using static, some prefer to avoid it.
Static can be very helpfull and there are a few features which rely on static. For instance Main, Class Extension, Singleton pattern.
I was greatly using static for my own code because it makes a lot of things easy (you don't have to worry about building the shared stuff). However, when I started doing unit testing I felt more and more unconfortable with it. Static data by definition will be created once and shared which means that for unit tests this data will be shared by the tests. It makes tests independancy much more difficult, forcing you to reset manually everything in your Setup/Teardown methods.
In a few words, for the purpose of unit testing and modularity, I would discourage you from using static constructor for data which isn't immutable (or at least that you use as immutable -> read only access). Immutable data is not an issue as it won't be altered while the program (or the tests) run and you can always be confident about it's value.
Again this is some kind of coding style and some people will disagree and that's fine (as long as they know why they prefer another style)

Related

Why would I use static methods for database access

So I came across this issues today and I couldn't find some meaningful explanation is there some non-subjective reason to use static methods when it comes to database interactions.
Right now I'm working on a project where everything is made through stored procedures and for example I have some regular methods like :
public void Delete(int clientID)
{
//calling store procedure
}
or
public void Save(int clientID)
{
//calling store procedure
}
but I also have :
public static Client GetByID(int id)
{
//calling stored procedure
}
or
public static int AddNew(string firstName, string lastName...)
{
//calling store procedure
}
and since I'm working with .NET for about 9 months and I've been using only Entity Framework and Repository Pattern I can't recall anywhere or any code where static methods were used. Not for standard CRUD operations, neither for more specific tasks related to the database.
So is this something related to the particular way that the database is accessed, is it some practice that can give (even a very small) performance boost, or it's just the developers approach and I shouldn't give it much of a thought when and when to not use static methods in my database related methods?
In the particular case of a data access layer I'd avoid static methods for one simple reason... coupling.
Static methods can't implement an interface, instance methods can. By using static methods one is essentially insisting against coding to an interface and instead coding to an implementation. Thus, everything which uses this data access layer is required to this this specific data access layer at all times.
No alternate implementations, no test stubs, no dependency inversion at all. The business logic has a dependency arrow pointing to an infrastructure concern (the data access layer), whereas that should be the other way around.
Additionally, it seems like this at least carries a greater risk of having problems with the disposal of resources. That might not be the case here, but it's really easy for it to become the case. What if a developer somewhere down the road has the bright idea to extract common lines of code into a class-level static method and property? Something like the Connection or DBContext object? That'll create some very interesting and very difficult-to-debug run-time errors.
On the other hand, if repositories were instances then they can simply implement IDisposable and make sure any class-level objects are correctly disposed.
Continuing (I guess I had more objections to the design than I thought), this feels very counter-intuitive to me from an object-oriented sense. Perhaps this one is just personal preference, but this is turning what would otherwise be a "repository object" into a "dumping ground of DB helper methods."
In a system like this I would expect the number of random one-off methods to grow significantly over time as developers make quick solutions to meet requirements without thinking about the overall architecture. Instead of a consistent and well-managed series of objects, you could very likely end up with a bloated and difficult-to-follow codebase.
Static methods are used when there is either no state, or shared state. If you have code that is merely calling stored procedures, then it may have no state other than a shared database connection string. This would be a valid use of static methods.
I think your last statement is correct; its just the previous developers approach.
I will say, though, that having those methods static is going to make your life a nightmare to create a testable product; if you have the power to change them to be instance based and create a set of unit tests that can test the app via mocks without needing a database it'll make your life easier in the long run.
We very rarely use them here in our company, although they can serve a purpose in utility classes or things of the sort that are simply calling functions. Depending on how many instances you would expect of a non-static class, they can also affect performance., but that would need to be a notable instance difference.
source - MSDN

Design issue: static class only initializes once, breaks unit testing

I have a static Configuration class responsible for data settings for my entire system. It loads certain values from the registry in its constructor, and all of its methods are based on these values. If it cannot get the values from the registry (which is possible if the application hasn't been activated yet), it throws an exception, which translates to a TypeInitializationException, which is fine by me.
I wrote unit tests using NUnit to make sure that Configuration's constructor handles all cases correctly - normal values, blank values, Null value. Each test initializes the registry using the relevant values and then calls some method inside Configuration.
And here's the problem: NUnit has decided to run the Null test first. It clears the registry, initializes Configuration, throws an exception - all is well. But then, because this is a static class whose constructor just failed - it doesn't re-construct the class again for the other tests, and they all fail.
I would have a problem even without the Null test, because Configuration probably (I'm guessing) gets initialized once for all classes that use it.
My question is: Should I use reflection to re-construct the class for each test, or should I re-design this class to check the registry in a property rather than the constructor?
My advice is to re-design your Configuration class a bit. Because your question is theoretical in nature, with a little practical aspect (failure of unit test), I'll provide some link to back-up my ideas.
First, make Configuration an non-static class. Miško Hevery, engineer at google, has a very good speech about OO Design for Testability where he specifically touches global state as a bad design choice, specially if you want to test it.
Your configuration could accept RegistryProvider instance through constructor (I assume you heard about Dependency Injection principles). RegistryProvider responsibility would be just read values from registry and that's the only thing, that it should do. Now when you test Configuration, you will provide RegistryProvider stub (if you don't know what stubs and mocks are - google it, they are simple in nature), where you will hardcode values for specific registry entries.
Now, benefits:
you have good unit tests, because you don't rely on registry
you don't have global state (testability)
your tests don't depend on
each other (each have separate Configuration instance)
your tests don't rely on environment, in which they are executed (you may not have permissions to access registry, but still you are able to test your Configuration class)
If you feel like you are not quite good at Dependency Injection, I would recommend a marvelous piece of art and engineering, provided to mortal souls by the genius of Mark Seemann, called Dependency Injection in .NET. One of the best book I've read about class design, which is oriented to .NET developers.
To make my answer more concrete :
Should I use reflection to re-construct the class for each test?
No, you should never use reflexion in your tests (only if it is no other case). Reflexion will make you tests:
fragile
hard to understand
hard to maintain
Use object-oriented practices with conjunction of encapsulation to achieve hiding of implementation. Then test only external behavior and don't rely on internal implementation details. This will make you tests depend only on external behavior and not on internal implementation, which can change a lot.
should I re-design this class to check the registry in a property
rather than the constructor?
Designing you class as described in my answer will make you able to test your class not accessing registry at all. This is a cornerstone of unit tests - not to rely on external systems (databases, file systems, web, registry, etc... ). If you want to test if you can access registry at all - write separate integration tests, where you will write to registry and read from it.
Now I don't have enough information to tell you whether you should read registry via RegistryProvider in Configuration constructor, or lazily read registry on demand, that's a tricky question. But I definitely can say - try to avoid global state as much as you can, try to minimize dependency on implementation details in you tests (this related to OO principles as a whole) and try to tests you objects in isolation, i.e. without accessing external systems. Then you can mimic exceptional cases, for example does you class behaves as expected when registry is no available? It is really hard to re-create such scenario if you access registry directly via static members of a Configuration class.
static classes / methods are notoriously hard to unit-test.
(Also notice that what you're currently doing isn't unit testing at all; it's integration testing (you're changing registry values for your tests).)
I'm afraid you'll have to choose between your class being testable and it being static.
A compromise you could make is to move the 'logical' bits (i.e validation etc.) to a different, non-static class, which will be called by the main static class.
That non-static class can be then easily tested.
I would opt for redesign.
Also having a TypeInitializationException if anything goes wrong could confuse the user/developer.
I would suggest adapting your code to use the singleton pattern as a first step.

Is it bad form to try and have classes other than main/form1 interact with each other? [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'm trying to learn the correct way to use classes in my code, when it's not something obvious like a set of customers, dogs inheriting from animals, etc.
I've broken off large sections of code into "features" such as Installer.cs, Downloader.cs, UiManager.cs. The only way I can find to have those classes interact with each others' properties and methods is to make them all static, which I've been told in another question is the wrong way to go.
So my problem is one of 3 things:
There is a way to make classes talk to each other that I just don't understand yet.
Classes should never try to talk to each other, but perform one-off actions and then return something back to main/form1, which the main class can then use to pass into another class for a one-off action.
Classes are really only useful for making lots of instances, and there's some other structure entirely I need to learn about for abstracting large chunks of functionality out from the main class.
All the tutorials I can find and lectures I watch seem to only tell you how classes work, but not when and how to use them in a real product.
EDIT - A more specific example:
Say I have one string that is central to the entire app, and needs to be seen and/or modified potentially by every class. How do I move that information around the code without either having everything in one class or making it static?
I can't see a way to let that string live in Form1 without making it static (because all the form events and functions would need to be able to see it to pass it to a class).
I can't see a way to put the string into another class without having to make the string and the whole class static, so other classes can see into it.
Maybe there's something I'm missing about actually instantiating the classes, and making objects interact with each other.
I think all your intuitions are right.
No, there's not. Static or instance.
It's a design choice (and there's a lot out there). I'm a pragmatic, so I consider a design pattern that generates spaguethi code a bad design pattern choice. But a bad design pattern for a project can be a good design pattern for another project. Try to read the Head First Design Pattern book.
Yes, there are interfaces and abstract classes.
A few more thoughts:
I don't think the use of static methods or classes must be avoided. What must be avoided is the miss use of a static method or class, like the miss use of everything inside a language. But is very hard to define what's a miss use of a static, and because static methods or classes are particulary dangerous, people like to say to avoid the static keyword at all. A static method will be in memory unless you end your application, so if you don't dispose a connection inside a static method, you will have a very bad day.
I have a utility project, and inside the utility project I have a data class. The data class provides access to the database. It's a static class. Why?
Well, first of all, it is static because the connection string comes from the webconfig. So I have a static constructor (runs once when the application starts and the class is mentioned) who reads the webconfig and store the string in a static private member variable. I think it's a lot better than read the webconfig file and create a scoped variable 10 bilion times day. The methods are static because they are simple enough, meaning that they don't need a lot of configuration to work, they just need a few parameters and they are used only in the data access project. All my website users are using the same instance of the method (the static one), but everyone uses the static method with different parameters, so they get different responses from it (they share the pipe, but they drink different water). It's only necessary extra care inside the method to clean everything (dispose every scoped instance), because if you don't they will stay in memory. And finally, my bussiness is about data manipulation, a non static data class means a lot more memory usage than a static one (the cpu usage is almost the same in both patterns).
public abstract class Data
{
[...]
static Data()
{
#if DEBUG
_Connection = ConfigurationManager.AppSettings["debug"];
#endif
#if RELEASE
_Connection = ConfigurationManager.AppSettings["release"];
#endif
[...]
}
[...]
}
In the end of the day I use static when:
If it is simple enough (that I can control every aspect);
If it is small enough (I use extension methods to validations, and they are static) and;
If it is heavy used.
Besides that, I use layers to organize my project (poco + factory pattern). I have a utility project, then a entity model project, then a access project, then a bussiness logic project, then a website, a api, a manager, and so on. The classes in the utility project don't interact each other, but the classes inside the entity model project do (a class can have a instance of another class inside it). The entity model project don't interact with the utility project because they have the same level, they interact each other in another level, in the access project, but it's more intuitive in a data manipulation project.
Classes talk to eachother when they have a reference, in order for A to pass a message to B, A needs a reference to B (either an instance or static reference)
Classes can either talk to each other, or return information to another class that controlls the whole process (this is actually a design pattern)
For abstracting information from the main class (or any class) you have interfaces and abstract classes
The Design patterns book from the Gang of Four it's a must read in this case.
Something else to keep in mind beside is the simplicity of your design, sometimes trying to fit to a design pattern just cause may end up creating more spaguethi code. As a rule of thumb always try to sepparate the presentation funcionality from the logic, and think of classes as persons talking to eachother and performing jobs (it's kinda weird iknow but sometimes it helps me to think this way)

Unit tests in same class (with conditional compilation)?

I'm aware of (and agree with) the usual arguments for placing unit tests in a separate assembly. However, of late I've been experiencing some situations where I really want to be testing private methods. The behind-the-scenes logic in question is complex enough that testing the public and internal interfaces doesn't quite get the job done. The testing against the class's public interface feels overwrought, and I see several spots where a few tests against privates would get the job done more simply and effectively.
In the past I've tackled these kinds of situations by making the stuff I need to test protected, and creating a subclass that I can use to get at it in the test framework. But that doesn't work so well on classes that should be sealed. Not to mention bloating the test framework with all that scaffolding.
So I'm thinking of doing this instead: Place some tests in the class, where they can get at the private members. But keep them out of the production code using '#if DEBUG`.
Does this seem like a good idea?
Before anybody asks...
The solution to OP's problem is to properly incorporate IoC with DI and eliminate the need of testing private method altogether (as Joel Martinez noted). As it's been mentioned multiple times, unit testing private members is not the way to go.
However, sometimes you just can't change the code (legacy systems, risk of breaking changes - you name it) nor you can use tools that allow private members testing (like Typemock, which is paid product). For such cases, you can either not test at all, or cut corners. Which I believe is situation OP's facing.
Leaving private methods testing discussion aside...
Remember you can use reflection to access and invoke private members.
In my opinion, placing conditional debugs in the class itself is rather bad idea - it adds noise (as in, something unrelated) to the class code. Sure, it will be gone in release, but you (and possibly other programmers) will have to deal with it on the daily basics.
I realize your idea might sound good on paper - simple test wrapped with conditional debug. But in reality, tests quickly turn out to use extra variables (those will also have to be placed in the class code), some utility (extra references, custom types), testing frameworks (even more references) and what not. This all will have to be somehow connected to the class code. Put that all together, and you quickly end up with an unmaintanable monster.
Are you sure you want to deal with that? Especially considering that throwing together simple reflection-based utility is probably not that hard.
Everything you're referring to can be solved with just two concepts: Single Responsibility Principle, and Dependency Injection. It definitely sounds like you need to simplify your classes. Mind you, that doesn't mean the class must offer less value, it just means that the internals need to be simpler and some functionality may have to be delegated to others.
If you need to test this method independently of the public API of the class, then it sounds like a candidate for being removed from the class itself.
You could say the class is dependent on the private method (as is arguably evident by the need to test it separately from the class public API).
If this dependency cannot be satisfied through testing the public API of the type alone then have the class instead delegate this dependency to another type. You can either instantiate this type internally or have this type injected / resolved.
This new type can then have its own unit tests, as it's public API will be expressing what was previously a private method.

Should static classes be avoided because it makes Dependency Injection Difficult?

Somebody tasked with creating a "Core" set of libraries created a set of static classes providing all sorts of utilities from logging, auditing and common database access methods.
I personally think this stinks because we now have a Core set of libraries that are hard to test because I can't mock / stub these classes or do any injection into their constructors.
I suppose I can use TypeMock to stub these out but I'd rather do it for free.
What do you think?
Edit
If you don't think they're hard to test could you give an example of how you would test them. These static classes instantiate other types to do their functions.
Static classes (methods) do not necessarily have to be avoided as long as they have no hidden dependencies. Of course you can pass dependencies into a static method - it just should not be stored internally and modify the behaviour of later calls.
There should be no problem to test them in this case, too.
But I have a bad feeling about the cases you mentioned, too. I know some of these static "wrapper" utility classes - and in most cases they really stink :)
EDIT:
Maybe I should clarify. I would use static classes/methods only for very small distinguished tasks. When static classes start to initialize dependencies they certainly should be avoided. If you can't test these static classes they already have a too big job to do.
In the first answer of this question are the arguments against static classes as you mentioned.
How hard would it be to modify those static classes to utilize Dependency Injection? If you make the DI optional (if possible), you can essentially make a situation where you can use the static classes for mocking, just by properly doing the DI, while not changing any of the "normal" behavior.
Following is from Journal of Object Technology: Decoupling responsibilities from static methods for fine-grained configurability
Static methods pose obstacles to the development of tests by hardwiring instance creation. A study of 120 static methods in open-source Smalltalk code shows that out of the 120 static methods, only 6 could not equally well be implemented as instance methods, but were not, thus burdening their caller with the implicit dependency on these static methods

Categories

Resources