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

15

u/door_of_doom Apr 05 '22

These are all really good questions, and I don't feel like the answers you have gotten so far are adequete.

Interestingly, all of your questions fall into a really interesting realm of programming that concerns itself with "validity," or whether or not data is in a "valid" state.

What does it mean for something to be ain a "valid" state? Well imagine if you got a bill for your internet, and it was missing a few crucial things: It is missing important things, like the due date or the balance due. These are all critically important things for a bill to have, but your bill doesn't have them. This bill is not a valid bill. Bills have to state how much is due and when it is due.

Invalid states are really scary for programmers: Something that you generally don't want to have to do when programming a function is to manually validate all if your input, every single time. Some languages do require you to do this, but some languages give you tools to make it so that you don't have to.

This is where many languages try to give you the tools to design your code to make it "Easy to do the right thing, and hard to do the wrong thing." We generally want it to be easy for our data structures to be in a valid state, and hard/impossible for it to be in an invalid state.

So, consider a constructor: A constructor is a way of defining the bare minimum that an object requires in order to be considered valid. To use our previous example in a very silly way, if the only way to create a Bill object is to call the Bill Constructor, which has the paramaters float amountDue and DateTime dueDate, it would be nigh impossible to ever create a Bill that doesn't have an amountDue or a dueDate.

(There are other ways of achieving this, for example, the Builder pattern, but we won't go into that right now)

Now, whenever you are writing a function that includes a Bill as a paramater, you don't need to verify whether or not is currently has a dueDate, you can know that it is always guaranteed to have one, as it is impossible to create one without it.

Getters and Setters follow similar thinking: Many times, we don't want to give complete and unfettered access to our underlying data structures, because then it might be possible to invalidate the underlying data. For example, what if some bozo goes out and tries to set the dueDate of our Bill to NULL? NULL is not a valid due date, so instead of allowing them to have direct access to the DueDate field of our Bill Class, we ask them to use the setDueDate function. We can then add validation logic to our setDueDate function that throws errors if they every try to do something illegal like set the dueDate to NULL.

"But what if I don't need any validation logic?" You might ask. "Do I still need to use Getters and Setters?" The answer is basically "Technically no, but you might hate yourself later if you don't use them." While you might not think you need any validation now, you might change your mind later. And if you do change your mind, it is a lot easier to add validation logic to a function that already exists, rather than to create a brand new function and ask everybody to stop doing things the old way and start doing things the new way. What could have been a completely invisible improvment to your library is now a breaking change that negatively effects everybody downstream. By using Getters and Setters everywhere, you are future-proofing yourself against possible breaking changes down the road.

Dependency Injection is a pretty controversial topic, to be honest. First off, (and this applies to the constructors, getters, and setters too) in no way shape or form is it "needed." It is more a style (or framework) for programming that has certain pros and cons.

Put simply, think of Dependancy Injection as a different way of thinking about Constructors.

When we talked about Constructors before, we made it so that our Object class needs to define what it needs in order to be valid, and then whenever we have code that intends to create one of those objects, it needs to take it upon itself to provide everything that the new instance of the class is going to need. in our Bill Example, that means that whenever you want to create a new Bill, you need to be ready to provide a valid amountDue and dueDate

What Dependancy Injection does is provides you with a (metaphorical) machine that knows and understands what Classes need in order to be instantiated (their dependancies), so if you want an instance of something (like a Bill), you can simply ask your Dependency Injection framework to provide one for you; it will analyze the dependencies of what you asked for, see if it knows how to generate those dependencies, and "inject" them into the instance, providing you with a new, neat, and (most importantly) valid instance of that class.

What people generally don't like about DI is that it starts getting really magical. The idea is that once you have wired up all of the dependencies and taught the DI framework how everything works, you can just ask it for an instance of something and it will just magically make one for you. It obfuscates things that some people don't really like being obfuscated. That "magic" can be both a blessing and a curse.

Anyway, even though this was a long-winded comment, it really was just a brief overview of these topics. If you have any followup questions, I'd be happy to answer.

2

u/__Fred Apr 06 '22 edited Apr 06 '22

Thank you for this explanation!

I find getters and setters annoying and now I have a better understanding why they are useful.

I think there are mechanisms to define classes with less boilerplate and still have those advantages.

I don't know which programming language has them, but you could define getter/setter-properties with a "property"-keyword.

Then the definition would look like this:

class Bill {
   property float amountDue;
   property DateTime dueDate;
}

and it would still act as a regular class with getters and setters to the outside. "Lombok" does something like this, but it works around the Java compiler instead of together with it.

The other option would be to make it possible to overwrite reading and writing properties. I think that used to be possible in Scala but it's considered bad style(?), because you assume that a simple assignment without brackets is quick and has no side effects.

So someone could still write myBill.dueDate = null and would get an exception when the class defines the "setter" for dueDate like so:

class Bill {
    private DateTime dueDate;
    // ... amount ...

    public void dueDate_=(DateTime value) {
        if (value == null) {
            throw new IllegalArgumentException("date can't be null");
        } else {
            this.dueDate = value;
        }
    }
}

That means you can just keep the property public at the beginning and then decide later that you want to make it private, without disturbing the rest of the program.

2

u/door_of_doom Apr 06 '22

Yup, that is C#. A very nice evolution of that design that I appreciate very much.

2

u/vikrum2083 Apr 21 '22

Absolutely incredible post. As a new c++ learner this made so much more sense to me than I gathered from my lecture on these topics. Thank you so much!

If you wanted to expand upon this with Templates I would definitely read it.

5

u/AlSweigart Author: ATBS Apr 05 '22
  1. Constructors are the code that set up (i.e. initialize) the member variables (i.e. the state) for new objects.

Say you have a Rectangle object with width and height member variables. It has a constructor where you set up this info when you create the object, like: Rectangle foo = Rectangle(5, 10); Then later you can call the area() and perimeter() methods of this object and they return 50 and 20, respectively.

If you didn't have to specify this in the constructor (like, you could just call Rectangle foo = new Rectangle(); then this puts you in a situation where calling area() and perimeter() would have to raise an exception, because the width and height of the rectangle are unspecified. If you forgot to write code to catch this exception, then the unhandled exception crashes the entire program.

Forcing you to specify this info right from the start of the creation of the object can prevent bugs later on.

2) You want to have setters and getters because they can also run some code to do some checks before they get or set a member value.

