r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

16

u/tube32 Apr 05 '22
  1. Constructors and why are they important.

  2. Same about setters and getters. What's the point of declaring a variable private only to allowed to access them via public methods?

  3. Dependency injection

1

u/npepin Apr 05 '22

3) Dependency injection is based on dependency inversion, which means that lower level details depend on higher level details.

You may have a database method that grabs some records that using a connection string. You can put that connection string in the method itself, or you can pass it in as a parameter. When you pass it in, you inverting the dependency because now that method depends on a higher level. Your database method may depend on something you setup in main instead of something in method or class.

You can do this with a lot of things, like classes. For instance you can have an interface as a parameter and then pass in an object that implements the interface. In that case, your method has a higher level dependency, and that dependency is not tied to any specific implementation, which means that it'll work with whatever interface implementation you pass in.

Passing in dependencies is great, but it can be a bit cumbersome if you are doing it a lot as there may be a lot of dependencies to change. Dependency injection handles a lot of the boiler plate and makes it easy by allowing you to register dependencies and it'll handle the injection for you by looking at what you registered.

A big plus to dependency inversion is testing, you can swap out details very easily. Like your test may swap the database to something local environment.