When can I use Static in class?

Asked

Viewed 1,129 times

3

I know the use of methods static should be avoided, so I have a question and I do not know if it is right to implement a ArrayList as static, it is accessed by several classes and contains data from every program (I only want an omnic list), in this case it is okay to use static?

The methods of this class (handle and read the ArrayList) should also be static or should I instantiate the object when using?

An excerpt from the code:

public class DadosSalvos {

    static private ArrayList <Dados> dados = new ArrayList <>();

    public static void setDados(ArrayList dados) {
        DadosSalvos.dados = dados;
    }

    public static ArrayList getDados() {
        return dados;
    }

}
  • There is a synchronized list in Java, which should be better for this than arraylist, I just can’t remember the name now.

  • java.util.Vector

2 answers

6


I know the use of methods static should be avoided

Why? Silly little rule told by someone? If you have reason to use have no reason not to use. In fact it is preferable by pragmatic programmers whenever it can be used smoothly.

implement a ArrayList as Static, it is accessed by various classes and contains data from every program

If the application involves competition you have to deal with it properly. If it does not involve and only should have a list of this for every application there is no big problem no. Of course in complex application can be a problem. In fact global state is a problem and should be avoided, but in complex applications.

The methods of this class (handle and read the ArrayList) should also be Static or should instantiate the object when using?

Generally methods accessing static state must be static, I just saw no use for them in this case.

In simple applications a lot of things that say you can’t actually access fields (that people mistakenly call attributes) without getters and setters.

You can’t memorize rules and try to apply, you have to understand the reason for everything you’re going to use and know when to use and when not to use. If you only know the rule you can never decide when to use.

Depending on the context I would do completely different, but so simple I would do just this:

public class DadosSalvos {
    static ArrayList <Dados> dados = new ArrayList<>();
}

I put in the Github for future reference.

Maybe I didn’t even start anything, maybe I designed it quite differently.

0

I think you need a controller class. Look for the design standard Singleton. However, Singleton is considered an anti-ban, precisely for using Static and increase the dependency on classes that are not associated. So, if you want to use something a little more elegant, I recommend studying about Dependency injection, even present in various frameworks for various LP’s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.