Suppose I have a method used by multiple classes in my application. This method takes a Stream
as a parameter and applies a terminal operation forEach
in order to write the data to a file, something like the following:
public File writeStreamToTempFile(Stream stream) {
stream.forEach(item -> {
//some code to write item to a file
}
}
There are multiple callers of this method, and in some of those methods I need to transform the data, let's say using map function, like the following:
public void exportAnimalsData() {
Stream<Animal> animalStream = //fetch data from a DB
animals.filter(a -> a.type.equals("dog"))
.map(a -> //Do something useful to transform the Dogs);
writeStreamToTempFile(animalStream);
}
Not all the callers of the writeStreamToTempFile
method need to perform additional operations on the stream.
So my question is:
Is it a bad practice to apply operations to a stream in different methods?
I read somewhere that Stream should never be the return type of a method (the caller does not know if that method already consumes the stream or not), does it also apply for parameters of a method?
Should I just apply all the operations needed in the same method or is it ok to append intermediate operations to the same stream in a different method?