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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With