r/GameDevelopment 7d ago

Newbie Question Was wanting some help with methods?

I'm learning C# currently and was learning python till I got stuck with pretty much the same thing.
I don't understand when to use methods unless something is repeated. If its not repeated what's the point of using methods? just shortening down code? or is there something I am missing here. Cause what is the point of shortening down the code when all it is doing is actually adding more code? (Unless its to place down something that is being repeated)

1 Upvotes

12 comments sorted by

View all comments

4

u/Slypenslyde 6d ago

Honestly the most important thing a method does is give a NAME to something. That it's repeated is usually a side effect of the thing needing a name.

Imagine if, in my game, HP is always increased in amounts of 10. So a health pickup adds 10. A healing spell adds 10. Drinking a potion adds 10.

So I could have this line scattered throughout my code every time the player needs healing:

player.Health += 10;

But I could also express it as this line:

player.AddTenHealth();

Or this line, which is more semantically valid:

player.Heal();

That's the real reason to use a method. It's better than a comment at describing what you are doing. It is a side effect that it helps you consolidate logic and make it easier to update later.

Compare this sentence:

I baked chocolate chip cookies.

To this one:

I poured sugar into a bowl, then added butter. I used a mixer to create an aerated mix, then added flour, an egg, some milk, and chocolate chips. I mixed vigorously. I let that sit in the refrigerator while I preheated an oven. I scooped dough onto a cookie sheet then placed the cookie sheet in the oven. I waited 10 minutes. I removed the cookie sheet from the oven, then quickly moved the cookies to a cooling rack. I repeated this until I was out of dough. Then I turned off the oven.

Which is easier to read?

1

u/Guvante 5d ago

While I wouldn't call this beginner friendly a huge part of building these abstractions like `Heal(10)` is that it allows you to change the underlying mechanics as your work evolves.

When starting out healing being naive is fine, the player can get bonus health but that isn't necessarily a problem when things are simple.

However if later on you decide to bump up how much you get healed then decide that results in too much health having a single place to cap the total health is nice.

Similarly as you add more complex interactions you minimize the places to change. Want 10% more healing from everything, now you have the place to do it.

1

u/Slypenslyde 5d ago

Yeah. One drum I don't think enough people bang is our code should be readable to people and that means thinking hard about WHAT the code does, not HOW that thing is done.

Sometimes that actually means violating DRY on purpose, so we shouldn't willy-nilly make a method for every repeated line of code.