I have an ASP.NET MVC project wherein I need to follow the open closed principles.
The project converts a .csv file to a model from a database, but in the future we might also have to convert Excel files to the same model from the database.
Now, I have this code in the Convertor class:
public class Convertor
{
private static ICompanyRepository companyRepository;
/// <summary>
/// converts the uploaded csv data to Company model
/// </summary>
/// <param name="filePath">the csv data</param>
/// <returns>a list of Compamy model</returns>
public List<Company> ConvertCsvToCompanyModel(string filePath)
{
companyRepository = new CompanyRepository(new ImportContext());
List<Company> companies = new List<Company>();
//Read the contents of CSV file.
string csvData = System.IO.File.ReadAllText(filePath);
//we skip the first row, because it contain the header
var csvLines = csvData.Split('\n').Skip(1);
//Execute a loop over the rows.
foreach (string row in csvLines)
{
if (!string.IsNullOrEmpty(row))
{
if (!companyRepository.CompanyExist(row.Split(',')[0]))//check if already contains the ExternalId
{
companies.Add(new Company
{
//CounterPartId
ExternalId = row.Split(',')[0],
//Name
TradingName = row.Split(',')[1],
//IsBuyer
IsForwarder = Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), row.Split(',')[2])),
//IsSeller
IsCarrier = Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), row.Split(',')[3])),
//Phone
Phone = row.Split(',')[4],
//Fax
Fax = row.Split(',')[5]
});
}
}
}
return companies;
}
}
Can you please give me some hints how to change this code in order to follow the open closed principle? In the future, as I mentioned, it is possible to need a converter for Excel files, too.