This is not a homework question.
If I were to describe the exact differences between the following two methods and their use in the caller, how would I do so?
Method 1:
public void WriteSpace(int numSpaces) {
if (numSpaces <= 0) return;
for (var x = 0; x < numSpaces; x++) {
Response.Write(" ");
}
}
Method 2:
public String WriteSpaceReturn(int numSpaces) {
var space = "";
if (numSpaces <= 0) return space;
for (var x = 0; x < numSpaces; x++) {
space += " ";
}
return space;
}
Caller:
WriteSpace(4); //1
Response.Write(WriteSpaceReturn(4)); //2
The end result is the same from both. So I realize obviously that the first method does not return a value to the caller whereas the second does, but beyond that, how else would I describe these?
Is there a difference in atomicity between the first & second methods? Scope? Blocking? Is there a name for the fact that the first method writes output inside the method, whereas the second lets the caller do that? If these were writing significant amounts of data, would one be preferred to the other? I suspect since the first is making a call to Response.Write for each character, it would be slower?
Main difference in terms of performance: the second version of the code uses string concatenation in a loop, which is inefficient. I would hope that
Response.Writewould be more efficient than that.Main difference in terms of encapsulation: the second form is a pure method – it has no side-effects. This makes it easier to test in isolation, and in this particular case makes it easier to use in multiple situations.
That’s not to say the second version is better for being pure, necessarily – it depends on the context.
(In both cases you should remove the redundant check for
numSpacesbeing non-positive.)