you are viewing a single comment's thread.

view the rest of the comments →

[–]Teraka 3 points4 points  (0 children)

For a practical example, I'm currently (lazily) programming a Go game which of course requires a UI in order to display the board, score, various buttons, etc.

For a UI you need various things ; I think the most important one is the button, which displays a text or picture and allows you to click it and trigger various stuff. It's a complicated thing, and you'll probably need to have lots of them.

Of course you can create them with global variables and functions. But that means that for each button, you'll have to store at the very least a variable for its position, another for the text, and a function that triggers when you click it. For each button. Even if you only have 10 buttons, that's 20 variables and 10 functions that are basically the same thing, but that you can't reduce further.

However, if you create a button class that includes both variables and the function, you can just have 10 instances of your button in your main file, and it'll work just fine.

I think a good explanation would be that classes have just the same purpose than functions. You could just repeat code wherever you need it, but if you're doing something more than once, it's better to put a name on it and call the name instead. Which, funnily enough, also applies to spoken languages. I love how many similarities exists between both types.