user1526912
user1526912

Reputation: 17220

How to prevent repeating code

I am a beginner programmer and feel like I am repeating code(DownloadFiles()) as in the below example:

var files = DownloadFiles();
var retryCount = 0;

while (files == null && retryCount < 3)
{
    retryCount++; 
    Console.WriteLine("Retrying {0} time", retryCount);
    files = DownloadFiles();       
}

My application is basically downloading files via a HttpWebrequest` and is supposed to retry the download 3 times if no files are retrieved.

I need your expert opinion here:

I am repeating code with DownloadFiles()

Could this snippet of code be written more efficiently?

This may seem trivial but I want to develop good programming practices.

Upvotes: 1

Views: 475

Answers (5)

MD-Tech
MD-Tech

Reputation: 1224

a for loop may look neater:

var files = DownloadFiles();

for (int retryCount = 0; files == null && retryCount < 3; retryCount++)
{
    Console.WriteLine("Retrying {0} time", retryCount);
    files = DownloadFiles();       
}

edit: additionally: I normally hate "magic numbers" - constants without context, such as the 3 in the comparison, as it makes code less maintainable. This is particularly true if you want to give the user a choice of how many times to retry. I would normally use something like:

const maxRetries = 3;

and

retryCount < maxRetries

in the loop but thats up for debate.

Upvotes: 0

Xiaoy312
Xiaoy312

Reputation: 14477

??? files; //type returned by the function
var retryCount = 0;

do 
{
    files = DownloadFiles();

    if (retryCount > 0)
        Console.WriteLine("Retrying {0} time", retryCount);       
} while (files == null && retryCount++ < 3)

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 133995

Another way to do it is:

List<File> files;  // replace with whatever type files is
var retryCount = 0;

while ((files = DownloadFiles()) == null && retryCount < 3)
{
    retryCount++; 
    Console.WriteLine("Retrying {0} time", retryCount);
}

Upvotes: 1

quantdev
quantdev

Reputation: 23793

You are not repeating your code, you already encapsulated the Download logic in a method, and you are looping over this method.

Bad things would have been to inline the DownloadFiles method or to unroll the while loop.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can use do ... while as Ben Aaronson already suggested:

TypeOfFiles files;
var retryCount = 0;

do
{
    files = DownloadFiles();       

    if (retryCount > 0)
    {
        Console.WriteLine("Retrying {0} time", retryCount);
    }
}
while (files == null && retryCount++ < 3)

I moved the retryCount++ to inside the while so your number doesn't get off (compared to do this inside the loop).

Upvotes: 1

Related Questions