c# - 重构具有内部静态属性的结构
问题描述
我遇到了一位前雇员的相当多的课程。在检查代码是什么时,我遇到了一个struct
带有internal static
属性的东西。
该结构经常使用。大多数属性只有一个get
,但有些确实有一个set
和get
。该结构大约有 200 行长,其中包含嵌套的内部结构。
我无法理解这个结构以及这个人想要用它实现的目标。
它没有经过测试,也没有文档让我想知道为什么这个人决定实现这样的东西。
该结构主要包含在整个程序中使用的设置和路径。
在我重构此代码并将其称为开发人员的“早期杰作”之前,我想检查一下我是否弄错了,在非常罕见的情况下使用这样的东西是一个相当合理的想法。
我的问题是:为什么有人应该使用具有公共静态属性的结构,以及如何摆脱它(可能是众所周知的重构或类似的东西),因为它在整个代码中都使用过(Visual Studio 统计了大约 800 个引用)
顺便说一句:它没有放在任何命名空间中
internal struct ConfigurationPaths
{
private static string _pathConfig;
private static string _pathConfigUI;
private static string _pathConfigUI_Default;
private static string _pathConfig_DataToView;
//... removed the following lines due to readability in the question
internal static string AppPath
{
get
{
Module[] mod = Assembly.GetExecutingAssembly().GetModules();
return Path.GetDirectoryName(mod[0].FullyQualifiedName);
}
}
internal static string FilePath
{
set { _pathConfig = value; }
get { return _pathConfig; }
}
internal static string UserInterface
{
set { _pathConfigUI = value; }
get { return _pathConfigUI; }
}
internal static string UserInterface_Default
{
get
{
if (_pathConfigUI_Default == null)
{
String appPath = AppPath.AppendPathSeperatorIfNeeded();
_pathConfigUI_Default = String.Format("{0}files{1}config{1}ui{1}default.ux", appPath, Path.DirectorySeparatorChar);
}
return _pathConfigUI_Default;
}
}
internal static string UserInterface_GridView
{
set { _pathConfig_DataToView = value; }
get { return _pathConfig_DataToView; }
}
//... removed the following lines due to readability in the question
}
解决方案
看起来意图是用于配置。如果是这种情况,静态类会更有用
internal static class Configuration { ... }
这样struct
做没有任何价值,也不是惯用的。至于他们为什么这样做……可能只是不是最伟大的开发者。我会将配置类放在项目的根名称空间中,尽管他们可能将其放在任何名称空间中以避免using
在整个代码库中进行一些声明。
如果全局/静态性质困扰您,我建议将整个事物转换为实例属性并将其传递给需要它的事物。这样做,它变得更像一个配置服务——可能完全删除设置器并内化执行设置的代码。这样肯定会更加面向对象。
这也有助于依赖注入和可测试性,特别是如果你在它上面加上一个接口。
推荐阅读
- angular - 在不使用提交按钮的情况下上传多个带有预览的图像
- javascript - 反应原生 - '未定义不是对象'?
- python - Python:帮助修复我秒表上的重置功能
- reactjs - Shopify 石板主题样式未加载
- c# - Unity - 将四元数转换为 Vector3
- mysql - mysql join查询ID IN
- batch-file - Windows批处理文件循环多次打印文件
- python - Python ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')"))
- c# - CultureInfo 在 linux-64 centos 的生产环境中不起作用
- java - JFreeChart 和 Hibernate 中的问题