So I did what any other socially awkward nerd would do: I asked the teacher if I could get an exception. And I got that exception, and took the class the second semester. The class was well within my capabilities as I had to endure complaints from other students that I was a curve buster with my 105% score in the class (when adding in extra credit). It was the only time I have ever been accused of "busting the curve." But it wasn't all ice cream and lollipops. The teacher didn't always like the way I coded the solutions, particularly the fact I never used procedures. My programs were all one long stream of instructions. Just like a VIC-20 basic program, except there were no line numbers. My thinking was if you are only going to call a procedure at one point in the code then why type all those extra keystrokes? Mr. Shepard was not impressed.
public class FizzBuzz04 { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { System.out.println(theValue(i)); } } public static String theValue(int i) { if ((i % 3 == 0) && (i % 5 == 0)) { return "FizzBuzz"; } else if (i % 5 == 0) { return "Buzz"; } else if (i % 3 == 0) { return "Fizz"; } else { return Integer.toString(i); } } }
I hope Mr. Shepard is impressed now. This actually does, believe it or not, improve the readability and maintainability of the code. It pulls out the biggest third of the problem (doing ugly math) and keeps the other two thirds (counting to one hundred and printing out stuff) in a nice neat package.
In the main method the function it calls is a wondrous and magical black box. Data goes in, answers come out. This is a fundamental abstraction that actually allows a lot of magical code to work. Consider encryption. Do you know about congruence in number theory? What? Numbers have theories?! And what's that about the Chinese remainders? Don't know, and since I have a procedure I can call I don't care.
It's magic.
No comments:
Post a Comment