Quality Code Short Tip #3 – Use Nested Class for Constants
One of the ‘best-practice’ and code styling guidelines say that you need to use constants instead of literals for more readability and ease of maintenance. Among the usages there are time that you want to specify database field names, xml attribute / element names and etc. In such cases the code easily get messed with dozens of constants around the code and make it harder to find the constant you need.
A little trick can aid here:
Instead of:
1: class TheClassUsingTheConstants
2: {
3: public const string CustomerIdField = “CustomerId”;
4: public const string CustomerNameField = “CustomerName”;
5: public const string TaskIdField = “TaskId”;
6: public const string TaskTitleField = “TaskTitle”;
7:
8: private void UseConstants(IDataReader reader)
9: {
10: var fieldValue = reader[CustomerIdField];
11: }
12: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Use:
1: class TheClassUsingTheConstants
2: {
3: private static class CustomerFields
4: {
5: public const string Id = “CustomerId”;
6: public const string Name = “CustomerName”;
7: }
8:
9: private class TaskFields
10: {
11: public const string Id= “TaskId”;
12: public const string Name = “TaskTitle”;
13: }
14:
15: private void UseConstants(IDataReader reader)
16: {
17: var fieldValue = reader[CustomerFields.Id];
18: }
19: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }