-2

I want to generate CSV files. I have a generateCSV method which takes a filename as parameters and a bunch of entries

private static void generateCSV(String pFilename, String... pColumns) {

    try(FileWriter fileWriter = new FileWriter(pFilename,true)) {
        for(String column : pColumns) {
            fileWriter.append(column);
            fileWriter.append(";");
        }
        fileWriter.append("\n");
        fileWriter.flush();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

When calling the method with generateCSV("myfile.csv") without the entries i don't get any compilation error. I thought that this notation implies passing 1-N parameters from this object type. No ?

Hassam Abdelillah
  • 2,246
  • 3
  • 16
  • 37

1 Answers1

0

It is fine to only pass a single parameter to this method: pColumns will then be a zero-length array.

If you want to require that at least one column name is passed, add an additional parameter:

private static void generateCSV(
    String pFilename, String firstColumn, String... otherColumns) {

You then need to handle the first column specially:

    fileWriter.append(firstColumn);
    fileWriter.append(";");
    for(String column : otherColumns) {
        fileWriter.append(column);
        fileWriter.append(";");
    }

which is slightly less convenient than being able to treat them as a single array; but you just need to weigh that against the benefits of compile-time enforcement of having at least one column.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243