patterncsharpModerate
Editing e-commerce website values
Viewed 0 times
valueswebsitecommerceediting
Problem
Each product in my e-commerce website has Arabic and English values for the title, description and excerpt. I have this method
The method works well, but I think I can improve the way I write it to be more elegant.
Any suggestions?
EditProduct to update those values based on current culture (Arabic or English)public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
{
var product = DoSomeMagicToGetAProduct();
if (element == "title")
{
if (culture == "en")
{
if (edit1)
{
product.Title = text1;
}
if (edit2)
{
product.TitleAr = text2;
}
}
if (culture == "ar")
{
if (edit1)
{
product.TitleAr = text1;
}
if (edit2)
{
product.Title = text2;
}
}
}
if (element == "description")
{
// similar codes here
}
if (element == "excerpt")
{
// similar codes here
}
product.Save();
}The method works well, but I think I can improve the way I write it to be more elegant.
Any suggestions?
Solution
I think the code is a little dodgy, and the design is dodgy. I'd store the translation in a dictionary of some sort.
But addressing your immediate question, to simplify the code you have, you could do....
But addressing your immediate question, to simplify the code you have, you could do....
public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
{
var product = DoSomeMagicToGetAProduct();
var arText = culture == "ar" ? text1 : text2;
var enText = culture == "en" ? text1 : text2;
var updateEn = culture == "en" ? edit1 : edit2;
var updateAr = culture == "ar" ? edit1 : edit2;
if (element == "title")
{
if (updateEn) product.Title = enText;
if (updateAr) product.TitleAr = arText;
}
if (element == "description")
{
if (updateEn) product.Description = enText;
if (updateAr) product.DescriptionAr = arText;
}
if (element == "excerpt")
{
if (updateEn) product.Excerpt = enText;
if (updateAr) product.ExcerptAr = arText;
}
product.Save();
}Code Snippets
public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture)
{
var product = DoSomeMagicToGetAProduct();
var arText = culture == "ar" ? text1 : text2;
var enText = culture == "en" ? text1 : text2;
var updateEn = culture == "en" ? edit1 : edit2;
var updateAr = culture == "ar" ? edit1 : edit2;
if (element == "title")
{
if (updateEn) product.Title = enText;
if (updateAr) product.TitleAr = arText;
}
if (element == "description")
{
if (updateEn) product.Description = enText;
if (updateAr) product.DescriptionAr = arText;
}
if (element == "excerpt")
{
if (updateEn) product.Excerpt = enText;
if (updateAr) product.ExcerptAr = arText;
}
product.Save();
}Context
StackExchange Code Review Q#3993, answer score: 10
Revisions (0)
No revisions yet.