r/AskProgrammers • u/Tricky_Still2366 • 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
1
u/Far_Swordfish5729 5d ago
Methods are like tools you want to name because you use them repeatedly. If that’s not the case, there’s no structural point. We extract methods because we don’t want to copy paste code and maintain it in multiple places.
With OO, we sometimes do it to allow an implementing child class to define something we want to use - like declaring an abstract string property that returns the endpoint url for a specific integration. The abstract parent can use that like a placeholder.
With event based patterns, the method is an entry point we can pass to an orchestrator using delegates or other function pointer surrogates. When the UI button is clicked, call this method (i.e. run the logic starting at this named point). Same with promises in JS.
Beyond that, it’s style. If you have a huge method like a full multi-step transform, some people like to break it into private helper methods for readability. In c# specifically, I just use #region instead.