解耦问题 - 改进和替代方案

我正在学习 SOLID 原则——尤其是控制反转-DI-解耦,当我在审查我的一个代码时,我注意到这种方法(见下文)引起了我的注意。


此代码将由任何需要读取 json 文件的方法调用,接受将用于查找 json 文件的字符串值。但是正如您所看到的(我简化了代码 - 为了本主题排除了异常处理),我不确定从哪里开始(有很多初始化或依赖项??发生了,我不确定在哪里开始)。


这种方法/场景可以作为一个很好的选择开始吗?你认为我应该保留哪个?并且需要解耦?


谢谢。


public async Task<object> ReadJsonByKey(string jsonPath, string jsonKey)

{

    // First - is it okay to have an initialization at this stage?

    var value = new object();     


    // Second - is this fine to have this in the scope of this method?

    using (TextReader reader = File.OpenText(jsonPath))  

    {

        // Third -  Calling Jobject that accepts new instance of JsonTextReader

        var jObject = await JObject.LoadAsync(new JsonTextReader(reader)); 

        obj = jObject.SelectToken(jsonKey);

    }

    return value;

}

我问这个的原因也是因为(基于标准)松散耦合的东西可以很容易地测试 - 即单元测试


[UnitTestSuite]

    [TestCase1]

        // Method should only be able to accept ".json" or ".txt" file


    [TestCase2]

        // JsonPath file is valid file system


    [TestCase3]

        // Method should be able to retrieve a node value based from a specific json and key


    [TestCase4]

        // Json-text file is not empty


慕少森
浏览 172回答 1
1回答

函数式编程

看起来您正试图将基础设施问题与应用程序代码分离。假设是这种情况,您需要一个负责读取数据的类:public interface IDataReader{&nbsp; &nbsp; &nbsp;Task<object> ReadJsonByKey(string jsonPath, string jsonKey)}其实现将是您上面的代码:public class DataReader : IDataReader{&nbsp; &nbsp; public async Task<object> ReadJsonByKey(string jsonPath, string jsonKey)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // First - is it okay to have an initialization at this stage?&nbsp; &nbsp; &nbsp; &nbsp; var value = new object();&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // Second - is this fine to have this in the scope of this method?&nbsp; &nbsp; &nbsp; &nbsp; using (TextReader reader = File.OpenText(jsonPath))&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Third -&nbsp; Calling Jobject that accepts new instance of JsonTextReader&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var jObject = await JObject.LoadAsync(new JsonTextReader(reader));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj = jObject.SelectToken(jsonKey);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return value;&nbsp; &nbsp; }}但是,这个类现在同时进行文件读取和反序列化,因此您可以进一步分为:public class DataReader : IDataReader{&nbsp; &nbsp; IDeserializer _deserializer;&nbsp; &nbsp; public DataReader(IDeserializer deserializer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _deserializer = deserializer;&nbsp; &nbsp; }&nbsp; &nbsp; public async Task<object> ReadJsonByKey(string jsonPath, string jsonKey)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var json =&nbsp; File.ReadAllText(jsonPath);&nbsp; &nbsp; &nbsp; &nbsp; return _deserializer.Deserialize(json, jsonKey);&nbsp; &nbsp; }}这意味着现在可以IDeserializer独立于文件系统依赖项进行单元测试。但是,主要的好处应该是您现在可以IDataReader在对应用程序代码进行单元测试时模拟实现。
打开App,查看更多内容
随时随地看视频慕课网APP