When can I use static in the class?

2

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

Should the methods of this class (which are manipulating and reading the ArrayList ) also be static or should I instantiate the object when using it?

A snippet of 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;
    }

}
    
asked by anonymous 27.09.2017 / 23:31

2 answers

5
  

I know that using static methods should be avoided

Why? Silly rule said by someone? If you have reason to use you have no reason not to use it. In fact it is preferred by pragmatic programmers whenever it can be used without problems.

  

Implement an ArrayList as static, it is accessed by several classes and contains data from every program

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

  

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

Generally methods that access static state should be static, I just did not see utility for them in this case.

In simple applications a lot of things that say they can not in fact can, for example access attributes without getters and setters .

You can not decorate rules and try to apply, you have to understand the reason for everything you will use and know when to use r when not to use. If you only know the rule, you'll never be able to decide when to use it.

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

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

Maybe I did not even initialize anything, maybe I would architect a lot differently.

    
27.09.2017 / 23:42
0

I think you need a controlling class. Look for the Singleton design pattern. However, Singleton is considered an anti-pattern, precisely because it uses static and increase the dependency of classes that are not associated. So, if you want to use something a bit more elegant, I recommend studying about Dependency Injection, including present in several frameworks for various LP's.

    
27.09.2017 / 23:59