Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is object creation in getters bad practice?

Tags:

Let's have an object created in a getter like this :

public class Class1 {        public string Id { get; set; }        public string Oz { get; set; }        public string Poznamka { get; set; }         public Object object        {              get              {                   // maybe some more code                   return new Object { Id = Id, poznamla = Poznamka, Oz = OZ };              }         }  } 

Or should I rather create a Method that will create and return the object ?

like image 551
user137348 Avatar asked Jan 20 '10 13:01

user137348


People also ask

Is lazy initialization of objects a good practice?

Lazy initialization is usually used to delay the construction of objects that take a long time to be constructed or that take a lot of memory once fully constructed. That is a very valid reason for using lazy initialization.

Are getters and setters OOP?

With getters and setters, we achieve one more key principle of OOP, i.e., abstraction, which is hiding implementation details so that no one can use the fields directly in other classes or modules.

What's the advantage of using getters and setters that only get and set instead of simply using public fields for those variables?

1) getter and setter method gives you centralized control on how a the particular field is initialized and provided to the client which makes the validation and debugging much easier. you can simply put breakpoints or print statement to see which thread are accessing and what values are going out.

Should I use getters and setters in C#?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.


1 Answers

Yes, it is bad practice.

Ideally, a getter should not be changing or creating anything (aside from lazy loading, and even then I think it leads to less clear code...). That way you minimise the risk of unintentional side effects.

like image 78
Mitch Wheat Avatar answered Jan 01 '23 22:01

Mitch Wheat