I am reviewing a co-worker's C# console app, and I see this snippet:
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.RealMain();
}
... non-static RealMain function
}
Presumably, he's doing this because he wants to have instance-level fields, etc.
I haven't seen this before, but this style bugs me. Is it a common and accepted practice?
There is a school of thought that says that the main() function of object oriented code should do as little as possible. Main() is an "ugly" throwback to procedural code design, where programs were written in one function, calling subroutines only as necessary. In OOP, all code should be encapsulated in objects that do their jobs when told.
So, by doing this, you reduce the LOC in the main() entry point to two lines, and the real logic of the program is structured and executed in a more O-O fashion.
It makes sense to me.
In particular, you may want to add just enough logic into Main
to parse the command line arguments - possibly using a generalized argument parser - and then pass those options into the constructor in a strongly-typed way suitable for the program in question.
Albin asked why this would be necessary. In a word: testability. In some cases it's entirely feasible to at least test some aspects of a top level program with unit tests or possibly integration tests. Using instance fields instead of static fields (etc) improves the testability here, as you don't need to worry about previous test runs messing up the state.
if you want to get non static functions
you have to do like this.
class Program
{
static void Main(string[] args)
{
Program p = new Program(); // dependency of the class will be there.So not a good practice
p.RealMain();// if you want initalize, you have to go like this or better you can do it in some other class.
}
void RealMain(){}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With