I have a method that generates the S3 key prefix according to the provided args. However, my gut feeling is that this method is not as elegant as it should be, maybe I just don't have an eye for it. Care to instruct me on how to make this little bit less sketchy?
private String generateFullQualifiedS3KeyPrefix(DataStream dataStream, Options options) {
String environmentName, applicationName, streamName = applicationName = environmentName = null;
if (dataStream != null) {
environmentName = dataStream.getEnvironmentName();
applicationName = dataStream.getApplicationName();
streamName = dataStream.getStreamName();
}
String year, month, date, groupById = date = month = year = null;
if (options != null) {
year = String.valueOf(options.getYear());
month = String.format("%02d", options.getMonth());
date = String.format("%02d", options.getDate());
groupById = options.getGroupById();
}
String[] arr = new String[]{environmentName, applicationName, streamName, groupById, year, month, date};
StringJoiner filePath = new StringJoiner("/");
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) {
break;
}
filePath.add(arr[i]);
}
return filePath.toString() + "/";
}
1 Answer 1
The local variables make this very verbose: each variable is declared, initialized, re-assigned, and referenced. (They each appear 3-4 times in the code.) You could instead accumulate values in a list.
Creating an array that may contain null
values,
then filtering out the null
values in a second step feels like a waste that's easy to avoid.
You could instead accumulate non-null values in a list.
Using StringJoiner
is efficient to join a string from multiple parts.
Then at the end the filePath.toString() + "/"
is an inefficient string concatenation that could have been easily avoided by appending an empty string to filePath
.
And instead of using StringJoiner
, you could use String.join
.
Consider this alternative:
private String generateFullQualifiedS3KeyPrefix(DataStream dataStream, Options options) {
List<String> values = new ArrayList<>();
if (dataStream != null) {
values.add(dataStream.getEnvironmentName());
values.add(dataStream.getApplicationName());
values.add(dataStream.getStreamName());
}
if (options != null) {
values.add(String.valueOf(options.getYear()));
values.add(String.format("%02d", options.getMonth()));
values.add(String.format("%02d", options.getDate()));
values.add(options.getGroupById());
}
values.add("");
return String.join("/", values);
}