从问题传递到代码的过程.你是怎么学习的?

Osc*_*Ryz 8 process

我在教学/帮助学生编程.

我记得当我开始时,以下过程总能帮助我; 它看起来非常直观,我想知道其他人是否有类似的方法.

  1. 阅读问题并理解(当然).
  2. 确定可能的"功能"和变量.
  3. 写一下我将如何逐步完成(算法)
  4. 将它翻译成代码,如果有什么是你做不到的,创建一个为你做的动作并继续前进.

随着时间和实践,我似乎忘记了从问题描述转到编码解决方案有多难,但是,通过应用这种方法,我设法学习如何编程.

所以对于项目描述如下:

系统必须根据以下规则计算物品的价格(规则的描述......客户,折扣,可用性等等.等等.)

我的第一步是了解问题所在.

然后识别项目,规则变量等.

伪代码类似于:

function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int 
   if( hourOfDay > 18 ) then
      discount = 5%

   if( quantity > 10 ) then
      discount = 5%

   if( clientAge > 60 or < 18 ) then
      discount = 5%


        return item_price - discounts...
end
Run Code Online (Sandbox Code Playgroud)

然后将其传递给编程语言..

public class Problem1{
    public int getPrice( int itemPrice, int quantity,hourOdDay ) {
        int discount = 0;
        if( hourOfDay > 10 ) {
             // uh uh.. U don't know how to calculate percentage... 
             // create a function and move on.
            discount += percentOf( 5, itemPriece );
            .
            .
            .
            you get the idea..

        }
     }
    public int percentOf( int percent, int i ) {
             // .... 
    }


}
Run Code Online (Sandbox Code Playgroud)

你有没有采用类似的方法?有人教你一个类似的方法,或者你发现了自己(就像我做的那样:()

jop*_*jop 11

我通过测试驱动的方法.

1.我(在纸上或纯文本编辑器上)写下一份满足问题需要的测试或规范列表.

- simple calculations (no discounts and concessions) with:
    - single item
    - two items
    - maximum number of items that doesn't have a discount
- calculate for discounts based on number of items
    - buying 10 items gives you a 5% discount
    - buying 15 items gives you a 7% discount
    - etc.
- calculate based on hourly rates
    - calculate morning rates
    - calculate afternoon rates
    - calculate evening rates
    - calculate midnight rates
- calculate based on buyer's age
    - children
    - adults
    - seniors
- calculate based on combinations
    - buying 10 items in the afternoon
Run Code Online (Sandbox Code Playgroud)

2.查找我认为最容易实现的项目并为其编写测试.例如单件物品看起来很容易

使用Nunit和C#的示例.

[Test] public void SingleItems()
{
    Assert.AreEqual(5, GetPrice(5, 1));
}
Run Code Online (Sandbox Code Playgroud)

实现使用:

public decimal GetPrice(decimal amount, int quantity)
{
    return amount * quantity; // easy!
}
Run Code Online (Sandbox Code Playgroud)

然后转到这两个项目.

[Test]
public void TwoItemsItems()
{
    Assert.AreEqual(10, GetPrice(5, 2));
}
Run Code Online (Sandbox Code Playgroud)

实现仍然通过测试,所以继续进行下一个测试.

3.始终注意重复并删除它.当所有测试通过并且您不再考虑任何测试时,您就完成了.

这并不能保证您将创建最有效的算法,但只要您知道要测试的内容并且一切都通过,它将保证您获得正确的答案.

  • YAGNI会说在初始实现中会忽略数量 - 因为最简单的事情可能就是返回金额 - 然后第二次测试就会失败,推动GetPrice()的设计而不仅仅是确认它. (2认同)

Ste*_*owe 5

老派的OO方式:

  • 写下问题及其解决方案的描述
  • 圈出名词,这些是候选对象
  • 在动词周围绘制框,这些是候选消息
  • 将动词与可以"做"动作的名词分组; 列出需要帮助的任何其他名词
  • 看看你是否可以使用形式noun.verb(其他名词)重述解决方案
  • 编码吧

[这种方法先于CRC卡,但它已经很久了(超过20年),我不记得我在哪里学到了它]


J.J*_*.J. 3

我做了类似的事情。

  • 找出规则/逻辑。
  • 算出数学。
  • 然后尝试编码。

这样做几个月后,它就会内化。直到您遇到需要您分解的复杂问题时,您才会意识到自己正在这样做。