Using The Main(string[] args) Better

I have recently started a college class on Java. It haven’t worked with it in a while and thought maybe its a good choice as the last elective I have left to do. One thing I noticed is that a lot of the assignments and examples don’t mind if you cram your code into the


Main(string[] args) { [...] }

which is fine for those just beginning programming. For a lot of people just making code work is already a god send. However, I cannot help but point out that this is a fairly bad practice for a few reasons:

  • Any class scope variables have to be static
  • All functions have to be static
  • You have to initialize all your variables inside of the main function. Not a good practice.

This is not a very good thing because this is a pitfall for memory management. A program NEEDS to have a static entry point, but this does not mean that you need to wrap your code around it. If everything is static (which is something students LOVE to abuse), then the only time your memory gets cleared is when your function variables go out of scope and/or when the program exits. This is a bad coding practice which makes it very difficult to write optimized applications.

So what do I do?

You don’t have to do much. Simply create a non-static class and call it “Main” or any name you would like to give it. Then simply create a new instance of the variable inside the main and call a start function. Very simple! Let me show you an example:


     public class Main 
     {
          //Now your class variables don't have to be static
          int myInt;

          public Main()
          {
              myInt = 0;
              //Your variables initialization here
          }

          public void start()
          {
          //Put your code here!
          }
     }

and so your static main now looks like this!


public static void main(String[] args) {
      Main main = new Main();
      main.start();
 }

Should I Teach This?

I started Java a about 6 years ago and for a very long time I did not understand how to structure code in an easy way. This concept might be a little bit confusing for students, but it will clean up their code. Students starting Java without coding experience still don’t understand what static variables are (and why you should avoid them), so this will help them avoid the pitfalls of “Well everything is static ill just make mine static too!”. It removes an extra element for something that is already somewhat confusing for many!

Closing Notes

        This helps exit your application better

Its not quite faster or “better” in the sense of exiting, but it nests your code in such a way where you know when your application is exiting. The only time your code will go beyond the “main.start()” is when it is exiting or switching states. This is extremely useful if you want to do some processing right before exiting.

Early Programmers: Initializing an empty object to be replaced

This is my first programming post and I thought I would start with something that I see all the time with programmers who are just seasoning. This is a common mistake I used to make as well and I believe it stems from the miss understanding of how variables and references relate to one another. Thankfully .NET based languages (including those which compile down to CLI) manage object deletion automatically. Otherwise you would have a pretty serious memory leak.

Lets look at a common example. We are using C# here but Java should look almost one to one. For instance if we have a simple class:

class SomeObject
{
     string someString = "";
     int someInt = 0;
}

and so I implement it as follows

public void main() //Lets assume this is our entry point
{
      SomeObject obj = new SomeObject();

      //someBLL is an arbitrary static class that gets your data from the database or some other source and creates a new object to hold that data

      obj = SomeBLL.fetchObjectData();
}

What has happened here is a new object reference has been created, pointing to an object, only to be repointed to another object. Considering the new object:

     SomeObject obj = new SomeObject();

is quickly overwritten by some new object that someBLL.fetchObjectData(); returns. As mentioned before, C# has a garbage collector to deal with objects that are being disposed, but in reality this is a memory leak, garbage collector or not. For those who are just starting programming in C# (and Java), there are a few things that needs to be outlined:

  • “obj”, as I have named it above, is a reference to an object in the memory. It is not actually the object itself, but rather points to some location in memory at which the object is located
  • If you use the same reference again, for instance in obj = someBLL.fetchObjectData(); as mentioned above, the variable “obj” now points to a new location in memory for a completely different object.
  • When you re point your reference, you leave the old object still in memory taking up space.

So what is the solution to this? It’s very simple. Simply don’t create a new object before repointing your reference somewhere else. To correct the code above, we can do the following:

 public void main() //Lets assume this is our entry point
 {
      SomeObject obj = SomeBLL.fetchObjectData();
 }

However it is common that doing something like this is not quite so simple. For instance, what if I need to decide from where my data is coming from? I am getting the same object type back from either, but they load the object with different data. Consider the following code:

//Using an int here might not be most preferred (use an enum instead), but it will suffice
pubic SomeObject getMyData(int dataType)
{
      SomeObject obj;
      switch (datatype)
      {
           case 0:
           {
                obj = SomeBLL.getDataA();
           }
           case 1:
           {
                obj = SomeBLL.getDataB();
           }
      }
      return obj;
}

With the code above, it is very tempting to initialize the “obj” reference with a default value. Before it hits the case statement, it equals “null” (null == 0 in C/C++). However, if you do initialize it with a blank object you are more than likely to run into a deceivingly existing data, even when you have passed in 3 into your function. If you use the function wrong, you’re better with your code returning a null object. Otherwise you will end up with an empty object eventually somewhere down the road and its much harder to track down why you have empty objects.

Regardless, this is the approach you want to maintain. Provided vast memory sizes and a garbage collector I have encountered this mistake even with somewhat seasoned programmers. For some it might be a tough habit to break, but we must never forget we cannot pollute the heap with empty objects; otherwise its bad programming.