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.