Skip to Content
Course content

287: Practice Exercise: Parsing and Validating CSV Data

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably encountered a CSV file at some point in your career. They seem so simple—just values separated by commas, right? When I first started out, I thought parsing them was a one-liner. I'd just grab the line, call .split(","), and map the resulting array to my object. It works perfectly... until it doesn't.

The allure of the split() method

Let's say we're building a system to import monthly subscription data. Our CSV looks like this: CustomerName,Email,MonthlyFee. A naive implementation looks something like this:

String line = "John Doe,john@example.com,29.99";
String[] parts = line.split(",");
String name = parts[0];
double fee = Double.parseDouble(parts[2]);

In a controlled environment with "perfect" data, this is fast and readable. I'll admit, it's tempting. You don't have to pull in any external libraries, and you can get the feature shipped in ten minutes. But in the real world, data is almost never perfect.

When the comma betrays you

Here is where the split() approach falls apart. What happens when a customer's name is entered as "Doe, John"? To keep the CSV valid, the exporter will wrap that field in quotes: "Doe, John",john@example.com,29.99.

If you use split(",") on that line, your array suddenly has four elements instead of three. Your MonthlyFee is no longer at index 2; it's at index 3. Even worse, your Double.parseDouble() call will hit the email address or a fragment of the name and throw a NumberFormatException, crashing your entire import process. I've seen this exact bug bring down production imports because "the data changed slightly" on the vendor's end.

Building a robust validation pipeline

The professional way to handle this is to separate the parsing (turning a string into raw fields) from the validation (turning raw fields into typed Java objects). First, stop writing your own CSV logic. Use a library like OpenCSV or Apache Commons CSV. These libraries handle the edge cases—like quoted commas, escaped characters, and varying line endings—that would take you weeks to debug manually.

Once you have the raw strings, don't just shove them into your domain model. Create a validation layer. I prefer using a dedicated "Request" or "DTO" object that performs the sanity checks. Instead of calling Double.parseDouble() in the middle of your loop, wrap it in a try-catch block inside a validator that returns a meaningful error message, like "Row 42: MonthlyFee 'abc' is not a valid number". This allows you to log all the errors in a file and tell the user exactly what to fix, rather than just failing the whole job with a stack trace.

The trade-off here is a bit more boilerplate. You're adding a dependency and an extra class for validation. But the cost of that extra code is negligible compared to the cost of a corrupted database or a 2:00 AM wake-up call because a user put a comma in their company name.




📋 Practical Task

Exercise: Implementing a Resilient Subscription Importer

You are tasked with creating a CSV import utility for a subscription service. You must handle a file where some fields contain commas enclosed in double quotes.

Requirements:

  • Create a SubscriptionRecord class to hold customerName (String), email (String), and monthlyFee (double).
  • Write a parser that can correctly process the following line: "Smith, Jane",jane@email.com,15.50. (Hint: If you aren't using a library, you'll need to implement a loop that tracks whether the current character is inside a set of quotes).
  • Implement a validation method that checks if the email contains an '@' symbol and if the monthlyFee is a positive number.
  • If a line is malformed or fails validation, the program should print a specific error message identifying the row number and the reason for failure, but it must continue processing the rest of the file.

Test Data:

"Doe, John",john@example.com,29.99
"Invalid User",bad-email,10.00
"Jane Doe",jane@example.com,-5.00
"Brown, Charlie",charlie@example.com,invalid_price
"Correct User",correct@example.com,12.00
Rating
0 0

There are no comments for now.

to be the first to leave a comment.