Avantgarde

On a quest to understand functional programming better

Java Generics by Example

| Comments

In this post, I’m going to talk about some actual examples on how we can use Java generics to make our own code type safe.

In my last article, I explained how generics provide type safety in our code. More specifically, I explained how using code that has been implemented by other people using generics can give us the benefits of type safety.

In this post, I’m going to talk about how we can utilize generics in our own code (not someone else’s code) to achieve type safety and to brag to your friends how esoteric your code is (just kidding, I do not advocate unreadable code, it’s a pain for people reading your code).

And as always, I love examples that explain the motivation. I think it makes much more sense.

Disclaimer: You might have seen these examples somewhere on the Internet. If you find another article that explains these concepts, I would like to give the author credit for that.

Example 1: DRY Principle when Initializing a Generic Class

I just love this pattern. Google’s Guava library provides the Lists factory object to do precisely this.

So you’re just happily declaring lists in Java SE 6 as follows.

1
2
3
List<String> someStrings = new ArrayList<String>();
List<Integer> userIds = new ArrayList<Integer>();
List<User> users = new ArrayList<User>();

Don’t you wish you could just not repeat yourself typing the same type parameter on the right hand side of the expression? I guess Java SE 7 helps alleviate this issue a little bit by incorporating the diamond operator.

1
2
3
List<String> someStrings = new ArrayList<>();
List<Integer> userIds = new ArrayList<>();
List<User> users = new ArrayList<>();

Hmm, slightly better. But we can do even better using Google Guava’s Lists factory object!

1
2
3
4
5
6
7
8
9
/* 
 * Not recommended since this clutters namespace, but this achieves the least
 * characters to initialize lists 
 */
import static com.google.common.collect.Lists.newArrayList;

List<String> someStrings = newArrayList();
List<Integer> userIds = newArrayList();
List<User> users = newArrayList();

“Wait, what? What is this magic? What just happened?”

Gentle Introduction to Generics

| Comments

There are a lot of articles explaining the theory behind Java generics, and whenever I read about these articles, I always feel confused, because I think it’s always confusing to learn about an abstract concept without concrete examples and actual use cases. Try reading Oracle’s Java tutorial on generics. I think I know generics fairly enough to be effective with generics and I still find the article confusing.

The concept of Java generics itself is a hard but interesting one to understand, and when articles start by telling people what it is and what the benefits are in some esoteric terms, it usually just doesn’t help me.

In this article, I’m going to take a shot at explaining generics by outlining why it was incorporated as a language feature in the first place Having said all of the above, you do need to have a vague sense of what generics are before jumping to my explanation below (i.e. you should have at least seen them and used them before).

Introduction

So why are generics implemented in the first place anyway?

Most of us will get acquainted very early with Java generics through the use of Java’s collection library. Among the Java standard collections library, one of the most often used data structures in computer science is a list, which is an sequence of values. The following code snippet shows how you would declare some list of items in Java SE 6.

1
2
3
4
5
6
List<String> names = new List<String>();
names.add("Jack");
names.add("Jill");

for (String name : names)
    System.out.println("My friend's name is " + name);

The class that you put in the angled brackets in the example above when declaring the variable names of class List defines what the list contains. In the example above, it’s String. Formally speaking, String is called the type parameter of List in this case.

Prevent Production Server Shutdowns Using Visudo

| Comments

Ever been granted sudo powers in a production server and accidentally ran sudo shutdown -h now because you think you’re shutting down your own computer? Well, I have (technically, it wasn’t a production server, but it’s running somewhere and I can’t turn it back on myself), and it’s pretty embarassing because I’d have to walk up to the Ops guy and ask him to reboot the server.

So, if you have been given sudo powers, make sure you use them wisely and defensively. Thanks to this example, I’ve finally found out how to reliably limit yourself from accidentally using those commands: by preventing yourself to run those commands before thinking twice.

  • First, open up the /etc/sudoers file using visudo (do NOT use any other text editor because visudo has a basic syntax check to make sure you do not destroy your sudoers file).
1
$ sudo visudo
  • Go to the part where it has a lot of Cmnd_Alias snippets, and add the following:
1
2
## Shutdown
Cmnd_Alias SHUTDOWN = /sbin/shutdown, /sbin/halt, /sbin/poweroff
  • Go to the “main part”, which is supposed to be the part where you give out permissions to run certain commands to users. It should have something like root ALL=(ALL) ALL. Add the following line (replace username with the username you use to log in to the server):
1
2
root    ALL=(ALL)   ALL
username    ALL=(ALL)   ALL, !SHUTDOWN
  • Now, when you do sudo shutdown -h now, it should stop you from doing so. If you really need to shutdown the server for any reasons, you have to go to visudo to allow yourself to shutdown the server, so this will force you to think twice before shutting it down. Neat, huh?

Setting SSH Public Keys

| Comments

So I keep forgetting how to do this, and thought it’d be good to have a self-note on this.

  • If you haven’t done so, create RSA key pairs using the following command. (hint: just keep pressing Enter and follow the instructions.)
1
$ ssh-keygen -t rsa -c example@somewhere.com
  • You should now have ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub, which are your private and public keys, respectively.

  • Ensure that the remote computer that you want to passwordlessly SSH into has an .ssh folder in the home directory.

  • Copy your public key (not your private key) to the remote machine, using the following command (replace username with your username and hostname with the host name or IP of the remote computer).

1
$ scp ~/.ssh/id_rsa.pub username@hostname:~/.ssh/authorized_keys
  • Some versions of SSH do not like it if the .ssh directory are not given the correct permissions. So SSH into your remote computer, and perform the following commands. If you’re wondering what these commands do, they grant read, write, execute permissions in the .ssh directory, and read, write permissions to .ssh/authorized_keys file.
1
2
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys
  • You should be able to SSH into the remote computer without typing your password!

My First Post

| Comments

Hurrah, finally, the first post in my blog! Truth is, I’ve been wanting to get a blog up and running for myself. However, of course there are always issues (or excuses, if you will) that get in the way.

First, I needed a place to host my blog online. I don’t want to pay for it, though; it should be a poor man’s blog. After searching online and weighing the pros and cons, I finally decided to go with Heroku to host my blog! They actually offer free web hosting for small web applications, and that’s probably how I intend to keep my blog (small, and filled with self notes).

I have prior experience with Git, so it was a smooth transition to using the Heroku platform. That being said, it was kind of sad that Mac OS X did not have a Portfile for the heroku-toolbelt, so I needed to install that from a DMG file, which I’d like to avoid as much as possible. Also, Heroku has their own rules for pushing to a repository. You can’t just push any file into a Heroku repository if it doesn’t match some application structure that they expect (which they call the Cedar stack, I think?), and they will just reject the push. So, that took me a while to figure out and configure.

Second, I didn’t want to use Wordpress, because it’s PHP (it’s not that I don’t like it, I just don’t know how to use it and don’t plan on learning it any time soon), and I really didn’t want a WYSIWYG editor to write my blog posts, since I’m probably going to write code snippets at some point later. It would be perfect if I could write my posts using vim and manage my blog through the terminal. This actually took me a while, before I finally found a solution that really fit my needs.

Enter Octopress! Well, it pretty much does what I want. It’s written in Ruby (which I just started to learn and use, and am enjoying it very much). I can manage it and host it for free using Heroku, and I can create and edit blog posts from the comfort of my terminal, which is just perfect!

So anyways, as I said, my first post has finally arrived! Just need to learn that Markdown syntax now…