picture home | pixelblog | qt_tools

omino code blog

We need code. Lots of code.
David Van Brink // Thu 2011.08.4 21:32 // {java}

Stupid Java Tricks

Syntactic Sugar

You know what I hate? I hate that I always am writing code, usually for tests, that looks like:


	List<String> stuff = new ArrayList<String>();
	stuff.add("fish");
	stuff.add("cow");
	stuff.add("dog");

So now I just type:


	List<String> stuff = Om.list("fish","cow","dog");

Nothing exotic, but here’s the handy method that allows it, and several others of a related ilk. I particularly like the Om.map() method. Enjoy. I’ll share a few more soon.


package com.omino.roundabout;

/**
 * Generic and System utility methods, like printf.
 * @author poly
 */
public class Om 
{
	...

	/**
	 * Syntactic utility for inlining object lists without the tedium of creating a list and adding to it.
	 * @param <T> the implicit type of all the pieces
	 * @param pieces things to put into the list
	 * @return a mutable list. Add more to it or delete some if you like.
	 */
	public static <T> List<T> list(T...pieces)
	{
		List<T> result = new ArrayList<T>();
		result.addAll(Arrays.asList(pieces));
		return result;
	}

	
	/**
	 * Syntactic utility for inlining a map. The map signature is sussed from
	 * the first two items, but you can include as many pairs as you like.
	 * @param <K>
	 * @param <V>
	 * @param key1
	 * @param value1
	 * @param theRestOfTheKeyValuePairs
	 * @return a mutable map.
	 */
	@SuppressWarnings("unchecked")
	public static <K,V> Map<K,V> map(K key1,V value1,Object...theRestOfTheKeyValuePairs)
	{
		Map<K,V> result = new HashMap<K, V>();
		result.put(key1,value1);
		for(int i = 0; i < theRestOfTheKeyValuePairs.length - 1; i += 2)
		{
			K key = (K)theRestOfTheKeyValuePairs[i];
			V value = (V)theRestOfTheKeyValuePairs[i + 1];
			result.put(key,value);
		}
		
		return result;
	}

	/**
	 * Syntactic helper to make a set of objects.
	 * @param <T>
	 * @param items
	 * @return
	 */
	public static <T> Set<T> set(T...items) 
	{
		List<T> list = Om.list(items);
		Set<T> result = new HashSet<T>(list);
		return result;
	}

	...
}

oh, i dont know. what do you think?


David Van Brink // Tue 2008.09.30 17:01 // {broad generalities java}

Practical API Design by Jaroslav Tulach

Found and acquired this book today at Bookshop Santa Cruz. Very nice tome on good Java API style. Alas, slightly pricey ($75 retail). The fellow’s a bit ranty at times… but, ah, I can relate. The author was a founding architect of NetBeans , and is still a principal on that project.

Also, look, google lets you embed a book for up to 20% reading! (Embedded below, may take a moment to load.)

Search for “beatiful” or “symmetry” or “backwards compatibility”…

oh, i dont know. what do you think?



(c) 2003-2011 omino.com / contact poly@omino.com