HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Simplify 'if' condition

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplifyconditionstackoverflow

Problem

How can I simplify this code?

if (directory.Exists)
  {
    smallFileNames = directory.GetFiles("*.csv").Select(i => i.FullName).ToList();
    if(smallFileNames.Count == 0)
      smallFileNames = DivideIntoFiles(fileName);  
  }
  else
    smallFileNames = DivideIntoFiles(fileName);


I confused by identical lines...

Solution

Jumping in after the horse has bolted with a very minor different approach (using Any rather than Count and null).

IEnumerable GetSmallFileNames(Directory directory, string fileName, string filter) 
{
   var smallFileNames = new List();

   if (directory.Exists)
   {
       smallFileNames = directory.GetFiles(filter).Select(i => i.FullName);           
   }

   return smallFileNames.Any() ? smallFileNames : DivideIntoFiles(fileName);
}


Then used such as

IEnumerable smallFileNames = GetSmallFileNames(directory, fileName, "*.csv");

Code Snippets

IEnumerable<string> GetSmallFileNames(Directory directory, string fileName, string filter) 
{
   var smallFileNames = new List<string>();

   if (directory.Exists)
   {
       smallFileNames = directory.GetFiles(filter).Select(i => i.FullName);           
   }

   return smallFileNames.Any() ? smallFileNames : DivideIntoFiles(fileName);
}
IEnumerable<string> smallFileNames = GetSmallFileNames(directory, fileName, "*.csv");

Context

StackExchange Code Review Q#18837, answer score: 3

Revisions (0)

No revisions yet.