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

Show parent comments

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.