r/learnjava • • Nov 21 '14

learning about methods, question

it's not covered in the text so i figured i'd ask. so basically methods = a way to make your text nice and clean and readable. so if u did something like checking if a number is like odd or even or something that involves if statements or else statements, you put it in a method then call on that so your "main method (am i using the correct terminology)" is readable and cool.

also, do all methods u make need to be after the main method? can it be before the main method like you have something called checkEvenOrOdd() before the main method, then in the main method u call on that. is that wrong ? thx bros

0 Upvotes

13 comments sorted by

1

u/RhysLlewellyn Nov 21 '14

I'm also new to programming and would like to offer my opinion but don't take it as fact and I'd welcome any corrections if I get any of this wrong...

The main method is always the first method to be called upon. It initialises the programme, from the class main.

If you were making a simple programme just to say if a number is odd or even, you could set up your variables and methods within the main class as there wouldn't be a need to create a new object in a new class, due to the simplicity of the programme.

It's not possible to make anything run before the main method.

Is that right people?

-1

u/imgonnabethebest Nov 21 '14

uhh i mean look at the reply i got from the G master java king he said it doesnt matter

0

u/[deleted] Nov 21 '14

[deleted]

1

u/imgonnabethebest Nov 21 '14

yeah i got it now thanks. doing an exercise http://www.reddit.com/r/learnprogramming/comments/2mydur/trying_to_print_stars_without_using_for_loops/

i also learned that you can call on methods and use them inside another method that you're trying to write. thats some inception next level shit, pretty cool.

0

u/[deleted] Nov 21 '14

[deleted]

0

u/imgonnabethebest Nov 21 '14

ya bro :) didn't you read the comments

1

u/get_username Nov 21 '14 edited Nov 21 '14

... method = a way to make your text nice and clean and readable

Yes.

But there is more power than just readability here.

There are two misunderstood powers of methods that aren't used often enough:

  • Abstraction - expressing your code as ideas

  • Encapsulation - insulating your code from changes made to other parts

I am going to take a simple function now. Using abstraction I will express it as ideas (to show you how much easier it is to understand). Then using encapsulation I will play with it until it resembles something kind of crazy.

Follow me down the rabbit hole now.

Disclaimer: If you become confused, that is fine. Stop reading whenever you'd like. I go overboard at the end :)

Let me give you an example: we have some method sqrt that calculates the square root of a given number.

Rabbit Hole Level: 0

public class Rooter {

    public double sqrt(int n) {
        int guess = 1;
        while (guess * guess  - n > 0.0001) {
            guess = (guess * guess + x) / (2 * guess);
        }
        return guess;
    }
}

This isn't so bad... maybe you know what its doing, maybe you don't.

If you don't it can be confusing:

  • Why are we using guess * guess - n > 0.0001 as you while loop check?

  • Why are we using (guess * guess + x ) / (2 * guess) in the while loop?

The problem is I've been very descriptive in the method. The process is very clear (to a computer), but the ideas of the method don't really come through. Why am I doing these things?

Lets "push" them into a couple methods:

public Rooter {

    // sqrt class here.. I hid it for psychological benefit

    public static boolean notGoodEnough(double n, double guess) {
        return guess * guess - n > 0.0001;
    }

    public static double updateGuess(double n, double guess) {
        return (guess * guess + n) / (2 * guess);
    }

}

Now we've created these sub (private) methods. They can be called at any time. They represent the ideas of checking if a number is good enough, and updating a guess.

Putting them into our previous method makes things more transparent.

We can see how the sqrt method is actually functioning. It has become a member of the realm of ideas now.

public Rooter {
  
    public static double sqrt(double n) {
        double guess = 1;
        while (notGoodEnough(n, guess)) {
            guess = updateGuess(n, guess);
        }
        return guess;
    }

    // other methods here
}

This is what I mean by abstraction. You can make your intention alot clearer.

By making your intention in your code clearer it is easier for you and others to analyze if you're performing the correct actions.

If an error occurs you can isolate it down to either sqrt, notGoodEnough, or updateGuess.

Isolating the problems like this helps everyone involved craft better code.

Because I isolated the methods, I don't even need to tell you what they are. You just know the ideas of these methods:

  • notGoodEnough - checks if a number is not good enough

  • updateGuess - updates our guess

