Exercise 39 CsvWriter. | Consider this code to write Comma-Separated Value ( CSV ) files. (Online at http://www.xp123.com/rwb ) CsvWriter.java public class CsvWriter { public CsvWriter() {} public void write(String[][] lines) { for (int i = 0; i < lines.length; i++) writeLine(lines[i]); } private void writeLine(String[] fields) { if (fields.length == 0) System.out.println(); else { writeField(fields[0]); for (int i = 1; i < fields.length; i++) { System.out.print(","); writeField(fields[i]); } System.out.println(); } } private void writeField(String field) { if (field.indexOf(',') != -1 field.indexOf('\"') != -1) writeQuoted(field); else System.out.print(field); } private void writeQuoted(String field) { System.out.print('\"'); for (int i = 0; i < field.length(); i++) { char c = field.charAt(i); if (c == '\"') System.out.print("\"\""); else System.out.print(c); } System.out.print('\"'); } } CsvWriterTest.java (A Manual Test) import junit.framework.TestCase; public class CsvWriterTest extends TestCase { public CsvWriterTest (String name) { super(name); } public void testWriter() { CsvWriter writer = new CsvWriter(); String[] [] lines = new String[] [] { new String[] {}, new String[] {"only one field"}, new String[] {"two", "fields"}, new String[] {"", "contents", "several words included"}, new String[] {",", "embedded , commas, included", "trailing comma,"}, new String[] {"\"", "embedded \" quotes", "multiple \"\"\" quotes\"\""}, new String[] {"mixed commas, and \"quotes\"", "simple field"} }; // Expected: // -- (empty line) // only one field // two,fields // ,contents,several words included // ",","embedded , commas, included","trailing comma," // """","embedded "" quotes","multiple """""" quotes""""" // "mixed commas, and ""quotes""",simple field writer.write(lines); } } -
How is this code an example of divergent change? (What decisions does it embody?) -
Modify this code to write to a stream passed in as an argument. -
Starting from the original code, modify the functions to return a string value corresponding to what the functions would have written. -
Which version seems better and why? Which is easier to test? See Appendix A for solutions. |