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 8 years ago.
Improve this question
i do not want to know the difference between singleton and static class first of all.
i like to know when people should use singleton class and when static class.
in my apps i use static class for helper or utility method and use singleton for db connection and error logger class. but with the help of static class can be used to return sql db connection object and as well as error logging system.
i really like to know about other senior developer where they use singleton class and where they use static class.
it will very helpful if some one discuss this matter with sample situation and sample code. thanks
If you are creating loosely coupled system, then there is no way you can use static classes (because they cannot implement abstraction and cannot be injected). Static classes also very hard to mock, so it's not your choice if you are doing TDD or simple unit-testing. So, I use them only for dependencies which are not related to business requirements and should not be mocked. E.g. infrastructure logic like logging or mapping.
I also use static classes for extension methods if I cannot extend existing class, but want handy member-like API. Usually this is a also infrastructure-related extensions, like mapping, or serialization, which do not contain business logic.
A very broad question but will give you the first reason that popped into my head for use of a Singleton.
A Singleton is more appropriate than a dedicated static class when you need to manage the lifetime of some cached objects. Singletons are perfect when you want to refresh state without having to worry about thread safety, for example if you have a class that is being used as a singleton and it has many cached properties or lists that incoming requests may want access to.
The Refresh() method can simply be setting the current instance to a new instance and not having to refresh individual properties of the class:
private static YourClass instance = new YourClass(); // first instance
public static void Refresh(){
instance = new YourClass(); // creates a new, refreshed instance while not needing to worry about thread safety
}
public static YourClass Instance{
get{
return instance;
}
}
I usually use singleton classes when I am creating a database access object. Where I can have the instance of the object anywhere inside an application.
I usually stay away from static classes, which the exception of an occasional loader class when loading particular assets.
Related
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 months ago.
Improve this question
I'm working on an app which uses the Factory pattern to create new objects. In the Factory Class I've added a new Private method called SendApprovalEmail() and I am calling this from within the Process() method.
There are other Factory classes which will have their own implementation of SendApprovalEmail(). Therefore should I make an interface (containing a SendApprovalEmail() method) which these factory classes can inherit from? Or is it an acceptable approach to have a private method on each factory class which is just called from their Process() method?
Looking around the app, they tend to use interfaces when extending the factory classes. Unsure what the pros and cons of this are?
I would not put this in an interface. This would be a good situation to use a protected virtual function — if this method is intrinsic to your factory design (i.e. should be included in all factory classes) rather than just part of this particular factory implementation.
The reason for my suggestion is that you say the function is private. You wouldn’t usually put private methods in an interface.
If it really is private then that would suggest that it is not going to be defined in a similar way for other factories I.e. it is just part of this particular factory’s implementation.
However you other comments sound like it is going to also be a necessary part of the design for other factories. In that case you would make it virtual (or abstract) protected so that it can be redefined in other factory classes.
A private member makes no sense as part of an interface. An interface is there to define a set of methods, a role, an object must always implement. Private methods, on the other hand, are implementation details, not intended for public consumption.
I agree with #sjb-sjb. Depending on what you want to accomplish an interface or abstract method would be way more appropriate. These two options would enforce implementation per class inheritance. An abstract method on a base class would offer far more flexibility. Yeah, but that method cannot stay private if you want to implement inheritance.
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 1 year ago.
Improve this question
Hope you are fine. I started learning C# about 2 weeks ago.I’ve been watching videos since now. Now he is teaching Constructions . I don’t get it. When you can use all strings and all numerical values, why restricting them? I mean does it make things bad if you just let it to be default? I tried many ways but I couldn’t find my proper answer. Your reply is so much to me and I really like to know why?!
There are many reasons why one might want to use a constructor, but they are optional and depend on what the developer wants to do.
Constructors can receive parameters and set values based on the
passed values/objects. So you can have many different constructors setting up the object in different ways
Constructors can also include logic to determine how fields/properties should be set. If at all
Constructors can call other constructors of the same class
Constructors are needed if you are using dependency injection, or
readonly fields/properties.
If you want to create copies of your class object, then constructors
can be very useful way to do this. Especially deep copies.
You can also have a static constructor. It is invoked only once in
the class and it is invoked during the creation of the first
reference to a static member in the class.
Constructors can also be private. And you can have a mix of public
and private constructors.
Constructors are useful in inheritance, to ensure that parent
fields/properties are still set correctly no matter what the child does (the child can then change these of course
Sometimes it is as simple as if you are setting many default values,
it can be easier to read if they are all in the same place where you can group them together can comment on them together
BTW: Even if you don't create a constructor, the compiler will create a default one for you.
So simply put, C# provides you with lots of different options. It is up to you to select the one which suits you best for this specific task & class.
There are several topics you can explore that will show where it is necessary...
Dependency injection and Private Readonly Properties for example.
It can also just be convenient
new Uri(pathNameString) will generate the Uri object you can put in an http request by just providing the string at instantiation.
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
I like the DI feature of ASP.NET Core, but am finding that some of my classes end up with huge constructor parameter signatures...
public class Foo {
private IBar1 _bar1;
private IBar2 _bar2;
// lots more here...
public Foo(IBar1 bar1, IBar2 bar2, lots more here...) {
_Bar1 = bar1;
_Bar2 = bar2;
// ...
}
public DoSomething() {
// Use _bar1
}
}
In case this looks like a code smell, it's worth pointing out that any controller is going to use AutoMapper, an email service and 2 or 3 managers related to ASP.NET Identity, so I have 4 or 5 dependencies before I start injecting a single repository. Even if I only use 2 repositories, I can end up with 6 or 7 dependencies without actually violating any SOLID principles.
I was wondering about using a parameter object instead. I could create a class that has a public property for every injected dependency in my application, takes a constructor parameter for each one, and then just inject this into each class instead of all the individual Bars...
public class Foo {
private IAllBars _allBars;
public Foo(IAllBars allBars) {
_allBars = allBars;
}
public DoSomething() {
// Use _allBars.Bar1
}
}
The only disadvantage I can see is that it would mean that every class would have every dependency injected into it via the parameter object. In theory, this sounds like a bad idea, but I can't find any evidence that it would cause any problems.
Anyone any comments? Am I letting myself into potential trouble by trying to make my constructor code neater?
What you're describing sounds like the service locator pattern, and while it seems tempting to simplify your code by eliminating all those constructor parameters, it usually ends up hurting maintainability in the long run. Check out Mark Seemann's post Service Locator violates encapsulation for more details about why it should be avoided.
Generally, when you find yourself with a class with dozens of constructor parameters, it means that class might have too many responsibilities. Can it be decomposed into a number of smaller classes with narrower goals? Rather than introducing a "catch-all" class that knows about everything, maybe there's a complex part of your application that you can abstract behind a facade.
Sometimes, you do end up with large coordinator classes that have many dependencies and that's okay in certain circumstances. However, if you have many of these it's usually a design smell.
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
In the case of the singleton class seen below, what is the proper way to initialize MyList? Do I refer directly to the field MyList (Option 1) or to Instance.MyList (Option 2)? What's best practice here? My gut says go through Instance, but I'm second-guessing myself and cannot find a definitive answer anywhere.
public class Foo
{
private readonly static Lazy<Foo> _instance =
new Lazy<Foo>(() => new Foo());
private List<string> MyList;
public static Foo Instance
{
get { return _instance.Value; }
}
private Foo()
{
MyList = new List<string> {"a","b","c"}; //Option 1
Instance.MyList = new List<string> {"a","b","c"}; //Option 2
}
}
To start with, I would say that either way is fine. That being said, I prefer the option that doesn't use the "Instance" identifier. The concept of the instance really belongs to the code outside of the singleton class. Inside the class, the fact that it is a singleton should be well known. Thus, specifying the Instance identifier is redundant.
The Singleton pattern is for creating types that can only have one instance, but are still treated like instances of a type, rather than being treated as just a type like static types. So if MyList is part of the single instance, then it should be an instance variable on that instance, not a static member of the class.
One of the perks of the Singleton pattern is that it is easier mock for testing and also easier to transition to using multiple instances later, compared to using static members and classes. For these purposes, making MyList an instance member also helps.
If using an instance, you can write MyList or this.MyList within that instance or Instance.MyList from other places. None of these are more correct than any others, it really depends on what you find readable. The important thing is to not mix conventions, which is the worst readability option.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I am not too familiar with classes and stuff so I am asking for some simple help here.. I've got a lot of database functions which I use a lot so I thought I'd put this into a class which I can call from other classes which require data from the database.
For example I've got a window that outputs a list of people, I've got the same code in the edit person window and I am repeating the same code for both of them.
What class to a I use ? I am very confused. I've implemented it as a static class but I wasn't sure if it was working correctly.
If someone could just give a simple primer on what classes are which I would very much appreciate it.
Thanks
A static class is basically a dressed up global variable. You don't create instances of a static class. All the methods must be static and if it holds onto any data, the data fields must be static. This means that all code that uses this class will be using the same data.
If your intent is to centralize db access pain points like login and session, a static class might be appropriate. Just always keep in mind that calls from different clients will see the same details from the static class.
A non-static class, or instance, is something that stores different data in each instance. You have to create an object instance of the class before you can do anything with it. The advantage of creating an object is that each consumer that constructs its own instance is isolated from any other consumers of that class. If window A constructs an instance of your db class and does operation abc, and window B constructs its own instance of your db class and does operation xyz, abc and xyz will not cross paths - they do not share any data between them.
In general, object instances are usually preferred over global/static classes because the shared nature of static classes creates data dependencies and side effects that the consumer may not be aware of.
You can create a class like this-
public class DBOperator
{
//Only static methods, so no public constructor
private DBOperator()
{
}
// static constructor
static DBOperator()
{
// do initialization stuff
}
// have static functions to operate on your database
public static int ExecuteNonQuery(string storedProc, params object[] parameters)
{}
}
You could put repeated code into a method and call the method from multiple methods.
In regards to the DB class, you could put all your DB code in a class - create an instance of it and call it from within other classes.
The DB class though could end up getting messy itself if you just start "bunging" everything DB related in there.
Read up on OO and look into a more efficient way to design your program.