3 ms·
Refactoring something along the lines of static void Main(string[] args) { var filename = args[0]; var needle = args[1]; var linesT
by Joker_vD 4y ago
Refactoring something along the lines of
static void Main(string[] args) {
var filename = args[0];
var needle = args[1];
var linesToProcess = filename != '' ? File.ReadAllLines(filename) : HardcodedLines;
ProcessLines(linesToProcess, needle);
}
static void ProcesLines(string[] linesToProcess, string needle) {
// lines-processing code...
}
into something like
static void Main(string[] args) {
var filename = args[0];
var needle = args[1];
var linesProvider = filename != '' ? FileLinesProvider(filename) : MemoryLinesProvider(HardcodedLines);
ProcessLines(lineProvider, needle);
}
static void ProcesLines(ILinesProvider linesProvider, string needle) {
var linesToProcess = linesProvider.GetLines();
// lines-processing code...
}
would still need some justification, IMO: what's the benefit of giving ILinesProvider to the ProcessLines instead of just string[]?
- deleted 4y ago[deleted]
- quietbritishjim 4y agoI'm not clear on what you GetLines() method is returning (thanks to the var keyword - very useful but sometimes problematic, this is one of those times). If your GetLines() is returning a string[] then I agree there was no benefit. But that's not what I meant. As I said, I'm imagining the base class (ILinesProvider) to have an iterator-like interface. So, rather than string[] GetLines() method, it would have a string getNextLine() method that you call in a loop. That way, with the file, you don't load the whole thing in memory (as I also said). If your GetLines() method is returning an IEnumerable<string> (since this seems to be C#) then this is the problem I mentioned at the end of my comment - the base class I'm imagining is similar to an existing base class in the language, and it's confusing to write your own similar-but-slightly-different version in an example. But I think it's best to do it anyway and explain it away in a footnote. (But my ILinesProvider wouldn't return an IEnumerable, like in your snippet - instead, ILinesProvider actually is the iterator (but with a slightly different interface).)