I am asking about a recommendation to use getters and setters. I wrote the same code in two versions: using getters and setters and using just the class method. And I can't clearly see the difference between them.
I wrote the class Book with the private field rating. And the constructor Book can assign something to Book.rating by RatingSetter or by RatingMethod. RatingMethod only sets the values, but I can also create a method only for getting values.
class Book
{
public string title;
public string author;
private string rating;
public Book(string title, string author, string rating)
{
this.title = title;
this.author = author;
RatingSetter = rating;
RatingMethod(rating);
}
public string RatingSetter
{
get { return this.rating; }
set
{
if (value == "PG" || value == "PG-13" || value == "R")
{
rating = value;
}
else
{
rating = "NR";
}
}
}
public string RatingMethod(string rating)
{
if (rating == "PG" || rating == "PG-13" || rating == "R")
{
return this.rating = rating;
}
else
{
return this.rating = "NR";
}
}
}
In my opinion, there is no difference about security, validation or anything. Could anyone guide and help me to understand what's the difference and why is it recommended to use getters and setters.
Getters and setters are just syntactic sugar. The compiler will compile your getters and setters into getter and setter methods eventually. So by writing getter and setter methods yourself, you are kind of doing the job of the compiler.
Therefore, I recommend you to use getters and setters, because one of their main purposes is to replace getter and setter methods.
Here are some other advantages of using getters and setters:
Getters and setters can save you a lot of time if you only need getters and setters without any logic:
public int Property { get; set; }
In my opinion, the aesthetic of getters and setters look better. Compare:
obj1.Property += obj2.Property;
with
obj1.SetProperty(obj1.GetProperty() + obj2.GetProperty());
I feel like the latter just has too many parentheses.
Keep the setters and getters close to the property declaration. If you use getter and setter methods, you could accidentally write other methods between the property declaration and the getter/setter methods, causing the getter/setter methods to slowly "drift away" from the property declaration. Next time you want to find it, you need to scroll up and down. With getters and setters, they will always be below the property declaration.