For example, say you have $500 in a bank account and this is represented by a BankAccount object's balance member variable being set to 500. The rest of the program counts on this member variable always being positive, and there can be unknown bugs if it becomes negative for some reason.

When you withdraw some amount of money (specified by an amount variable), you can runs someAccount.balance -= amount;. But if amount is 600, this code setsbalanceto-100. At some point later, this cause a bug and it's hard to trace the cause back to thissomeAccount.balance -= amount;` code.

The solution is to add a set() method to the BankAccount class which raises an exception if you try to withdraw more than what's in the account. Even if this exception goes unhandled and crashes the program, it "fails fast" and you immediately know when a problem has occurred.

But you still have a problem because balance is still public and can be modified by code anywhere. What you need to do to prevent this is make balance private and only changeable by other classes through a setter method.

Here's the confusing part: in Java, from the start we often create a bunch of public boilerplate getters and setters for every member variable, and make the member variables private. So you have a bunch of getBalance() and setBalance() methods for balance and every other member variable. But they all look like public getBalance() { return this.balance; } so we ask "why do we need this getter?"

The reason is because if you force everyone to use getters and setters from the start, if you later need to add in some logic or checks to the getters/setters, you can just add that code. If you didn't have getters and setters (e.g. writing code that directly modifies balance) then you'd have to write those checks and go through your entire code base to change everything to use getters and setters. This is such a common headache, that IDEs usually just set up these generic setters and getters. But they're so generic and don't do anything but, well, get and set that people wonder why we even have them.

