Hello Tim. I'm from Germany and programming in C# since 18 years now. I really enjoy your videos and learned much from you. I just want to say thank you for what you are doing here for us programmers. Videotutorials for free in this amazing quality are rare. So again: Thank you!
May be first cover frequently used design pattern's and then others. I am just loving your explanation on topics and encourage you to do more videos on such topics where i can write clean code
Ive been writing production level code now for nearly two years now, wasn't until I started watching Tims videos that I realised that I didn't know nada.
Hi Tim, Your videos are AWESOME! I have a question. @~24:00, you mention that turning the class to static would bring other complexities that we might not want. What could those be? Thanks!
I'll try to add some information about Singletons. I came from huge fan of Singletons using them everywhere I could to a moderate user. First I think it is interesting to point out Singletons, as design pattern, are one of the best source of discord and debate between programmers. So Tim, you explained very well why they are useful I'll try to explain why some programmers considers them as an anti-pattern (I disagree with that, but they have some interesting arguments). 1) Multi purpose : A Singleton will always have at least 2 purposes : manage his instantiation and the reason why you create it. So by using it you transgress the single responsibility principle. If you know what you're doing it is not a big deal, but still, at this point you already accept to not keep your code SOLID. 2) Most of the time not the best : This is more a problem for beginners which just learned this pattern That for me the biggest problem with singletons they are easy to use and once you now them you will easily want to use them where they really are not the best. They are able to do a bit to much jobs. 3) Unit testing : That a big one. Yes you can unit test with a Singleton in your workflows. But more the Singleton take importance and more the side effect will be hard to manage at some point testing will become impossible because of the complexity of the state management of your Singletons. Finally, Singleton have some unique behavior making them best pattern for some need. To know if I should use a Singleton I ask myself 3 questions : - Do I really need a Single instance class ? - Do I really need to be able to not instantiate it in run time ? - Does the creation of a factory will really be an overkill investment in my program ? Actually I see 2 feature that will very often have those needs : Loggers and seeders it is most of the time the reason why I'm making singletons.
Thanks! One question though: wouldn't simply changing 'nextServer' to static in the original code achieve the same result (so the counter is actually shared between all the instances)?
A static class cannot be instantiated, it cannot implement interfaces, it can't be passed as a parameter, and it cannot be lazy-loaded. You can't change just the method and access the instantiated value. You would need to make everything static to do that.
@@IAmTimCorey Thanks for the reply, but I'm not talking about making the whole class static, ONLY "nextServer" field static (i.e. take your code as shown at around 6:45 and only change "private int nextServer = 0;" to "private static int nextServer = 0;"). That way no matter how many TableServers you instantiate, the "nextServer" counter will be shared between all instances and you will always get the next "non-busy" server when calling GetNextServer(), no matter on which instance of TableServer (which is the same behavior of the singleton example).
@@Fergobirck Im just guessing here...in this case it will produce the same result but you will have two instance of Tableserver and then it will not be a Singleton.
@@Fergobirck the behavior seems to be the same, I agree. The upside of the singleton however is, that you only have one instance of that class loaded and thus it's a bit more resource friendly.
One might thing, if the intention is to simple create a single instance of a class why don't we just make the class static instead of implementing singleton pattern. First problem is, what if I want a derived class to have a single instance. A derived class cannot be made Static. Plus static class brings other restrictions in certain scenarios and it wont serve the purpose. So we need a different mechanism to create a single instance class, so we use Singleton pattern.
19:34 This made me click in the sense that we never talk about how to recover the state of a program when it crashes due to, let's say, a power loss... when there's no chance to cancel tasks, close connections and so on. Would be a nice topic to cover.
That's just RU-vid not updating the video. I had it uploaded for weeks but evidently it waited until it was public to process the rest of the formats. It is 1080p now.
your videos are long and i am impatient but when I clicked on them you are explaining things so well and are truly tapped into the learner's mindset. Thank you!
Personally, I find that the benefits of dependency injection (DI) are greater, than the benefit of real singletons. Real singletons can prevent more usage errors, but DI gives a lot more flexibility, and makes it far easier to switch around between singleton, scoped or transient modes for a given class or service. Another important thing to consider with singletons (both real and DI) is multi-threading. If you're using multiple threads, be sure your singleton is thread safe - otherwise you could easily run into errors, or worse, hard to find/debug race conditions.
Thanks a lot Monsieur Tim Corey, I have one question : Suppose that this application is hosted on a IIS Web Server. This means that two users or more calling the server (means more than 2 user sessions) will be using the same TableServers instance ? Thank you.
@@IAmTimCorey I never seen good YT channel as yours. I wasted so much time those last 7 years... ..I am learning a lot You deserve to have my patreon. thank so much for your quick feedback. Hi from Fr🇫🇷
Another great video! Can we get Strategy or Repository, please? If you make a course on all major design patterns and some other more advanced topics, that would be awesome.
"will not get destroyed for the life of your application". What does the application life look like? Like if it were a web-app, does each user create an "application life" when they access the application, and it is killed upon them closing the application? Two application lives can exist concurrently? Sorry if I'm asking an off topic question, but I'm trying to better understand the possible negative side effects of using singleton design pattern. Thank you!
For a desktop application, it is as long as the application is open. For a web application, it is as long as the web server is running (technically the website, since you can restart the website without restarting the web server).
@@IAmTimCorey Thank you for that clarification Tim. This might be in part why in my organization restarting the web server is a common thing to try when weird issues pop up.
Good tutorial on singletons. I have used them in game design to make inventory systems and never thought of using them for other applications. Will you be going over the observer pattern as well? Would love to see your take on that one
Really enjoyed that one. I'm looking forward to seeing mode Design Patterns videos. As always I learned something new from your videos, thanks for the great content!
Gamma and Johnson (two of the GoF) discussed about this pattern 20 years after the book was released and mentioned they should have reworded the singleton pattern. The way it was presented makes it easy for people to justify making something global which was the main drawback: why have it as a parameter when you can make it global and make the life easier for programmers calling that method. Another drawback is that it makes everything harder to test since you can't stub it directly, you need to wrap it before. Or you need to add a backdoor (like an "internal void overrideServers(List newServers)") to change the internal state of the singleton when testing. On the other side it's useful when dealing with legacy applications where globals are commonly used, you can convert them to singletons (which was the intended way of using it). Personally I rather err on the safe side, I prefer not using it at first but when I detect something is being called way too many times and might be impacting performance (typical example are configurations) I consider using it there.
Hey Corey, I am looking for a way to update my Binding of a static property, if it changes. I read that singletons can help, but I don't understand in what way. I still have to tell the code when the property changes. If I create a normal property get the static property value, INotifyPropertyChanged doesn't work since this only works with SetProperty and there is not GetProperty.
15 mins in the video, you mentioned it's lazy initialisation. Isn't it eager instead of lazy? The static initialisation happens the moment the application is run..
Is it lazy loaded or is it loaded at runtime? I think to lazy load it you need to call it in your GetTablesServers method if it hasn't been instantiated.
Hello Tim, thanks for this amazing video, I truly enjoyed it. However, I recently noticed some noises in the background when you're talking, instead of only having your voice clear. Could you please try looking into it? I find it pretty disturbing. Thank you!
A nice clear explanation. Looking forward to any other design patterns that you might do. My on criticism is that I probably would have mentioned about two methods calling the GetNextServer at the same time and getting the same server. I would then mention locking strategies that can be used to avoid this.
That's just RU-vid not updating the video. I had it uploaded for weeks but evidently it waited until it was public to process the rest of the formats. It is 1080p now.
I don't know... I find these videos both education AND entertaining.... but that's probably just the need inside of me, you know? ;-) And yes. Singletons can very much be one soft cushion too far -- you can easily go overboard very badly. As with EVERYTHING pertaining to programming it's all about picking the RIGHT TOOL for the RIGHT TASK and it's very easy to choose something wrong, and this isn't something you can just learn from reading... this is something you learn through experience, through being responsible for projects and following long term project development because you will rarely see the problems with too many Singletons until way down the road. And to use Singletons scarcely is really the best advice: don't use it unless you absolutely have-to.
Yes, it is necessary. The reason it is marked as static is because we want to have only one instance of TableServers. That instance gets created once, and then it will be just referenced from then on.
Explaining how AddSingleton differs from the actual pattern is priceless. Does the runtime then manage the resources of the singleton created using AddSingleton efficiently then, do you know?
Singleton is literally just a private constructor. That's it! That's the whole pattern! I have no why you took a potentially 3 minute video and turned into 28 minutes.
Be careful of this Singleton. It's awesome, but also dangerous in real world application where there are login sessions and many account users. People could be seeing other people's data. That static keyword means shared variable through the app
I wish I watched your videos at least last few years ago :( . Could you also please suggest good tool for design document? What are the essential applications other than VS a .Net or any developer should have? Please advise.
The singleton class also seems like it could be subject to race conditions in multi-threaded/multi-client environments. I assume a "real" implementation where state transition sequence is important would have to include a mutex implementation..
You should have mentioned what is the difference between using a static class and the singleton patterned class. From the video it isn't clearly visible but it gets clear when you think about dependency inversion. With static classes, it's not possible to pass instances as interfaces (static classes cannot implement interfaces or participate in inheritance). And that becomes important when doing Dependency Injection.
Logging isn't a great singleton situation because then you cannot get class-specific information to log. Typically we don't use a singleton for logging. For instance, in .NET Core, logging is set up in dependency inject as transient (one instance per class).
Typically no, because you want to interact with each instance of the WinForm as if it were unique. If you want them all to be the same, though, a Singleton would work.
Very informative video. I just want to ask what is the better way on writing a report. I have a web API that going to write a report and save to disk when completed. This reporting ulility should be available anywhere so I need a single instance. My problem is what if another client request the service, will they use the same instance?
That's called context. I could have said "a singleton only allows a class to be instantiated once", shown the code, and been done in less than 2 minutes but that would not have taught you anything of value. I don't teach to entertain you. I teach you to prepare you for the real world.
Nope, that's not wise. Singletons have specific purposes (I talked about this in the video). It is not efficient to use a lot of them (more than you absolutely need) and it can be unsafe as well, since you could give users access to the data from another user.
Hi Tim, hope you're doing ok, I wanted to ask you so by all this information is it safe to use SIngleton Design Pattern for seeding data for example city names so that we don't have to do a request in the database each time we want to get data? Thank you!
I have one doubt Tim. You said at 12:05 that if we have or need the list somewere else and make sure those list are sincronized that wouldn't be possible this way. Well, just make the list object declaration public and then call it like so: Program.hostlist.GetNextServer(); Is there any problem with that?
@@IAmTimCorey i don't understand how it limits. I do that and it works. And now i discovered that i can use things like lock and Semaphore to control thread access, wich i think was causing me a crash in my application. To me, a static variable like this is the same as a thread safe singleton. Maybe that's because i'm new at this but i don't see the diference..
That's just RU-vid not updating the video. I had it uploaded for weeks but evidently it waited until it was public to process the rest of the formats. It is 1080p now.
Thank you for your valuable insight, Tim! You are an inspiration! And I also remember the phrase you quoted (about the cure which can be more dangerous than illness) from old and famous French book by De Balzac called Lost Illusions where Eva Seshar told it to her lawyer offering her some weird solutions.
Nice pattern! Great demonstration! Later on in the video, when you discuss Dependency Injection... would it make sense to load an app's configuration as a DI'd AddSingleton() or AddSingleton()?
Hi, Tim! I know you're moving and are working on other Blazor PWA applications. I was wondering if you wouldn't mind looking into a video on merging concepts of the Blazor WebAssembly PWA app, using Azure Functions and Azure SignalR Serverless (also free for limited use), in order to talk to an outside .netcore application (console or otherwise) utilizing the same Azure SignalR Serverless service.
MR. Tim, awesome as always, you'reb eing my programming mentor! My question now is, why in your HTTPClient video you haven't had used the singleton pattern? If you had used it, then we could have the only one instance of HTTPClient and we wouldn't have to have the static one.
I didn't want one instance of the HttpClient. I wanted the HttpClientFactory to handle instances so that it would properly close them down and recycle them. This is safer and cleaner.
Whenever you talk about the SIngleton pattern for a mutable class that holds any data, I think it is also really important to mention thread-safe behaviour, such as implementing locking etc. This will definitely catch out someone naively trying to use this pattern in a web application or other highly multi-threaded environment. You could have quickly mentioned this issue and/or done a brief demonstration of lock in your GetNextServer() method (which is currently not thread-safe). Otherwise a great video!
Thanks for the lesson!!! Just a quick question to understand it better, would be useful to have Dispose() for the instance in the finally block to kill the instance everytime it finishes the execution?
You only need to implement IDisposable and/or Dispose of the object if you have something open that you need to close down properly (database connection, memory stream, etc.). In our case, we have nothing that needs to be closed down in a specific way. Objects themselves don't need to be disposed on their own.
Great video! I just think there should have been some statements about the disadvantages of Singleton. Like testability concerns, direct access from any/to any place which is a risk for spaghetti code, etc. I highly recommend not to use this old singleton pattern. Di really solves those things.
It's great that you are getting into the Gang of Four design patterns. Please keep going. But is the TableServers example a true "singleton" implementation? It doesn't prevent the users from still creating separate instances. I think a Singleton class should not be allowed to be used any other way. So you have to lock down the true instance by making the constructor private.
Hey! I'm not receiving an Email with the source code for this specific video. Tried it yesterday and tried again today. Any chance that's getting fixed? Thanks in advance.
Hi Tim, I have gone through a couple of vedios you made on design principles. Found all of them more explanatory and very useful. Thanks a lot for this.
Thanks for the video! Singleton has given me a lot of freedom making a bunch of similar utility classes that can implement an interface (which can't be done with static classes, I learned). One question: Does the positioning of the static implementation line matter? Could it be at the bottom of the code block for instance?
Nice to see a good Singelton lecture ;) Tip: at 4:00 ish you used Ctrl+C and then Ctrl+V, as i recall, you can just place the marker in that line of code and just press Ctrl+D to make a duplicate of that line.
Thanks for the detailed lecture. It is really helpful for me to understand why singleton design is followed in making the server based testing frameworks
I see managing database connection information or File IO parameters would be a good use case for this. Thanks for the video, looking forward to the next.