|
![](/i/fill.gif) |
Am 13.01.2014 09:54, schrieb scott:
>> But now suppose we refactor it to look like this:
>>
>> public SortedList<int> FindPrimesBelow(int max)
>> {
>> SortedList<int> candidates = InitialiseCandidates(max);
>> SortedList<int> primes = new SortedList<int>();
>>
>> while (candidates.Size() > 0)
>> {
>> int prime = GetNextPrime(candidates);
>> primes.Add(prime);
>> RemovePrimeAndItsMultiples(prime, candidates, max);
>> }
>>
>> return primes;
>> }
>>
>> private SortedList<int> InitialiseCandidates(int max)
>> {
>> SortedList<int> candidates = new SortedList<int>();
>>
>> for (int n=2; n<max; n++)
>> {
>> candidates.Add(n);
>> }
>>
>> return candidates;
>> }
>>
>> private int GetNextPrime(SortedList<int> candidates)
>> {
>> return candidates[0];
>> }
>>
>> private int RemovePrimeAndItsMultiples(int prime, SortedList<int>
>> candidates, int max)
>> {
>> for (int k=1; k*prime < max; k++)
>> {
>> candidates.Remove(k*prime);
>> }
>> }
>
> So you're writing 3x as much code just to avoid comments? Is the above
> really that much more readable to justify the extra work writing it?
>
> public SortedList<int> Primes(int max)
> {
> SortedList<int> candidates = new SortedList<int>();
> SortedList<int> primes = new SortedList<int>();
> for (int n=2; n<max; n++) candidates.Add(n); // initialise
> while (candidates.Size() > 0)
> {
> int p = candidates[0]; // get next prime
> primes.Add(p);
> for (int k=1; k*p < max; k++) candidates.Remove(k*p); // remove
> multiples
> }
> return primes;
> }
There is one major advantage in "commenting" your code by structuring it
and choosing good identifiers, rather than placing comments in there:
Comments are typically more prone to become outdated over time.
(Provided of course that the code is produced and maintained in an
environment where refactoring is encouraged. If the policy is "try to
avoid touching any of the existing code", it is easier to fix a comment
that has become obsolete, rather than a once-good identifier that no
longer matches what the function or variable does.)
Oh, and yes: I do think Andy's version is indeed easier to read. One
aspect is about visual perception: In your version, the reader has to
first figure out what is code and what is explanation, whereas in Andy's
version it's one and the same.
Another aspect is that Andy's version provides clear-cut interfaces
between the individual subsections of code. For instance, it makes it
immediately obvious that the step to remove a prime and its multiples
from the candidates doesn't access the "primes" list, but needs the
"max" parameter; in your version, inspection of the actual
implementation of that step is needed to figure that out.
Note that although all this figuring-out is quick to do, it still
requires concentration, and constitutes a potential source for mistakes.
Post a reply to this message
|
![](/i/fill.gif) |