What is the best practice for instantiating a class in Java?

Asked

Viewed 211 times

1

Aiming at performance, how should I instantiate an object (ex a Databasehandler) to be used in Fragments. I must instantiate them in Activity and pass via constructor method to the Fragments or instantiate them in each Fragment?

  • 3

    Classes are not called.

  • Okay thanks I’ll rephrase the question.

  • From what I have learned so far from JAVA Android everything you write of code is compiled for the executable bitecode of the virtual machine of java. So even if you call the object several times the memory consumption is basically the same. What exists is good code writing practices everything determines its logic and purpose. In my case I create a separate class and when I need to use it or use it as an interface. Besides the simplest everything gets separated in its proper place.

  • whatever. the important thing is the object that will be used several times not be of the static type.

  • The ideal is to be instantiated in each Fragment itself. Have you tried any code yet? Are you having some kind of error?

  • @Leonardo Dias has already made it work in both ways. The question is which is the best.

Show 1 more comment

1 answer

3


To know the best alternative, you would need to know if your object will be used by all fragments.

If so, it would be interesting to create an abstraction common to all fragments (e. g. AbstractFragment) that would implement a standard constructor to initialize this object as an attribute of this abstraction, and make it accessible to all child fragments. So you don’t repeat the statement of the object in all the fragments. In this approach, the state of the object may vary from fragment to fragment (i.e. it is not an attribute static) but his existence is common to all.

If the object belongs only to specific fragments, the ideal is to declare it within the scope of the fragment itself. In this approach you would add it as an attribute initialized by the constructor or parameter of a method depending on its use within the fragment. If it is used enough, put as attribute, otherwise, as parameter of the method that will use it. So you keep your classes cohesive.

Browser other questions tagged

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