Crucial tests in Main()

  • Thread starter Thread starter Gustaf Liljegren
  • Start date Start date
G

Gustaf Liljegren

This is a very general question of style. I'm often writing console
programs that takes one input file and returns an output file. They use
to look something like this:

class Program
{
public static int Main(string[] args)
{

// 1. See if we got the right number of arguments...
// 2. Parse arguments further...
// 3. Check if the input file exists...

}
}

Each of these steps must of course be passed successfully for the program
to do its real work. If any test fails, the program should exit with an
error message. I use to implement the tests this way:

class Program
{
public static int Main(string[] args)
{
// See if we got the right number of arguments
if (args.Length != 2)
{
Console.WriteLine("Usage: program <input> <output>");
return 1;
}
...
}
}

This is why I use "int" and not "void" as return type in Main(). This
works, but I wonder if it's the best practice? Maybe I'm putting too many
things in Main()? Any opinions?

Thanks,

Gustaf
 
Gustaf Liljegren said:
This is a very general question of style.

This has nothing to do with Main, if any function gets too big it should be broken down into functions.
 
This is why I use "int" and not "void" as return type in Main(). This
works, but I wonder if it's the best practice? Maybe I'm putting too many
things in Main()? Any opinions?

Refactor the argument checking out of Main:

static int CheckArgs(char[] args)
{
...
}
 
Back
Top