HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Putting read data into a combined file based on certain attributes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filereadintocertainattributesputtingbasedcombineddata

Problem

I have a pretty big method where I read data from files and then put them into a combined file in a specific format based on an ID, first and end timestamp.

I already refactored some of my code to reduce the code complexity of my method, but it's still over 11 right now. So I was wondering if I should leave the method as is or try to find other ways to make it less complex.

This code will run on hardware which is designed by the company I work for so it's important to be as efficient with memory usage as possible.

Can you have a look at the code and help me out with reducing the code complexity by extracting pieces of code and putting them into separate methods?

```
protected File getSensorData(String sensorId, long first, long end) throws IOException, NumberFormatException {
/*
* This method gets data collected from files named after timestamps in seconds
*/
String[] idArray = new String[0];
String[] valArray = new String[0];
long timestamp = 0;
File formatFile = File.createTempFile("temp", "bufferedsensordata");
PrintWriter formatPWriter = getFilePrintWriter(formatFile);

// This sorts numerical instead of alphabetical
File[] fileArray = sortFiles(file.listFiles());

for(File f : fileArray) {
long longTimestamp = getFileTimestamp(f); // Converts filename into timestamp
if(longTimestamp >= first && longTimestamp = first && Long.parseLong(timestampString) <= end)) {
// id should be used and timestamp falls between the requested range
if(!Arrays.asList(idArray).contains(id)) {
idArray = growArray(idArray); // Increases the array size by 1 to make room for missing id
valArray = growArray(valArray);
} else {
foundId = true;
index = getIdIndex(idArray, id); // Returns location of the id in the array
}

if(foundId) {
valArray[index] = val; // Puts value in valArray at same spot as id in idArray
} else {
id

Solution

I have to scroll to read it all, so without looking at the code: Yes, split it.

And now with looking at the code:
I would try to extract the content of your for loop and give the method a nice name.

Afterward you can check how to split this method.

Maybe you want to have a look at one-thing-extract-till-you-drop (also check the comments)

Context

StackExchange Code Review Q#28116, answer score: 5

Revisions (0)

No revisions yet.