One of the facets of good coding practices that almost everyone seems to agree on is that redundancy in code, usually via copy and paste, is a dangerous thing.
I saw a great example of this in some ASP.NET code I was working with recently. A tester had reported that some of the items in a display were being truncated inappropriately, while others weren’t being truncated at all. I looked at the screen and could immediately tell what was wrong. Every other row in the table was truncated. It corresponded perfectly with the ledger-paper-style alternating background colors.
Looking at the code, I saw the following things (simplified):
<asp:Repeater id="repeater" runat="server">
<tr bgcolor="#FFFFFF"><td><%# DataBinder.Eval(Container.DataItem, "Title")%></td></tr> </ItemTemplate>
<tr bgcolor="#CCCCCC"><td><%# DataBinder.Eval(Container.DataItem, "TruncatedTitle")%></td></tr>
The vast majority of the code in AlternatingItemTemplate has the same intention as the code in ItemTemplate. Whenever you have duplicated code (or near-duplicated code) you will eventually forget to update one of the two things that need to be updated in parallel. Hence the bug.
An alternative, would be to not have the duplicated/duplication-heavy AlternatingItemTemplate, but instead, call a method to get the row color, like this:
<tr bgcolor="<% = GetCurrentRowColor()%>">
<td><%# DataBinder.Eval(Container.DataItem, "TruncatedTitle")%></td></tr></ItemTemplate>
In the code behind (or even someplace more generalized, if you are going to use this layout more than once, of course), you could have this simple logic:
private const string initialRowColor = "#FFFFFF";
private const string alternatingRowColor = "#CCCCCC";
private string lastRowColor = initialRowColor;
public string GetCurrentRowColor()
if(lastRowColor == initialRowColor)
lastRowColor = alternatingRowColor;
lastRowColor = initialRowColor;
One Courtesy Note: in the off-chance that my comrade who introduced this problem is reading this, I don’t mean to single you out or pick on you. It’s the sort of mistake that I’ve made a billion times myself, and wanted to capture what I felt was a reasonable solution to the AlternatingItemTemplate redundancy problem.
Also, in case any ASP.NET gurus are out there, I generally don’t like to use the DataBinder.Eval syntax, this is a simplified example, remember?