Problems in common code based on ERP programs and solutions for excessive encapsulation that is not easy to maintain
- 2020-06-03 06:16:21
- OfStack
When designing an ERP program, it is necessary to extract common code into a common type library. This reduces code duplication and improves code utilization.
However, everything has to be done to a certain degree, and some common code leads to excessive encapsulation, which is detrimental to code understanding.
Here is an example
public class ConfigHelper
{
/// <summary> /// Gets whether the specified path is a valid absolute file path. /// </summary>
/// <param name="path">Any path. OK if null or empty.</param>
static public bool IsValidPath(string path)
{
Regex r = new Regex(@"^(([a-zA-Z]:)|(\))(\{1}|((\{1})[^\]([^/:*?<>""|]*))+)$");
return r.IsMatch(path);
}
public static string GetString(string key)
{
return System.Configuration.ConfigurationManager.AppSettings[key];
}
}
The second method, GetString, I think is not necessarily encapsulated. Encapsulating the code that calls the.NET framework, which is only one line or a few lines long, can be a barrier to understanding.
Let's look at another method, which is encapsulated according to the specific usage scenario.
public static decimal GetDecimal(string key)
{
decimal value = default(decimal);
if ((decimal.TryParse(GetString(key), out value)))
{
return value;
}
else
{
return 0m;
}
}
This method converts a string to a numeric type and returns the default value of 0 if its value is not numeric.
Depending on the scenario needed, this encapsulation may be necessary to reduce the amount of repetitive code.
Welcome to comment, I think this GetDecimal method is also redundant, unnecessary encapsulation.