dpxnrx11199 2016-11-13 08:49
浏览 8

具有不同成分的多个结构

I have a problem that I am not sure how to solve in Go. I need to make a client that talks to a json based api.

So I thought that I would use composition to build the struct similar to below.

type (
    BaseData struct {
        CommonFields string
    }

    Data struct {
        BaseData
        Result string
    }
)

Now I would send the Data struct to the api and unmarshal the response to the results, all good so far.

Now the issue is that I have different requests to send that require a different "results" composition and therefore would need to have many definitions of the Data struct in the same package, which is no good.

I am struggling to see how this should be done. Any pointers in a direction will great.

  • 写回答

1条回答 默认 最新

  • dqxboe2628 2016-11-13 09:53
    关注

    Do not create a model structure that mirrors or imitates the API you want to use. Design your model in a way that makes sense to your program, following DDD principles at a high conceptual level, and SOLID principles at implementation level, for example.

    Most probably:

    • You don't need all the features of the foreign API. By adhering too much to their structures, you will implement a lot of boilerplate that serves no purpose of its own in your program.
    • You don't want your program to break down due to minor changes in the foreign API.

    Create a layer in your program for communicating with the foreign API, and make the rest of your program depend on this layer, never directly on the foreign API. This way, if something changes in the API, you just need to change the communication layer, the rest of the program can continue working unaffected.

    In this communication layer, use whatever structures needed to talk to the API. Do not use any structures not needed. And convert these structures to the structures used within the rest of your program. This may involve a lot of manual copying that might not seem pretty at first, but it's the way to protect your program from external changes.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