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/Maukeb Apr 05 '22

1 - a class defines a type of object you might want to create, and the objects themselves are specific instances. The point of having multiple objects is that they are all different, even though they are if the same type, and the constructor is used to define those differences at instanciation. For a simple concrete example, imagine you are writing an integer class. Your program will use a lot of integers, and they will all hold different values at different times. When you create a new integer object from your class, you probably want it to have a value - there us no such thing as an empty integer. So as you create it, you pass that value into the constructor function, so at the point of instanciation it already holds its correct initial value.

2 - One if the main points of classes and objects is the abstraction they provide. Objects have properties and methods, where the properties define the internal state of the object and the methods define how it's possible to interact with the object. Getters and setters define certain interactions, but the fact that they are probably simple interactions doesn't mean you should drop the abstraction. The point of private properties is that outside the object you don't necessarily know what properties it has, meaning you shouldn't try to edit them directly. The getters and setters define what you can edit and manage it internally. This means that you can create getters for properties that don't necessarily exist, where the getter constructs data at the point of it being requested. It also means that setters can manage changes to properties in the way the object expects them to - for example, if you set the time zone on a time object, you might expect the current time also to change, and setting it using a setter rather than accessing directly allows you to make these changes the way you want to.