I’m building some web user controls and just wondering what is the right / best practice approach to implement properties. In this example he control is a “score card” control which has to display a score ( and it also has to do other stuff) ….to make things easier I made these code samples very simple but in reality my control does other stuff as well with the score besides displaying it in a label 🙂
Choice #1
private int _score;
public int Score
{
get { return _score; }
set { _score = value; Refresh(); }
}
public void Refresh()
{
lblScore.Text = Score;
}
Choice #2:
public int Score {get;set;}
protected void PageLoad(object sender, EventArgs e)
{
Refresh();
}
private void Refresh()
{
lblScore.Text = Score;
}
Choice #3:
public int Score
{
get { lblScore.Text; }
set { lblScore.Text = value; }
}
So , of course, the question is what is the best practice way of implementing the Score property of the control ….:-)
MadSeb
Choice 1
Refresh.Labelyou don’t want somebody to remember that he has to callRefreshafter he has set theScore. But that depends on how expensive “my control does other stuff as well with the score besides displaying it in a label” is. If you often change the Score but not necessarily need to refresh immediately, i would do theRefreshafter all initialization has done.In my opinion a UserControl should encapsulate complexity as long as it keeps enough flexibility and control to be reusable. Don’t do too much “magic” things in the background that might cause errors in different conditions that you won’t find quickly. That is particularly so in a
Setterwhat normally only should set the corresponding variable.There are two different use cases for an UserControl:
If your control contains only few controls but you want to reuse it many times, i would let the controller get/set properties and don’t do complex things in it that depend on specific conditions. That would reduce reusability. You might want to provide clear methods and events that the controller could handle.
If your control behaves similar to a page and has a lot of controls and functionality, it should do most of all by itself. You only want to provide a few methods and events(that don’t have to be handled necessarily). The most important method in this case would be e.g. a
public void BindData()that does all initialization after the controller has set the necessary variables. That is the replacement for yourChoice 2.Note: if your score is stored in
lblScore.Textas string anyway, i would prefer using theTextproperty of the label instead of creating another int-variable(cast it to an int in the getter). That has the advantages that you don’t need to store your variable in ViewState manually, because it’s already stored. On this way you don’t need to set it on every postback.