Understanding class instantiation

Asked

Viewed 352 times

3

I have a question and I would like to understand better how class instantiation works. More specifically the most appropriate way to do (if any) and the impacts of doing in the wrong way.

Assuming these two scenarios, which one should I use and why?

Scenario 1: Instantiating outside the methods.

public class PerfilController : Controller
{
    PerfilDTO viewDTO = new PerfilDTO();
    Perfil perfilNEG= new Perfil();
    Recurso recursoNEG = new Recurso();

    public ActionResult Cadastro()
    {
        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }      

    public ActionResult Listagem()
    {
        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }      
}

Scenario 2: Instantiating within methods

public class PerfilController : Controller
{      
    public ActionResult Cadastro()
    {
        PerfilDTO viewDTO = new PerfilDTO();
        Perfil perfilNEG= new Perfil();
        Recurso recursoNEG = new Recurso();

        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }      

    public ActionResult Listagem()
    {
        PerfilDTO viewDTO = new PerfilDTO();
        Perfil perfilNEG= new Perfil();
        Recurso recursoNEG = new Recurso();

        viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
        viewDTO.ListaRecursos = recursoNEG.ObterRecursos();

        return View(viewDTO);
    }      
}

NOTE: If there is another way and better can also alert me.

  • 1

    If you declare property within the method, it only exists in the method. If it is outside, it belongs to the instance and is visible in all methods.

  • Yeah, I’d rather put it away, but since I don’t quite understand it, I was still afraid it might be bad somehow. There is no problem then to start out of the methods then?

  • Look, I’m no expert on C#, but it would be nice to state the visibility of these properties (private, public, etc.). So without declaring should all be implicitly public.

  • 1

    Friend, I’m no expert either, but I recommend researching on "Lazy Initialization", or "Initialization on Demand", where you only create the object instance when you actually use it, and this standard also implements the "Singleton" standard. Perhaps the evening if no one has elaborated an answer on this I post one. But I recommend reading on this subject.

2 answers

4


In my view:

Instantiating the first way, when you create the object PerfilController 3 more objects will also be created in memory (PerfilDTO, Perfil and Recurso) even if they are never used.

Instantiating the second way, the 3 objects mentioned will be created only when the methods are called, that is, when it is really necessary. The disadvantage is that you need to instantiate in each method (code repetition) and the objects will be created several times in memory according to the number of calls to the method.

What you could do (what I’m going to talk about can be analyzed) is to use the pattern of projects Singleton, that guarantees only one instance of a given object. Example:

private ClasseExemplo getObjetoExemplo() {
    if (objetoExemplo == null) {
        objetoExemplo = new ClasseExemplo();
    }
    return objetoExemplo;
}

And where necessary, it would be enough to use this method:

objeto.objetoExemplo = getObjetoExemplo():

Thus it would be guaranteed that the object would be instantiated only when necessary and only once.

I wanted to give my contribution according to what I understand, maybe other people explain in a broader and didactic way that I.

  • My project is very small. In this case instantiating out of the methods will not cause as much impact of memory. Am I right? Or say that in a controller access looping this can be harmful?

  • 2

    I don’t see that it can be harmful, even more so being a small system, but as we failed humans can’t predict all situations that can occur in a system, I recommend you do it in the best way possible, regardless of whether it is a small system or not (I am not claiming that my answer is the best way). Advice (which is also for me): when developing a system, even small, always worry about scalability, maintainability and performance.

  • Right, I’m trying to do that, so I came to get the best alternative with the opinions here! Thank you very much!

  • Completing the correct answer from Electus: If you declare the objects at the "top" of the class, every time this class is instantiated that objects will also be created, even if they are not necessary and this can cause performance problems. Each case is a case, but try to analyze well where you initialize the objects, to make sure they are within the correct scope (within the method, within the class) and gain in performance and also organization of your code. Even though it is a small application one day it can be big and these initial errors can cause you problems up front.

2

There’s another way that’s different and better.

I recommend you use the standard Repository to retrieve the information necessary for your Controller.

Why use it in that situation?

With this standard you can avoid this duplication of codes to instantiate your objects, improve code maintenance, among other benefits such as conducting tests.

What’s wrong with creating these instances in Controller?

It’s not your responsibility Controller instantiate objects like Profile, Profile and Resource. It is the responsibility of the Controller to retrieve data from the Model and forward the related View to display this data.

  • I believe that if you gave an example of how to use this pattern it would be clearer.

Browser other questions tagged

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