osiegmar / FastCSV

CSV library for Java that is fast, RFC-compliant and dependency-free.
https://fastcsv.org/
MIT License
542 stars 93 forks source link

Could NamedCsvReader and CsvReader share a common interface? #55

Closed jamesdbaker closed 2 years ago

jamesdbaker commented 3 years ago

I was wondering whether it might be possible for NamedCsvReader and CsvReader to share a common interface, or perhaps for NamedCsvReader to extend from CsvReader? (And similarly for NamedCsvRow and CsvRow

Here's the use case I have in my head...

I want to use FastCSV to process a user-specified CSV, which may or may not have headers (but the user will tell me whether it does or not). At the moment, I have to write essentially the same code twice because NamedCsvReader and CsvReader are completely separate classes, as are NamedCsvRow and CsvRow. What would make my code much neater and easier to manage would be something along the following lines...

ICsvReader csvReader;
if(hasHeaders){
  csvReader = NamedCsvReader.builder().build(path, charset);
}else{
  csvReader = CsvReader.builder().build(path, charset);
}

csvReader.stream().forEach(row -> {
  //Do something here with each row, casting to NamedCsvRow where necessary and appropriate
});

Perhaps there's a reason why it hasn't been written this way (or perhaps I've missed an existing way of doing this), but perhaps something that could be considered in a future release?

osiegmar commented 3 years ago

During the development of version 2 I played around a few times with different ideas in order to have a shared common interface between index- and name based implementations. I also wanted to achieve that. With every attempt the result was worse compared to the final (current) API design from my point of view. I should also mention that I do not like casts and instanceof checks – especially if/as they hurt the performance of FastCSV!

I'm open to discuss an approach (drafted pull request) that is based on Generics – if you want to invest some time.