I like how Python avoids this by having properties: you can directly modify a value like someAccount.balance = 200 and if you need to add logic or checks later, you turn balance into a property that calls a setter method you create, and 200 is passed to it. You can turn balance into a property and you don't have to rewrite any of the someAccount.balance = 200 code.

3) Oof, this is too big of a topic for me to write here.

2

u/Longjumping_Round_46 Apr 05 '22

I don't know how much you know about OOP, so I'll try to keep it simple.

Say you have a class that represents a real world object.

public class Person
{ 

}

Classes can have data members and functions.

public class Person
{ 
    public string name;

    public int birthYear;

    public void IntroduceYourself()
    {
        Console.WriteLine("Hi, my name is {name}, and I was born in {birthYear}");
    }
}

With constructors, when you create (instantiate) a new class, you can set the date members right then and there.

public class Person
{ 
    public string name;

    public int birthYear;

    public void IntroduceYourself()
    {
        Console.WriteLine("Hi, my name is {name}, and I was born in {birthYear}");
    }

    public Person(string name, int birthYear)
    {
        this.name = name;
        this.birthYear = birthYear
    }
}

And when you want to create a class:

Person terry = new Person("Sir Terry Pratchett", 1948); 

terry.IntroduceYourself();

1

u/Olemus Apr 05 '22

2) They only feel this way when you aren’t doing anything complicated with them but getters and setters allow you to define logic when the variable js being retrieved or set. As an example a field called FullName might have a getter that concatenates the First Name and Last name fields when you retrieve it and splits a string on spaces when you set it and sets the [0] index to first name and the [1] index to last name (not the best example because doing that would be awful but hopefully gets the point across)

3) DI is just about decoupling classes from each other, basically class A doesn’t want to be doing any kind of instantiation of class B because that would tie them together and if I needed to change Class B to Class C I would have to change class A. Injecting class B into class A means that I can change Class B to Class C and still inject it without ever changing Class A

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.

1

u/Rote515 Apr 05 '22

Constructors define what needs to be populated for a class to be instantiated, so if I instantiate a person class object a constructor might tell me that the person needs a Gender, Age, Name, if I don’t supply those then it will fail to instantiate the class.

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.

1

u/lionhart280 Apr 06 '22

Constructors and why are they important.

If you want to be able to new up a Dog, but you want to be able to customize each instance of the Dog you have.

Specifically, Constructors demand those inputs, lets take a look at two possible ways to set properties of a class when you new it up in C#:

public class Dog {
    public string Name { get; set; }
}

vs public class Dog { public Dog(string name) { Name = name; } public string Name { get; set; } }

Now, the first one we can new up via:

 var myDog = new Dog() { Name = "Spot" };

Cool, no problem... but if we try and do this with the second dog:

var myDog = new Dog();

The compiler will throw errors... the second Dog requires you name it, you can't not name it... In other words for most languages, constructors let you define mandatory values the consumer must supply

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

Simply speaking, different combination of Setters and Getters with Public/Private on them allow you to define different combinations of access.

Specifically:

public Foo MyFoo { get; set; }

This Property you can access from outside the class and you can mutate it from outside the class

public Foo MyFoo { get; private set; }

This property can still be read from outside the class, but only internal private methods can write to the property. But it can mutate still!

public Foo MyFoo { get; }

This property can no longer be mutated, it can be access from outside to read from, but it can only be set in the constructor and then its "locked" in

private Foo MyFoo { get; set; }

You can't read or write this value from outside the class, but you can read/write it from internal methods on the class

private Foo MyFoo { get; }

You can only read from this property inside the class, and you can only set it in the constructor on instantiation, once it is set it is "locked" in.

Dependency injection

I wrote a whole blog post on this topic, enjoy!

https://blog.technically.fun/post/dependency-injection/dependency-injection-part-0/