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.
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 2 years ago.
Improve this question
Imagine I have the following class:
public class MyWeirdCollection
{
private IList<string> _myTrueList;
private IList<string> _myFalseList;
public MyCollection()
{
_myTrueList = new List<string>();
_myFalseList = new List<string>();
}
public void Add(string item, bool listType)
{
if (listType)
{
_myTrueList.Add(item);
}
else
{
_myFalseList.Add(item);
}
}
public IList<string> Get(bool listType)
{
return listType ? _myTrueList : myFalseList;
}
}
How would I go about unit testing the Get and Add methods? I'm doubting between 2 possible solutions:
Making the 2 lists protected instead of private, so I can create an inheriting TestableWeirdCollectionClass that exposes the content of the lists to the test
Leave the class as it is and test Add and Get together? i.e. calling Add to add some elements and then Get to see if the correct values come back.
I'm leaning towards option no. 2, but would like some more opinions. Thanks.
Definitely go for the option 2. Pretty much every test I can imagine must go though Add, then Get, together.
When testing you are ultimately testing the public interface, not the internal state. The whole idea of the test code is that you give items to it, then you get them back with the appropriate key. In your particular case it uses private lists to hold the items, but this may not be the case (you might store them to a database or file, rely on another class or something else). This is ultimately an implementation detail, the important bit is that Add and Get always play together, therefore you should it.
I would strongly recommend option 2. The reason is that your whole class should be consider a unit, and be tested as such. Making methods public for the sole purpose of unit testing can be motivated in some rare cases for very complex classes, but should be avoided if at all possible.
See also
Is it bad practice to make methods public solely for the sake of unit testing.
Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject
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
I am writing a game in Monogame framework and well
there are some objects that have only 1 instance
(but that does not necessarily mean that there should be only 1
instance) during the lifespan of an application by default,
like for example ContentManager.
Now what's bugging me is that I am not sure what is a better practice and why:
To make that object public static and access it from other classes
to use that static instance to load stuff
or
Pass that object as an argument to other classes constructor and use it that way
Just to add another option, you can use the singleton pattern to restrict the creation of new classes, like a GameManager. This pattern comes with cons and pros, so you need to analyze your requirements.
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
The simplest way to implement the implement the pattern is to have a class with a private constructor, a static parameter for your instance and a method to return the instance.
https://en.wikipedia.org/wiki/Singleton_pattern
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 5 years ago.
Improve this question
In my program, I have to add new instance of a given class to an ArrayList each time a method is invoked. My code looks like.
public class A
{
List<Object> myList = new List<Object>();
void resetMyList()
{
myList.Clear();
myList.Add(new B());
// Add more strings
// Call other methods
// ...
// Get a list of strings
}
}
public class B
{
public override string toString()
{
return "I'm B";
}
}
One of my colleague suggested to add new property to class A that refers to one instance of class B. So class B will only be created once and stay in the memory. With this solution, we can avoid to make the garbage collector works on creating and deleting new instance of B. Here is his code:
public class A
{
List<Object> myList = new List<Object>();
private B b = new B();
void resetMyList()
{
myList.Clear();
myList.Add(b);
// Add more strings
// Call other methods
// ...
// Get a list of strings
}
}
So which suggestion is better, design and performance wise?
Edit: Please I know that using:
Using List is better than using ArrayList
Codes are not equivalent
I just want to keep the example simple and my concern is about design and memory. Whether to add private member and keep it in memory or create new instance each time and avoid extra members.
Any way I will change the code to use List
Well, First of all - these codes are not equivalent - While in the first code you create a new instance of B every time you clear the ArrayList, in the second one you use the same instance of B all the time. This means that any changes made to this instace (assuming that B is not immutable) will be "canceled" every time you clear the ArrayList in the first code, but persist in the second one.
As to the question of which one is better "performance wise" - It usually depends on so many factors that it's almost always impossible to answer with complete confidence. In fact, it's so hard to answer this question correctly that Eric Lippert wrote an entire blog post about it - and if it's hard for someone like him to answer - it's hard for anyone (unless your name is Jon Skeet :-))
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 8 years ago.
Improve this question
Just being curious.
If I create 2 objects of a particular class, then 2 instances of the instance methods and the instance variables are present in the memory for that particular class?
EDIT: I tried with static and for sure, only one instance of the members were there but not sure with instance variables though.
If I create 2 objects of a particular class, then 2 instances of the instance methods and the instance variables are present in the memory for that particular class?
Instance fields - yes. Instance methods (including property accessors), no. Code (both instance and static) is shared among all instances.
Note that static classes will create an additional type for each generic parameter used, and each of those types will share one set of static variables, so for example:
// for example only, not intended to be a perfect singleton implementation
public class Singleton<T> where t : new()
{
private static T _Instance;
public T Instance()
{
return _Instance ?? (_Instance = new T());
}
}
Singleton<Class1> and Singleton<Class2> will each have a different object in memory for _Instance.
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.