So for the next section I will simply speak about single methods at any given time (because now you're more experienced in abstraction).


Encapsulation:

Now that its abstracted, lets play around with the ideas of the method. We will see how encapsulation has allowed us to play with the ideas without effecting the logic.

Previous I used abstraction which also encapsulated the notGoodEnough and updateGuess methods from change. When we change the code for sqrt now, we will have no effect on the other two methods!

Rabit Hole Level: 1

Now lets really play with it and see what we can do:

I want to change the sqrt method. Well lets just assume we have a method named sqrtUpdateAndCheck. Performing that method would perform a single iteration of the update and check. We would want to call that method.

    public static double sqrt(double n) {
        return sqrtUpdateAndCheck(n, 1.0);
    }    

Okay. Now last time I had to set a variable.. well this time I am just going to use a "helper" method and pass the guess through it. So I call the method I want. What method do I call? one I haven't created yet.. but I will now:

    public static double sqrtUpdateAndCheck(double n, double guess) {
        // code to find sqrt
    }

How do I find the sqrt? Well I can do my while loop before, but I named the method to imply it is a single run.. so lets do a single run:

   public static double sqrtUpdateAndCheck(double n, double guess) {
       guess = updateGuess(n, guess);
       
       if (notGoodEnough) {
           // update and check again.. return result
       } else {
          // return the result, we know its good enough
       }
   }

So we are using ideas again to express what we want. In the end we want to return a result.. we know that if we hit a return statement that terminates the method.. so that last else is redundant

     public static double sqrtUpdateAndCheck(double n, double guess) {
         guess = updateGuess(n, guess);

         if (notGoodEnough(n, guess)) {
             // update and check again.. return result
         }
         return guess;
     }

Now.. when its not good enough I need to return the update and check.

If only I had a method that could update and check the sqrt..

oh wait.. I do.. THE METHOD I AM WRITING.

In a bold move called recursion, we call ourselves:

     public static double sqrtUpdateAndCheck(double n, double guess) {
         guess = updateGuess(n, guess);

         if (notGoodEnough(n, guess)) {
             return sqrtUpdateAndCheck(n, guess);
         }
         return guess;
     }

Now since the methods notGoodEnough and updateGuess were encapsulated, the previous changes do not effect them. They run exactly like they did before.

Even though we've changed the code drastically.. it should still work as expected!


Really going off the deep end:

Well.. now I noticed we can play more with this method. Lets just do it and see what we get.. for fun.

Rabbit Hole Level: n + 1

Notice how we are calling updateGuess everytime we enter the method. That tells me we can push it into the call before.. like so:

    public static double sqrtUpdate(double n, double guess) {
        if (notGoodEnough(n, guess))
            return sqrtUpdate(n, updateGuess(n, guess));
        return guess;
    }

But now I notice something too. We only have a single if, with two conditions that execute in different ways. Perhaps we could in line this with ternary:

   public static double sqrtUpdate(double n, double guess) {
       return notGoodEnough(n, guess) ? sqrtUpdate(n, updateGuess(n, guess): guess;
   }

Oh my.. we've created some kind of Frankensteinian monster. Lets use abstraction and GO DEEPER!!!


Really REALLY going off the deep end:

Rabit Hole Level: n ^ n

Lets use abstraction again to push the original into the state of the class. Then I set all the members to non-static so that they can access this state:

public class Rooter {
    public static final double TOLERANCE = 0.0001;

    private double n;

    public void setState(int n) {
        this.n = n;
    }

     public void clearState() {
         this.n = 0.0;
     }

     public double sqrt(int n) {
         setState(n);
         double result = updateSqrt(1.0);
         clearState();
         return result;
      }

     public double updateSqrt(double guess) {
         return notGoodEnough(guess) ? updateSqrt(updateGuess(guess)) : guess;
     }

     private boolean notGoodEnough(double guess) {
         return guess * guess - n > TOLERANCE;
     }

     private double updateGuess(double guess) {
         return (guess * guess + n) / (2.0 * guess);
     }
}

The whole point here was just to show you how you can use abstraction and encapsulation to play with how methods work. To really play with the ideas of a method on a high level.

I really like how it ended up though. The updateSqrt method almost reads like a sentence (if you read : as "otherwise")

  • notGoodEnough(guess) ? updateSqrt(updateGuess(guess)) : guess;

  • Is the guess not good enough? update the sqrt with the updated guess, otherwise its your guess

1

u/imgonnabethebest Nov 21 '14

i cant read this right now cause i get confused when u say abstraction and encapsulation and type return (watever) and private instead of public but ill come back to it after i finish with week 3 or 4 i think thats when they do the private static thing instead of public, so dont think im ignoring it. thanks for the warm hearted response tho bro

1

u/get_username Nov 21 '14 edited Nov 21 '14

No problem. This was written for your benefit and everyone elses as well.

But I explain via example what abstraction and encapsulation are capable of.

Also just ignore the private/public thing.. it really isn't important :)

1

u/seronis Nov 21 '14

Is this meant to be in /r/learnprogramming instead of /r/learnjava ?

Java doesnt require forward declarations in the sense that C and C++ do. All methods in a class can see each other regardless of their position within the class.

2

u/imgonnabethebest Nov 21 '14

idk bro java is my first language so i dont know if other languages have methods too or how that works

2

u/seronis Nov 21 '14

No problem. Just the question you asked isnt relevant to java but it is relevant to C and C++ so i wasnt sure if you were even talking about java.

2

u/s0lv3 Nov 24 '14

His question is definitely relevant to Java he just is not sure how to ask it.

1

u/KillerAlt Nov 21 '14

I just wanted to add something to this conversation to hopefully clarify something for you. Methods are something a class does, like a door opening would be a method from a door class. A door in a game might also be able to break, that's another thing a door can do. I know you are at the very beginning stages so you don't know a whole lot about objects or classes yet, but this will be good for you to keep in mind later on down the road. Methods don't just make your code clean, they are a huge part of how your programs do everything they do.