Reputation: 12216
I have to generate a csv file from my db. I am using C# and I can do this. My question is more to do with validation. I was thinking of doing this:
public class MyObject
{
private string myString;
public string MyString
{
get
{
return this.myString;
}
set
{
this.myString = value.Remove(15).PadRight(15);
}
}
Obviously 15 is the max length on this field. Is this an idiotic way to handle this? I am open to suggestions. This is just the tip of the iceberg for this program that will be generating numerous different csv's and I want to make sure I set up a sustainable pattern.
Upvotes: 1
Views: 712
Reputation: 67898
The problem with this pattern is that you're going to miss any bad records because you're swallowing the exception by simply massaging the data. However, if that's what you want then it's perfect.
Another approach would be to push these records to an error list and let the user determine what to do with them after it's all done. So, you could do something like this:
public sealed class BadRecords
{
private static BadRecords _instance;
public static BadRecords Instance
{
if (_instance == null) { _instance = new BadRecords(); }
return _instance;
}
private BadRecords() { this.List = new List<MyObject>(); }
public List<MyObject> List { get; set; }
}
public class MyObject
{
private string myString;
public string MyString
{
get
{
return this.myString;
}
set
{
if (value.Length > 15) { BadRecords.Instanse.List.Add(this); }
else { this.myString = value.Remove(15).PadRight(15); }
}
}
however, there is still one problem with your solution, you're not really just taking the first 15 characters. In fact, the code you have would error on a string less than 15 characters. Consider something more like this:
this.myString = value.Length > 15 ? value.Substring(0, 15) : value;
if you're insistent on swallowing the error.
However, in the solution I provided you could simply use this:
this.myString = value.PadRight(15);
because we've already checked to see if it's greater than 15 characters.
Upvotes: 2