Java Lambdas : Syntactic Sugar

You glance down at your list of invited guests for your party.
Suddenly, you see someone with the last name of “Dang”, the very same family that ruined your party the last time they showed up.

Furiously, you write a program to sort through the hundreds of invited guests to remove everyone with the last name “Dang”.

For the sake of simplicity, a smaller list will be used, but nonetheless, you end up with this hideous snippet:

public class Party {

    static List invitedGuests;

    public static void main(String[] args){

        invitedGuests = new ArrayList() {{
	    add("Henry Dang");
            add("Joe Dang");
	    add("Kevin Smith");
	    add("John Dang");
	    add("John Doe");
	    add("Michelle Sans");
        }};

	for(Iterator iterator = invitedGuests.iterator(); iterator.hasNext();){
            String guestName = iterator.next();

	    if(guestName.contains("Dang")){
                iterator.remove();
	    }
	}

	for(String guests : invitedGuests){
	    System.out.println(guests);
	}
    }
}

 

What a terribly cluttered mess!

But what if you could have done it in a simpler, more concise way?
With Java 8’s lambdas, you can cut down the length of the logic to 1/5th of its size!

public class Party {

    static List invitedGuests;

    public static void main(String[] args){

        invitedGuests = new ArrayList() {{
	    add("Henry Dang");
            add("Joe Dang");
	    add("Kevin Smith");
	    add("John Dang");
	    add("John Doe");
	    add("Michelle Sans");
        }};

     invitedGuests.removeIf(name -> name.contains("Dang"));
     invitedGuests.forEach(name -> System.out.println(name));
    }
}

Just like that, your code instantly becomes clean, concise, and expressive.
The removeIf method simply takes a Predicate, which is basically a boolean. It checks if the name contains the word “Dang” in it, and if it does, it instantly removes it from the list.

The line after it is just a fancy for each loop, except it’s only one line long. The forEach method takes in a Consumer object, which basically says, “Give me a parameter, and something to do with that parameter.” You pass in the parameter “name”, and print all the names in the list.

Now that you’re done, all the Dangs are off your list, and you’ve shortened your otherwise obnoxiously verbose code by 8 lines.

Advertisements

The Importance of Unit Testing

Click click click. Tap tap tap. John sat at his desk, frantically searching for the elusive bug that plagued his code. No matter what he did, the software always returned the wrong result.

Kevin, a friend, took a look over at the code and found this snippet inside a method:

    int x = inputBox.getNumber;
    boolean z = (x%2==0) ? true : false;

    if(z = true){
        return 0;
    }else{
        return 1;
    }

John had made a simple typo on line 4. Instead of checking for equality, he had set z to true, meaning the program always returned 0.

Of course, John had used this method dozens of times in other methods, which then were used in even more methods. With the bug nested several functions deep, John lost several nights of sleep until he discovered the mistake.

Scenarios like these are common, and could have been avoided by unit testing.


What is unit testing?

Unit testing is essentially breaking your application into tiny tiny parts, and testing each of those parts to make sure they work properly. All of these tests are separate, and ensure that your code functions as it should.

Higher-level functions depend on lower-level functions, so by testing those lower-level functions, you can ensure that any function x that depends on a function y will run smoothly. Unit testing will allow you to be confident that your function y works correctly, and that any method that depends on function y will also work correctly, as long as the logic is correct. In addition, if function x is tested, and function y is changed, you can be sure that your change doesn’t break function x as long as all the tests pass. Having key functions tested will allow you to confidently and safely revise code without fear of causing random bugs in other parts of the software.

But Henry! I don’t have time to do unit testing. It takes up too much time!”

While this is a common argument against unit testing, and may hold true for tiny projects, unit tests pay off in the long run by several magnitudes. Although you might initially make much faster progress by neglecting unit tests, your code will ultimately be buggier and less stable, which in turn, will drain huge chunks of your time and ruin your productivity. By doing unit tests, your progress will be almost linear throughout the project because you will spot bugs before they become dozens of layers deep in your code. In addition, you can safely refactor without breaking any functionality, which reduces code rot, increases productivity, and improves the quality of your code base.

Unit tests are an efficient and easy way to decrease the number of bugs in your code, which would otherwise cause long nights with caffeine. Writing unit tests can boost your confidence in your code, and if you can’t trust that your code works, then what can you trust?

Unity – Checking for keyboard input

In this tutorial, you will be able to check for keyboard input from the user.

It’s a fairly simple process, and can be done in just a few keystrokes.

if(Input.GetKeyDown(KeyCode.KEY_YOU_WANT_TO_CHECK_FOR)){
    //Something happens
}

Replace KEY_YOU_WANT_TO_CHECK_FOR with whatever key you want, which you can find in Unity 3D’s documentation for the KeyCode.

One small pitfall is the enter key. The “enter” key on the keyboard is the return key, which is KeyCode.Return, not KeyCode.KeypadEnter. KeyCode.KeypadEnter will only work for the number pad’s enter key.

Also, the GetKeyDown method can accept either an enum or a String. KeyCode‘s fields are actually enums and not Strings, but it is accepted since GetKeyDown can accept different types of parameters.

It is generally better to use KeyCode instead of a String, since you are unlikely to make a mistake with KeyCode. For example, if you wanted to check for when the user presses the space bar, you can do it in one of two ways :

//First way with an enum :
if(Input.GetKeyDown(KeyCode.Space)){
    //Something happens
}

//Second way with a String :
if(Input.GetKeyDown("space")){
    //Something happens
}

Both are acceptable and will work fine. However, with the second method, there is nothing that stops someone from accidentally misspelling the word “space”. If you add an extra ‘e’ by accident, the compiler won’t warn you about it until run-time. However, if you try to write KeyCode.Spacee, the compiler will immediately complain that KeyCode.spacee doesn’t exist.

I hope this tutorial helped. Good luck!