Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

My take on Dependency Injection and Singleton

Discussion in 'General Discussion' started by Le_Tai, Mar 3, 2020.

  1. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    I've seen a lot of misinformation about DI all over the web. Many developers praise the practice without actually understanding its benefit. Similarly, many crap on Singleton because they heard other said so. I made a little write-up to, hopefully, clear up the confusion for new-ist developer.

    I know that many of you have a long term relationship with Singleton, and has bad experience with DI. I'd love to know if you agree or disagree with my opinion, or if you know of other methods to solve these problems.

    Cheers!
     
    Last edited: Mar 3, 2020
    tigerleapgorge likes this.
  2. N1warhead

    N1warhead

    Joined:
    Mar 12, 2014
    Posts:
    3,884
  3. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    Thank for pointing out, I must have F***ed up the copy paste.
     
    tigerleapgorge and N1warhead like this.
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    My problem with dependency injection is that most people never give me a good reason why I should care about it, and to be honest it doesn't help when they literally state in their examples (and this isn't just you doing this either) that it "is a contrived example I made up on the spot; you could have avoided some of these problems by with a better design".

    I've found the following link to be the easiest explanation I've read and a large part of that is because it focuses not on why I should care but simply on what the term is referring to and allowing me to draw my own conclusions on its benefits.

    https://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html
     
    Last edited: Mar 3, 2020
    RecursiveFrog, Ony, Martin_H and 4 others like this.
  5. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,800
    I read it. I have been using Unity daily for 10+ years. I have rarely ran into a Null Reference Exception that could not be resolved quickly. I still do not understand why I need dependency injection. Maybe I do it already as I have found that most patterns that get tossed around I seem to have discovered on my own by simply plugging away and using rules for performant and elegant readable down the road code. What am I missing? It seems to be for MS business app coders who bring their habits with them.
     
  6. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,800
    Uh oh.. You messed up a dependency injection pointing to your blog on dependency injections. ;)
     
  7. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
  8. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    @ippdev, unless I"m missing something obvious, the whole DI craze is just a fancy name for using callbacks, interfaces and polymorphism.

    https://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html

    Basically, you start with a class A that creates an instance of class B to do something. That is "bad", because you're hardwiring A to use B, and that's "not DI".

    So. You alter the method, and instead supply instance of B to A in a constructor. That is now DI. The (supposed?) benefit is that now B can be made abstract/interface, and you can provide multiple derived classes to A instead of being hardwired to use a single implementation.

    And that's it. It plays nice with unit testing, apparently. Because you can feed fake database accessors to classes this way.

    You've probably used this thousands of times in practice. In practice this pattern can automatically emerge, when you, say.... have a class that manipulates data regardless of underlying container, and methods to get/set this data are provided via lambdas or interfaces.

    So it feels like somebody intentionally is trying to make this more mysterious than it is.

    -----------

    And of course, if I happen to misunderstand it, anyone is free to correct me.
     
    tigerleapgorge likes this.
  9. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    Last edited: Mar 3, 2020
    tigerleapgorge likes this.
  10. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    I wrote this since I have the opposite problem as you. When I just read about stuff, I usually have the question: why would I do it this way.

    That is only because of the lack of type safety :).

    ---

    James post made it really clear *how* you do DI, but like I said in my post, he too focus on the testing aspect of it, which is not as relevant to gamedev, since pretty much no one does test in this field.

    The primary aspect of DI, IMO, is that it force you to think about your dependency. When you look at a class constructor, you know exactly what the class need. And you cannot create a class before you create the stuffs to pass into its constructor.
     
  11. frosted

    frosted

    Joined:
    Jan 17, 2014
    Posts:
    4,044
    In actual practice in professional parts - there tends to be more to it because they use containers with lots of fancy add ons. The dependencies are set up with attributes and stuff and often not directly passed via constructor. Sometimes the instance types are set up in a config file or something.

    There can be a lot of value in this (for example, you can modify behaviour without recompiling, etc) and a lot of that can be valuable at some jobs. Especially if you're doing testing and the like. Being able to make changes in configuration files without compilation can be a very big deal in some places.

    I tend not to think that it makes sense in most small unity teams, but I'm willing to entertain the idea - I'd like to actually see implementation details and use cases that include counter examples to compare.
     
  12. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    Very possibly. Im mostly self taught and also usually re-invented patterns before read about them.

    The key takeaway is in this part https://blog.leloctai.com/unity3d-dependency-injection/#dependency-injection-to-the-rescue, as well as my last post.
     
  13. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    I know. However, as said in the post, the complexity of these frameworks are unnecessary for many projects, especially game, and it scare many people away.
     
    phobos2077 likes this.
  14. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    I don't agree that he focused on the testing aspect of it. He merely made it one of his three examples.
     
    phobos2077 likes this.
  15. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    He only have 1 usage example. The other are code example, which only state how you do thing, not why compare to something else.
     
    tigerleapgorge likes this.
  16. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    But this still really boils down to constructor arguments and polymorphism. I mean, if the "dependency" you receive changes based on config parameter, then you're dealing with base class, or factory, or facade or whatnot.

    I am also not a fan of the OPs write up, as the way I see it, it makes things even more confusing.
     
    tigerleapgorge likes this.
  17. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    If you're at the point where you're looking at concepts like "dependency injection" I'd argue you're at the point where you're capable of comparing them against other concepts yourself.
     
    hippocoder likes this.
  18. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    So my main points are:
    • DI is not complex to use (no framework, just normal code)
    • DI is all about making it clear what a class depend on, and forcing you to create those dependencies before the class itself
    Do you think these points was not clear in the post, or was you confused by the weird example?
     
    phobos2077 likes this.
  19. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    I disagree. DI is an extremely simple concept, artificially complicated by many framework and the scary name. I made the post because Singleton is being the default method of communication between classes, popularize by too many beginner tutorial.
     
    phobos2077 likes this.
  20. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,189
    If it's an extremely simple concept then it shouldn't need a ton of effort to explain the benefits.
     
  21. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    Simple action can have subtle implication.
     
  22. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,800
    Still having trouble thinking of a real game building example on the Unity side of components, monobehaviours and GameObjects that this would be something I would use. I know what types I am passing around so not inclined to polymorphism. For some data structures not at the core but only feeding the engine...perhaps. I use managers to control states of groups of components. I use behavioral components for objects that do any sort of transform over time and data components to store Lists and items, numbers etc that the behaviour transforms over time. Generally only the behavioral components have any Update loops. This pattern works with Unity's rule breaking rules headspace but I have seen enterprise coders new to Unity's workings choke hard and be unable to read what the code does that came right of of the manual. And they get to interfacing and polymorphisizing and I am looking at them like "dude.. I can do this in 10 line of code or less..why do I need three classes and methods?? and how the eff do I debug this when yer arse is down the road?"
     
    JoNax97 likes this.
  23. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    Yes. I think those points are not clear in the post, and the text made me triple check that I understand what DI is about. It also looked like half of the article was missing.

    Basically, my thought were
    "debunking etc etc etc. I don't need it. (skip)"
    "nullreference exception? why is that a problem? how is this even related?"
    "Dependency Injection to the rescue --> rescue from what?"
    "Object passed through parameters, and....?"
    "Common Concern --> Wait a minute, where the actual DI?"
    "your mom and end of the article --> And that's it?"

    If a concept is simple, I think it needs a paragraph of text at most, not debunking before it gets to the meat of the problem.

    The best explanation I saw is this one:
    https://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html
    This makes it clear that DI is a non-concept that has been used by pretty much any programmer aware of polymorphism, callbacks and interfaces.

    No offense intended.
    -------
    You have an algorithm that works on a countainer, and is supposed to access ANY container, even the one that does not conformt ICollection interface.
    You solve that by providing a callback to get data and data size.
    This is pretty much DI.
    I saw this emerge couple of times.
     
  24. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    Thanks. That exactly what I'm looking for. Writing is not my strong suit and I'm looking to improve
     
    phobos2077 and neginfinity like this.
  25. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    Well, I'm glad to hear that there were no hurt feelings involved.

    Have fun.
     
  26. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,886
    Im with others here, I have never found an actual need for DI.

    I can understand the need for this stuff in say a mission critical business app which when something goes wrong that one time in 10 years, it can literally kill people.

    But in games, I think the overhead for designing in a DI way negates the usefulness of it. Its fighting against the engine.

    I think if your going to go this in depth into worrying about dependencies, your better off putting the time investment into avoiding monobehaviours entirely and using ECS + DOTS, which tends to enforce your code to think carefully about dependencies anyway BUT actually provides benefits that are tangible to us, like performance and code reuseability.
     
    RecursiveFrog, pcg and xVergilx like this.
  27. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    I think this stuff emerges by itself and then programmer fails to notice that this is DI. Given that unity is driven by MonoBehavior, however, this happens less often in unity compared to other software.
     
  28. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,294
    +1 million

    Most of the DI requests come from people that are working with C#, and have 0 knowledge about the engine itself.
    Basically its two paradigms that doing the same thing - DI vs Service Location (which Unity has by design).

    Also, reflection. Screw reflection overhead.

    Also, if you're writing singleton - you've failed. Singleton is anti-pattern.
    If something needs instance to work - its already a fail from program architecture perspective.

    Use them wisely, not everywhere and for everything.

    Also, decoupling can be achieved w/o DI. Not everyone knows how to do it properly though.
     
    Last edited: Mar 3, 2020
  29. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    A classic Unity-specific use for a singleton is ObjectPool.
     
  30. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,294
    Well, bollocks, you've got me.

    Okay, so its better not to use them when its possible.
     
  31. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,984
    A quick suggestion, always explain a concept before introducing misconceptions about it. Everything before the section titled "So what is Dependency Injection, and why do I want to use it?" needs to come after.

    I certainly see the issue related to dependency injection. But dependency injection seems to me to be a bit of a dependency issue in itself. It's usually better, in my opinion, to design classes so that they behave 'rationally' with or without their dependencies. If the dependencies are there, so much the better, but if they're not, just rest. And if dependencies are really required for some reason, add a direct, concrete link that pushes the information through in Awake().

    I've never really had a null reference exception that I couldn't solve by wrapping it with if (X != null){}.
     
  32. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,886
    Agreed, any classes I write always will notify me (or the person testing) when a dependency was unable to resolve, and instead of just breaking, itll log that stuff out.

    As you said, with a combination of null checks and clever design, there shouldnt be a need for this in a unity context.
     
  33. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,984
    If a lack of dependency would be an unusual thing, I usually write a debug warning for it. Otherwise it's pretty easy to inspect the private variable values in the Debug mode of the inspector if something is not operating as expected.
     
  34. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,353
    Gonna play devil's advocate here.

    Dependency injection is good if you want to make your software more testable.

    I don't know how useful it is for games, but business software benefits from it.

    For example, you have a large software which processes payments, sending API to PayPal and receiving a response.

    How are you gonna test that? Surely you wouldn't want to literally spend money testing ap solution :p

    Well, one of the ways this could be tested is through dependency injection.

    You could supply different dependency to a class which shares same interface with actual payment solution but instead of sending API requests it just gives a dummy response.

    You can't achieve that with singletons, unless you do some serious hacking.
     
  35. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,337
    Unless I'm missing something...

    "What is Dependency Injection?"

    A technique where an object used by a class, rather than being created inside the class, is instead provided from the caller as a parameter. I.e. instead of:
    Code (csharp):
    1.  
    2. void test(){
    3.     var dataPool = new DataPool();
    4.     ...
    5. }
    6.  
    It turns into:
    Code (csharp):
    1.  
    2. void test(DataPool dataPool){
    3.     ....
    4. }
    5.  
    The object is "dependency" and passing it is "injection".

    "Why do I want to use it".
    You want to use it in situation where you need flexibility and have more than one class that implements some sort of functionality, but differ in detail, and that detail may change at runtime. Using dependency injection results in higher flexibility.

    A practical example would be some sort of "DataWriter" class that writes something to external source. It could be implemented like this:
    Code (csharp):
    1.  
    2. public class DataWriter{
    3.      public DataWriter(string filename_){
    4.          filename = filename_;
    5.          ...
    6.      }
    7.  
    8.     void writeStuff(){
    9.        using(var outStream = new BinaryWriter(File.Open(....)){
    10.        }
    11.     }
    12. }
    13.  
    which will restrict its usage to filesystem outputs ONLY.

    Or it could be implemented this way:
    Code (csharp):
    1.  
    2. public class DataWriter{
    3.      public DataWriter(BinaryWriter writer_){
    4.          ...
    5.      }
    6. }
    7.  
    Which will make it agnostic to underlying stream through use of polymorphism.

    This is called polymorphism and encapsulation. The concepts have been around forever and they're basis of Object Oriented Programming. Given that you originally had only real way to process transaction and now need real and fake way to process a transaction so you can run a test, you create an abstract base (BasePayApi) class for your PayPalApi, pass THAT as a parameter into your code that deals with transactions, derive FakePalApi from the the abstract base you introduced (BasePayApi), and in the test case pass FakePalApi instead of PayPalApi. If PayPalApi is frozen and cannot be altered, then you create BasePayApi anyway, and from it derive PaypalApiAdapter, or PaypalApiFacade, which wraps around your PayPalApi, and pass THAT into your code.

    I think it would've been better if the concept renamed unnamed.
     
  36. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,984
    Thanks for the explanation! I already understand dependency injection (thanks to the short and sweet explanation Ryiah linked) those bold letters were the header for part of the OP's blog post, I was simply suggesting that they put it at the beginning of their post.
     
  37. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    It's spring so we need some fresh discussion about code and braces anyway. Here's my take on just singletons for simplicity.

    For the record I absolutely love singletons. I don't particularly care what people with different experience to me think but the reasons they should be embraced in Unity IMHO are:
    • Unity's own structure kind of demands them. Unity's framework makes development easier if you do not fight it. Using singletons is a pattern which works extremely well with components without causing more spaghetti which is very easy to do with Unity's existing framerwork we have to work in.
    • Singletons are how the majority of software actually works. If you've got a main.cpp you've got a singleton. And I'm pretty sure that's everything.
    • Singletons have a bad reputation only in enterprise, which is as far removed from game dev as you can get. In NASA you'll be using singletons aggressively, or actually not even that. You'd be using one big file of code with pretty much zero abstraction. In industries like commerce, you will have endless database style queries, no singletons etc... so advice bandied about really is out of context for the job at hand, by inexperienced developers (relatively, I mean I have 38 years coding now).
    I'm not saying I'm right about everything or the best programmer at all, but I'm saying I'm generally much more practical than most. Singletons are a practical answer in Unity-based game development.

    If you avoid singletons in a Unity context you need to replace a ton of work Unity's designed for, which has some pretty far reaching consequences like more scene-based wiring, or leaning heavier on abstracted connectivity (events/scriptable objects) and you do this for something like a ParticleManager or EnemyController you end up needing more support. More docs. More debugging.

    Instead you can just singleton it, and if you want and you're worried, you can force the singleton to only have one of itself. It's just the most straight line within C# and Unity without going all static and messy or ultra-abstracted.
     
  38. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,294
    Even global event is better than Singleton imo (in terms of coupling).

    I'm all in for event driven development. And there's less and less times / cases where I use singletons.

    Misused singletons are evil. Like seriously. Each time there's:
    Code (CSharp):
    1. Garbage.instance.DoSomething(...)
    2. Garbage.instance.DoSomething(...)
    3. Garbage.instance.DoSomething(...)
    4. Garbage.instance.DoSomething(...)
    5. Garbage.instance.DoSomething(...)
    6. Garbage.instance.DoSomething(...)
    7.  
    It can be reverse controlled by subscription to the event. Which illiminates even the need to access instance.
    Sometimes they're unavoidable, sometimes - using singleton is more chore than declaring an event.

    Key is what works for you - works best.

    Witcher 3 has singletons all over the place btw. And its still a gorgeous game (even if its a headache to mod).




    That said. DI can go DI itself.
     
  39. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,886
    Agreed, I dont think singletons are bad or something to be avoided. I think the problem is, generally advice for someone completely new, as in a newbie to both unity and C# would be to avoid singletons at first until they know what they are doing, so they dont get into the habbit of making everything and its dog a singleton to bypass proper ways of passing data about the application.

    The problem is that turns into "never use singletons" too often, when really just like any other tool in your programming toolbox, the real advice should be "try it, if it works and you cant think of a better / easier / cheaper / quicker alternative, then it works.".

    Personally I use singletons in every app and I have yet to hit a "omg if I had not used a singleton my app wouldnt be a steaming pile of fire and rubble right now!" type issues. Again a lot of bad use of singletons comes down to the way the program is designed, not the pattern itself.

    I do agree with @xVergilx that you could also use event driven stuff for the same uses, but I think its all about personal taste at this point. Use whatever you enjoy and are comfortable using as long as it does the job well :)
     
    Ryiah and hippocoder like this.
  40. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,353
    I think some follow-up information is due on my end.

    Using dependency injection alone is not enough to reap the benefits. The framework I use for my project, Autofac uses both Dependency Injection and IoC (Inversion of Control) patterns. It works pretty nicely with MVVM applications.

    The idea is that objects do not create other objects, instead, they're supplied during the construction by Autofac.

    You register various objects, specify their lifetimes and mention how they could be accessed (using interfaces):

    Code (CSharp):
    1. var builder = new ContainerBuilder();
    2. // Register individual components
    3. builder.RegisterInstance(new TaskRepository())
    4.        .As<ITaskRepository>();
    5. builder.RegisterType<TaskController>();
    6. builder.Register(c => new LogManager(DateTime.Now))
    7.        .As<ILogger>();
    8. // Scan an assembly for components
    9. builder.RegisterAssemblyTypes(myAssembly)
    10.        .Where(t => t.Name.EndsWith("Repository"))
    11.        .AsImplementedInterfaces();
    12. var container = builder.Build();
    Then your target object stores such interface and its ctor have required elements (dependency injection):

    Code (CSharp):
    1. public class TaskController
    2. {
    3.   private ITaskRepository _repository;
    4.   private ILogger _logger;
    5.   // Autofac will automatically find the registered
    6.   // values and pass them in for you.
    7.   public TaskController(
    8.     ITaskRepository repository,
    9.     ILogger logger)
    10.   {
    11.     this._repository = repository;
    12.     this._logger = logger;
    13.   }
    14. }
    In the test environment, you would create a separate container and supply a different kind of class implementing the same interface.
     
    phobos2077 likes this.
  41. Player7

    Player7

    Joined:
    Oct 21, 2015
    Posts:
    1,533
    Autofac? more like wtf :D
     
    RecursiveFrog and xVergilx like this.
  42. Voronoi

    Voronoi

    Joined:
    Jul 2, 2012
    Posts:
    571
    Wow! This really looks like enterprise code to me, which I never enjoy looking at or working with. It feels sooo beauractric, like an agency to request a list of approvers, that need a cover sheet, signed by a manager. When does the code actually do anything?

    I am kidding a bit, I can see how code that might get revisited 10 years later by a new team, might benefit from all of this. In reality, a game would just be redesigned in 10 years, and it's not like lives are on the line. The problem with I have with overly structured systems like this is it limits creativity in the actual thing your code is doing. Games need rapid prototyping and quick changes if a given mechanic/system doesn't work.

    To spend the time to craft something that layered, you either are making something you've made before, or you are unlikely to change anything once it's been created. It seems counter-intuitive for quick iteration and exploring ideas.
     
    phobos2077, JoNax97 and Martin_H like this.
  43. elmar1028

    elmar1028

    Joined:
    Nov 21, 2013
    Posts:
    2,353
    Yeah. As mentioned, you shouldn't really be considering patterns like these for a video game.
     
  44. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    I think it depends on the game but for most people they can't make games big enough or have enough programmers on the same team to do it. So for an MMO or even Hearthstone, this extra engineering is welcome. But for most people on these forums, it is confusing for them.

    I used to code with a far future in mind, but now I code for only what I need right now. It's not as if we can't refactor safely and quickly.

    If we were Unity with many users already using our code, then it would be a tricky situation and maybe need the extra engineering.
     
    phobos2077, andyz and JoNax97 like this.
  45. snacktime

    snacktime

    Joined:
    Apr 15, 2013
    Posts:
    3,356
    DI has a very high base indirection cost. Indirection inherently makes code more difficult to reason about. Which doesn't make DI bad it just means reason about the actual cost correctly. Like a single use/implementation, it's an obvious net loss. If it exists solely for testing it's wrong, you didn't use the right tool for the job.

    Interfaces are much the same just more difficult to abuse.

    The problem with the OP's article is he wasn't using the right tool for the job to start with. So naturally he had a difficult time trying to show the value.

    A context where the solution fit the problem, like say database adapters, needs almost no explaining.
     
    RecursiveFrog and andyz like this.
  46. andyz

    andyz

    Joined:
    Jan 5, 2010
    Posts:
    2,148
    Waiting for interfaces to be mentioned!
    I find it hard to bother with DI, Interfaces or even namespaces most of the time! Because it all slows me down and makes code harder to follow/debug.
    With DI testing is the main argument I see, but I find little need or time to test outside of the game environment that I would actually pass a Different class in and so even need DI - Singletons will do!

    And no you don't have to type Thing.Instance all the time just do var thingInst = Thing.Instance once if you want!
     
    Last edited: Mar 3, 2020
  47. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Oh, this. Because really, I had no idea I was using DI for basically forever, until I looked it up. When I looked it up, I thought "I don't get it. Isn't this something that's just a regular part of programming when needs be?" I mean I didn't think it was actually a technique to name, but used where it was required.

    To create a doctrine or methodology based around someone naming something that has many interpretations, that's the real danger.

    Almost as if someone somewhere wanted to master these two powerful words and lead with it, instead of actually just going "huh, this is just regular programming whenever".

    Building entire ships from just one of the materials typically used in shipbuilding is just showing off because you can.
     
    MadeFromPolygons, Ryiah and Martin_H like this.
  48. Le_Tai

    Le_Tai

    Joined:
    Jun 20, 2014
    Posts:
    432
    DI is not just "passing thing you need into the constructor", which is indeed the nature way of programming. Rather, it is "passing everything you need into the constructor", as opposed to using Singleton or Service Locator like Unity's, both hide the dependencies.

    The point is that whenever you create an instance if a class, you know exactly what it need to function.
     
  49. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,800
    That is what I do when I reference one component from another one. The other component has everything needed to know all about whatever I am querying. I will call it Component Referencing IntraDependency Transactioning just to get all fancy and compsci-ish and as well to distinguish it from the arcane alchemical art of Dependency Injection..
     
    MadeFromPolygons and hippocoder like this.
  50. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,984
    If class A creates class B with dependency injection in the manner you describe, doesn't that mean that class A needs to 'know' everything that class B requires in order to function, thereby creating a very strong dependency that need not exist?

    What if class B requires a lot of different things that class A doesn't really know about?

    It seems to me that DI is something that is good for cases where a process must occur no matter what, where the absence of some data at any time would put the entire program into disarray, which seems to me to be the sort of design that should be avoided if at all possible.
     
    JoNax97 likes this.