<p>I am working on this project:</p>
<p><a href="https://github.com/LuCavallin/yfirbord-grovepi" rel="nofollow">https://github.com/LuCavallin/yfirbord-grovepi</a></p>
<p>How is it so far, can I improve it somehow? Anyways, my question is: as you can see, I have a grovepi.config.json and sensors.config.json files where I keep the configuration. I'd like to load these in memory and use them from there for more flexibility.</p>
<p>I'm trying to abstract the sensors part, but I can't quite tell how to do it. My idea is: I load a list of sensors from the config file, each sensor could be read in a different way, therefore I need to abstract the Read function. I then loop through the sensors and keep reading, but doesn't matter the exact configuration, the code will sort it out automatically.</p>
<p>Any suggestions?</p>
<hr/>**评论:**<br/><br/>shovelpost: <pre><p>Figure out what is common between the sensors and create an interface based on that.</p></pre>gentleman_tech: <pre><p>Looks OK to me. </p>
<p>Your NewSensor function is probably unnecessary; anywhere you call that you could just use x := Sensor{<values>}</p>
<p>Abstraction-wise it looks OK. You've pulled the only command out into an interface so you can call it for different implementations.</p>
<p>I would rename it to Reader though. If you add more commands you'll be tempted to add them to a common interface. Instead of grouping functionality by source, group it by use. So instead of having a single interface for all sensors, have an interface for all the functions that a caller will call on an interface during an operation. That's not very clear, let me give an example:</p>
<p>Let's say you decide to abstract the configuration more. So you implement a Configure function to take a chunk of JSON and set the sensor up. You'd be tempted to do this:</p>
<pre><code>type InputSensor interface {
Configure(String) error
Read() (measurement, error)
}
</code></pre>
<p>because that's the things a Sensor does, right?</p>
<p>But it makes much more sense to separate them into Configurable and Readable interfaces. That way when you start playing with motors you can re-use the Configurable interface. Or when you start reading from StdIn which isn't Configurable you don't break anything.</p>
<p>You might have a Calibrate operation that needs to happen for all reading sensors (for example). Your code doesn't want to work out if the sensor needs to be calibrated or not, so it makes sense to add that to the Readable interface, like so:</p>
<pre><code>type Readable interface {
Calibrate(Int, Int) error
Read() (measurement, error)
}
</code></pre>
<p>Because these things are related to the Read operation, they belong together.</p>
<p>I hope that makes sense...</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传