Please explain the point of Methods and Parameters to me? It seems so much easier to avoid them? Beginning Java...
Methods and parameters make it so that when you someone else reads your code and tries to make sense of it, they are less likely to want to blow their brains out.
Okay,k so I understand how they can be used to simplify your code and organize it. But what about how sometimes you have to pass a variable inside the parameter of a method, for example: public Method1 (int hi) { //do random stuff } what's the point of passing the variable inside the parameter when you can just have it inside the block of code?
The purpose is to make sure that the function only has access to the data it absolutely needs.
It also has to do with the idea of object orientated. Long ago a program was very static thing and it was hard to reuse code. People did so by making their own library of code snippets, pasting them in, and editing. The the idea of OOP came in where the objects were designed to be reusable and a larger, public set could be made. People were encouraged to both use the standard objects and still make their own ones, but following layouts that made this easier to do. A method with a passed variable allows a simple object to be reused time and time again. This cuts down on the amount of work you need to do over the years, allowing you to be a more productive programmer. It also allows the use of teams where you may know what needs to be done to the data for one step, but not everything about what will be done in other parts of the code.
I may be really annoying right now, but then why do you pass variables? Why can't you just have the variable inside the block of code. Is passing a variable integral to the success of the method so that it can be reused?
Yes. For example, lets say your method is one to return the square of a number. Yes, I know this is a simplified example, but that is what you use at the start. Now, do you want to write one block of code for every possible number, or do you want to write one that takes a number ad returns the square? So now expand that to something that does more work. Say evaluating a list of things and spitting out a result. You pass it the file name for the list that might be a million items, and which type of result you want. By doing this with variables it allows you to look for different things in different files. By making it a method you can design what is called a database handler. That is a modular form of programming, or OOP. But you don''t just start writing database handlers. You write smaller, simpler things at the start. Then you learn about inheritance and how to customize the children. As you go on, you are able to make effective programs more rapidly because of code reuse and flexibility due to variables.
That works I guess
Thanks
np. Have fun!
Join our real-time social learning platform and learn together with your friends!