Extract method to reduce cognitive complexity of createHeaders()

This commit is contained in:
Sigee 2024-09-19 15:46:49 +02:00
parent e9d466ecc5
commit 8b23cbb6a8
1 changed files with 45 additions and 33 deletions

View File

@ -504,7 +504,21 @@ public final class CSVParser implements Iterable<CSVRecord>, Closeable {
headerRecord = formatHeader;
}
// build the name to index mappings
headerNames = getHeaderNames(headerRecord, hdrMap);
}
// Make header names Collection immutable
return new Headers(hdrMap, headerNames == null ? Collections.emptyList() : Collections.unmodifiableList(headerNames));
}
/**
* Build the name to index mappings
*
* @param headerRecord the record as an array of values, or {@code null} if the end of the stream has been reached
* @param headerMap the header column positions (0-based)
* @return header names in column order, or {@code null} if {@code headerRecord} is {@code null}.
*/
private List<String> getHeaderNames(final String[] headerRecord, final Map<String, Integer> headerMap) {
List<String> headerNames = null;
if (headerRecord != null) {
// Track an occurrence of a null, empty or blank header.
boolean observedMissing = false;
@ -516,7 +530,7 @@ public final class CSVParser implements Iterable<CSVRecord>, Closeable {
"A header name is missing in " + Arrays.toString(headerRecord));
}
final boolean containsHeader = blankHeader ? observedMissing : hdrMap.containsKey(header);
final boolean containsHeader = blankHeader ? observedMissing : headerMap.containsKey(header);
final DuplicateHeaderMode headerMode = format.getDuplicateHeaderMode();
final boolean duplicatesAllowed = headerMode == DuplicateHeaderMode.ALLOW_ALL;
final boolean emptyDuplicatesAllowed = headerMode == DuplicateHeaderMode.ALLOW_EMPTY;
@ -529,7 +543,7 @@ public final class CSVParser implements Iterable<CSVRecord>, Closeable {
}
observedMissing |= blankHeader;
if (header != null) {
hdrMap.put(header, Integer.valueOf(i)); // N.B. Explicit (un)boxing is intentional
headerMap.put(header, Integer.valueOf(i)); // N.B. Explicit (un)boxing is intentional
if (headerNames == null) {
headerNames = new ArrayList<>(headerRecord.length);
}
@ -537,9 +551,7 @@ public final class CSVParser implements Iterable<CSVRecord>, Closeable {
}
}
}
}
// Make header names Collection immutable
return new Headers(hdrMap, headerNames == null ? Collections.emptyList() : Collections.unmodifiableList(headerNames));
return headerNames;
}
/**