Mukil Deepthi
Mukil Deepthi

Reputation: 6492

Object oriented way to validate a delimited line of a text file

I have a pipe delimited line in a text file. What is the best way to validate the line. I have a definite format for how each token in the line should be i.e for eg; say 5th item should be a date.

Could anyone help me what is the best object oriented way to achive this?Is there any design pattern to achieve this?

Thanks

Upvotes: 0

Views: 409

Answers (2)

fharreau
fharreau

Reputation: 2357

The "clean" way for achieve this would be to use Regular Expression. Here is a basic example :

var allLines = new List<string>();

for (int i = 0; i < 5; i++)
{
     allLines.Add("test" + i);
}

// if you add this line, it will fail because the last line doesn't match the reg ex
allLines.Add("test");

var myRegEx = @"\w*\d"; // <- find the regex that match your lines
Regex regex = new Regex(myRegEx);
var success = allLines.All(line => regex.Match(line).Success);

In this example, my regex is waiting for a word immediately followed by a digit. All you have to do is to find the regex that match your line.

You can also avoid the linq expression by using a more complexe reg ex.

Give us your token so we can help you with.

Upvotes: 0

bjhuffine
bjhuffine

Reputation: 934

You're looking for a specific pattern for validation. That can be done any number of ways, but the simplest is to validate in the constructor of the object. Since you're looking for a more OO approach, you might consider creating an object to represent the file and an object to represent each record. There's no real pattern here other than associational. You could, however, utilize the iterator pattern to allow your records to be iterated in a loop. You're talking about reading a text file so that's not complicated enough of a process, but if it was, you could consider a factory pattern to create the file object. If there's a lot to validate, then you could create a separate method to validate each in your class. Here's an example of what I'm talking about...

 static void Main(string[] args)
    {

        DataFile myFile = new DataFile(@"C:\...");

        foreach (DataRecord item in myFile)
        {
            Console.WriteLine("ID: {0}, Name: {1}, StartDate: {2}", item.ID, item.Name, item.StartDate);
        }

        Console.ReadLine();
    }


    public class DataFile : IEnumerable<DataRecord>
    {
        HashSet<DataRecord> _items = new HashSet<DataRecord>();


        public DataFile(string filePath)
        {
            // read your file and obtain record data here... 
            //I'm not showing that
            //... then begin iterating through your string results
            //... though I'm only showing one record for this example

            DataRecord record = new DataRecord("1234|11-4-2015|John Doe");
            _items.Add(record);
        }


        public IEnumerator<DataRecord> GetEnumerator()
        {
            foreach (DataRecord item in _items)
            {
                yield return item;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class DataRecord
    {
        private int _id;

        public int ID
        {
            get { return _id; }
            private set { _id = value; }
        }

        private DateTime _startDate;

        public DateTime StartDate
        {
            get { return _startDate; }
            private set { _startDate = value; }
        }

        private string _name;

        public string Name
        {
            get { return _name; }
            private set { _name = value; }
        }

        internal DataRecord(string delimitedRecord)
        {
            if (delimitedRecord == null)
                throw new ArgumentNullException("delimitedRecord");

            string[] items = delimitedRecord.Split('|');


            //You could put these in separate methods if there's a lot

            int id = 0;
            if (!int.TryParse(items[0], out id))
                throw new InvalidOperationException("Invalid type...");

            this.ID = id;

            DateTime startDate = DateTime.MinValue;
            if (!DateTime.TryParse(items[1], out startDate))
                throw new InvalidOperationException("Invalid type...");

            this.StartDate = startDate;

            //This one shouldn't need validation since it's already a string and 
            //will probably be taken as-is
            string name = items[2];

            if (string.IsNullOrEmpty(name))
                throw new InvalidOperationException("Invalid type...");

            this.Name = name;
        }


    }

Upvotes: 1

Related Questions