Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating the class that contains static void Main()

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?

like image 441
anonymous Avatar asked May 12 '11 17:05

anonymous


3 Answers

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.

like image 139
KeithS Avatar answered Sep 19 '22 21:09

KeithS


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.

like image 28
Jon Skeet Avatar answered Sep 17 '22 21:09

Jon Skeet


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(){} 
}
like image 24
anishMarokey Avatar answered Sep 17 '22 21:09

anishMarokey