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

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.