Picking good identifier names

前端 未结 10 1012
猫巷女王i
猫巷女王i 2020-12-17 19:23

Ok, so you can read guidelines on identifier naming \'til you\'re blue in the face... camel case, pascal case, make \'em descriptive... but they won\'t help you actually pic

10条回答
  •  余生分开走
    2020-12-17 19:53

    Clean Code is a good book but don't follow the advice on identifier names and comments. (See Self Describing Code and Long Identifiers Make Code Unreadable )

    For example, here is Uncle Bob's bowling example (see other replies for Uncle Bob's code) done properly:

    // Returns total score for a game of ten-pin bowling. On entry the number of fallen pins
    // for each ball is provided in fallen[] and the number of balls bowled is in balls_bowled.
    public int score()
    {
      int points = 0;                                            // Cumulative count of points for the game
      int ball = 0;                                               // Current shot or "ball" (1 or 2 per frame)
      int frame;                                                  // Current frame of the game
    
    
      for (frame = 0; frame < max_frames; ++frame)
      {
        if (fallen[ball] == 10)
        {
            // Strike (all pins knocked over from 1 ball) gives bonus of next two balls
            points += 10 + fallen[ball + 1] + fallen[ball + 2];
            ++ball;                                                 // Move to next frame (no 2nd ball)
        }
        else if (fallen[ball] + fallen[ball + 1] == 10)
        {
            // Spare (all pins knocked over in 2 balls) gives bonus of following ball
            assert(fallen[ball + 1] > 0);
            points += 10 + fallen[ball + 2];
            ball += 2;                                             // Move to first ball of next frame
        }
        else
        {
            // Open frame just gives score of all fallen pins of both frame's balls
            assert(fallen[ball] + fallen[ball + 1] < 10);
            points += fallen[ball] + fallen[ball + 1];
            ball += 2;                                             // Move to first shot of next frame
        }
      }
      assert(frame == max_frames && ball == balls_bowled);
      assert(points <= max_frames*30);                // Maximum possible score
      return points;
    }
    

提交回复
热议问题