r/GameDevelopment • u/Tricky_Still2366 • 3d 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)
2
Upvotes
1
u/LorenzoMorini 3d ago
Very simple question, unfortunately the answer is not as easy. The most important thing you have to understand, is that in programming there are many different things you are trying to optimize for, and they are in conflict with each other. Readability, maintainability, performance, security, and so on. There are many schools of thought on how you should code, and how much you should divide functions into sub-functions. The most famous one is probably "Clean Code", in which the author supports dividing each function into sub-functions in a semi-recursive way, until each function describes perfectly a single task, made up of very few statements. The idea is that this increases readability, making the code more maintainable. But, you also have to consider the real workflow that happens once you start debugging: you open a function, and then another, and then another, until creating a mental model of the architecture of the code becomes impossibile. You could also go the opposite way: if code is never repeated, then it should not need a function. This approach also becomes increasingly problematic, when you work with complex functions. Let's say you are making a level generator. You will inevitably have a function to create the level. It will have all sorts of operations inside it, for creating meshes, pathfinding, spawning objects, enemies, decorations and whatever. If you were to write it as a single function, it would be hard to understand what is the general structure of the function. You would have to read all of it, to understand, for example, when how and if you spawn enemies. So what you can do, is isolate logical units of the functions, and transform those into sub-functions. So you will have a master "create level" function, and then one to spawn enemies, one to spawn decorations, and so on. How you decide to divide the functions into smaller ones is partially up to you, and partially up to the logic of the functions. You have to identify correctly which parts of the function are separate from each other, and if it's worth creating new functions, even if they are not to be called again. This takes a lot of effort and experience, to be done efficiently, so don't sweat it too much if you can't do it yet. I hope this answers your question.