Java Code Review: Refactoring a CSV Generator
StringsModel answerLast updated
Analyze a poorly designed Java method for generating CSV strings and detail performance, RFC 4180 compliance, memory usage, and security enhancements.
During a technical interview, you are shown the following Java method responsible for converting a two-dimensional list of values into a CSV formatted string:
public String buildCsv(List<List<String>> rows) {
String s = "";
for (List<String> row : rows) {
for (String cell : row) {
s += cell + ",";
}
s += "\n";
}
return s;
}
Identify the bugs, performance bottlenecks, and design issues in this implementation. Explain how you would refactor it for production usage, addressing standard CSV specification edge cases, memory limits, and potential security risks.
Hints
Hint 1
Consider the time and space complexity of String concatenation in Java inside nested loops.
Hint 2
Think about RFC 4180 rules for cells containing special characters like commas, newlines, or double quotes.
Hint 3
How does this method handle edge cases like null inputs, trailing commas, or extremely large datasets?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Key Issues Identified
A. Performance and Memory Complexity
- $O(N^2)$ Memory Allocations: Immutable string concatenation using the
+=operator inside nested loops creates a newStringobject on every iteration. For $N$ total characters across all cells, this results in $O(N^2)$ time complexity and massive allocation overhead, leading to garbage collection pressure. - Fix: Use a
StringBuilderinitialized with a reasonable capacity, or stream directly to an output target (e.g.,WriterorOutputStream).
B. CSV Format Violation (RFC 4180)
- Trailing Delimiters: The current logic appends a comma after every cell, including the final cell in a row (e.g.,
"val1,val2,"), resulting in an empty phantom column. - Unescaped Special Characters: If a cell contains a comma (
,), a double quote ("), or line breaks (\nor\r), the output CSV structure breaks. Standard CSV requires wrapping such cells in double quotes and escaping embedded quotes by doubling them (""). - Inconsistent Line Endings: Standard CSV (RFC 4180) prescribes
\r\n(CRLF) as line breaks rather than\n(LF).
C. Edge Cases & Null Safety
nullCell Values: If a cell inrowsisnull,cell + ","convertsnullinto the literal string"null,".nullInput Structures: Passing anullrowslist or containingnullrow elements will trigger aNullPointerException.- Empty Rows: An empty sub-list produces an empty line with a trailing newline, which may create unexpected empty records depending on consumer strictness.
D. Security Risks (CSV Injection / Formula Injection)
- If the exported CSV is rendered in spreadsheet applications like Microsoft Excel or Google Sheets, cell values starting with
=,+,-, or@can be interpreted as executable formulas. This can lead to Data Exfiltration or Remote Code Execution (RCE) on the user's machine.
2. Standard Production Refactoring (In-Memory)
If the dataset is small enough to fit comfortably in memory as a String, standard escaping and StringBuilder should be used:
public String buildCsv(List<List<String>> rows) {
if (rows == null) {
return "";
}
StringBuilder sb = new StringBuilder(1024);
for (List<String> row : rows) {
if (row == null) continue;
for (int i = 0; i < row.size(); i++) {
if (i > 0) {
sb.append(',');
}
sb.append(escapeCell(row.get(i)));
}
sb.append("\r\n");
}
return sb.toString();
}
private String escapeCell(String cell) {
if (cell == null) {
return "";
}
// Formula injection mitigation: prefix formula triggers with a single quote
String sanitized = cell;
if (sanitized.startsWith("=") || sanitized.startsWith("+") ||
sanitized.startsWith("-") || sanitized.startsWith("@")) {
sanitized = "'" + sanitized;
}
// RFC 4180 Escaping: quote cells containing commas, quotes, or line breaks
if (sanitized.contains(",") || sanitized.contains("\"") ||
sanitized.contains("\n") || sanitized.contains("\r")) {
sanitized = "\"" + sanitized.replace("\"", "\"\"") + "\"";
}
return sanitized;
}
3. Scalable Architecture (Streaming Large Data)
For large datasets, storing the entire output in memory as a single String can cause an OutOfMemoryError. Instead, the API should accept a streaming sink such as java.io.Writer:
public void writeCsv(List<List<String>> rows, Writer writer) throws IOException {
if (rows == null) return;
for (List<String> row : rows) {
if (row == null) continue;
for (int i = 0; i < row.size(); i++) {
if (i > 0) {
writer.write(',');
}
writer.write(escapeCell(row.get(i)));
}
writer.write("\r\n");
}
writer.flush();
}
4. Trade-offs & Production Recommendations
- Custom Implementation vs. Open-Source Libraries:
- Custom: Zero external dependencies, suitable for simple use cases without complex CSV dialect variations.
- Library (e.g., Apache Commons CSV, Jackson Dataformat CSV, OpenCSV): Highly recommended for enterprise projects. Third-party libraries automatically handle edge cases like custom delimiters, non-standard line endings, alternative quote characters, and streaming optimizations.
- Performance Complexity:
- Original Code: $O(N^2)$ time complexity due to repeated string copying; excessive memory churn.
- Refactored Code: $O(N)$ time complexity where $N$ is total character count; $O(1)$ auxiliary space overhead when streaming directly to a
Writer.