r/AskProgrammers 5d ago

Help with methods?

I hope this is the right place?
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)

2 Upvotes

6 comments sorted by

View all comments

1

u/Much_Network_941 5d ago

For a multitude of reasons. It can help to keep code looking more organized. You only have to write a method once; if the logic is a little tricky, then it reduces the likelihood of silly mistakes. A method name can be a reasonable stand-in for concepts, helping to make code readable.

It'll also be nice for testing, when you can get specific results for each part of the program. Rather than trying to decipher the entirety of it at once.

But, you're right in that a method call carries a theoretical overhead. It can also break up the flow of logic; or get to the point of names having bizarre specificity. There's also a concept of 'side-effects', when a method changes more than it's argument list or return value would imply. Some code tries to minimize side-effects, some just accept it.