<p><a href="https://github.com/jamesseanwright/golang-tdd-factorial" rel="nofollow">https://github.com/jamesseanwright/golang-tdd-factorial</a></p>
<p>I've been playing with Go for a while now and I wrote a very simple function for generating <a href="https://en.wikipedia.org/wiki/Factorial" rel="nofollow">factorials</a> using Test-Driven Development. You can see from the commit history how I've written the tests first, satisfied them, and then refactored the code without causing any regressions.</p>
<p>Any feedback is welcome and appreciated!</p>
<hr/>**评论:**<br/><br/>tv64738: <pre><pre><code> expectedFactorial := 720
actualFactorial := GetFactorial(n)
assertMatch(t, expectedFactorial, actualFactorial)
</code></pre>
<p>why not just</p>
<pre><code> if g, e := GetFactorial(n), 720; g != e {
t.Errorf("wrong factorial: %d != %d", g, e)
}
</code></pre></pre>swan--ronson: <pre><p>As funky as that is, I don't think it's as readable. Even setting aside the single letter variable names, I've never enjoyed assignments in conditions. Good to know that this is possible though, thanks!</p>
<p>That said, I'd definitely be up for rewriting the assignments as follows:</p>
<pre><code>expectedFactorial, actualFactorial := 720, GetFactorial(n)
assertMatch(t, expectedFactorial, actualFactorial)
</code></pre></pre>shovelpost: <pre><p>If single letter variable names are a problem then how about:</p>
<pre><code>if got, want := GetFactorial(n), 720; got != want {
t.Errorf("wrong factorial: %d != %d", got, want)
}
</code></pre>
<p>For better or worse, this "funky" way is considered the <a href="https://golang.org/doc/faq#testing_framework" rel="nofollow">"standard" way of testing in Go</a>.</p></pre>swan--ronson: <pre><p>Actually, with more fleshed out variable names, this looks better. I like <code>got</code> and <code>want</code>; they're both short and descriptive. Thanks for your help!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传