HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Which option is better for readability when dealing with blank strings?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withreadabilityblankbetterdealingoptionforwhenwhichstrings

Problem

I'm working off a specification that says a bunch of fields within a record (one record being one line) must be blank. For example, it says that chars 6-14 must be blank. I am building a class hierarchy structure that represents the layout of the file, and within this class hierarchy I'm including every field for each type of record, including the blank ones.

Basically I want to know if I should make each field return a blank literal, or if I should pad string.Empty with spaces.

Example:

public string ImmediateDestinationRoutingNumber { get { return " "; } }


Versus

public string ImmediateDestinationRoutingNumber { get { return string.Empty.PadRight(8, ' '); } }


The second option of padding string.Empty looks the most readable to me, but I don't know if the runtime cost is significant enough to worry about.

Solution

Instead of returning a " " or string.Empty.PadRight(8, ' ') you should extract the values to some meaningful constants.

The easiest way would be for your example to just use the overloaded constructor of the String class like

private const string eightSpaces = new string(' ', 8);


this makes it clear for Mr./Mrs.Maintainer what it stands for. But because this seems to produce CS0133: The expression being assigned to must be constant. you should just use a readonly string like

private readonly string eightSpaces = new string(' ', 8);


Using your first version will lead for each bug which needs to be solved to count the spaces which are returned.

The name of this property is also poorly named. It doesn't represent an ImmediateDestinationRoutingNumber but instead ImmediateDestinationRoutingNumberSpaces.

Code Snippets

private const string eightSpaces = new string(' ', 8);
private readonly string eightSpaces = new string(' ', 8);

Context

StackExchange Code Review Q#78755, answer score: 11

Revisions (0)

No revisions yet.