Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > merging equal code (exercise in refactoring)

Reply
Thread Tools

merging equal code (exercise in refactoring)

 
 
SlowStrider SlowStrider is offline
Junior Member
Join Date: Apr 2012
Posts: 1
 
      04-10-2012
I admit this is a little late (I found your exercise through google), but I think I have quite an elegant solution that is equivalent:

Code:
import static java.util.Arrays.asList;

import java.util.List;

import com.google.common.base.Joiner;

class UtilRefactored {

	public static CharSequence format(List<CharSequence> source) {
		return "Listing:\n" + addBrackets(Joiner.on("\n ").join(source));
	}

	public static CharSequence format(CharSequence... source) {
		return format(asList(source));
	}

	private static String addBrackets(String text) {
		String result = "[ " + text;
		if (!result.endsWith(" ") && (!result.endsWith("]"))) {
			result += " ";
		}
		return result + "]";
	}
}
If you don't wish to depend on Google guava, you can also replace "Joiner.on("\n ").join(source)" by a method call to join("\n ", source) with the following join method
Code:
	private static String join(String separator, CharSequence... source) {
		StringBuilder text = new StringBuilder();
		for (final CharSequence component : source) {
			text.append(component);
			text.append(separator);
		}
		if (text.length() == 0) {
			return "";
		}
		// Remove excess last separator
		return text.substring(0, text.length() - separator.length());
	}
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
What is the equal command of this C code in Java ? tobleron Java 6 10-23-2008 09:52 AM
merging equal code (exercise in refactoring) Stefan Ram Java 0 01-18-2008 06:42 PM
Internet Sharing: Equal upload speeds but un-equal download speeds =?Utf-8?B?TkpU?= Wireless Networking 3 09-15-2007 06:22 AM
AVI Merging XhArD Software 24 11-04-2005 06:37 AM
Merging mail folders Tony Raven Firefox 2 12-04-2004 12:56 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57