25 Dòng Code Cho Mỗi Hàm Có Quá Ngắn? - Dạy Nhau Học

Em thấy code kernel có nhiều hàm hơn 25 dòng lắm anh ơi. Ví dụ như hàm đầu tiên của kernel start_kernel cũng 186 dòng tính cả blank line + comments. Bỏ hết blank line + comments đi chắc giảm được nhiều nhưng chắc chắn là hơn 25 dòng rồi.

torvalds/linux/blob/master/init/main.c#L502-L688

  1. #ifdef TRACEPOINTS_ENABLED
  2. static void __init initcall_debug_enable(void);
  3. #else
  4. static inline void initcall_debug_enable(void)
  5. {
  6. }
  7. #endif
  8. /*
  9. * Set up kernel memory allocators
  10. */
  11. static void __init mm_init(void)
  12. {
  13. /*
  14. * page_ext requires contiguous pages,
  15. * bigger than MAX_ORDER unless SPARSEMEM.
  16. */
  17. page_ext_init_flatmem();
  18. mem_init();
  19. kmem_cache_init();
This file has been truncated. show original

Theo “Code Complete 2nd” thì cỡ 200 dòng đổ lại là được.

Where does all this leave the question of routine length in object-oriented programs? A large percentage of routines in object-oriented programs will be accessor routines, which will be very short. From time to time, a complex algorithm will lead to a longer routine, and in those circumstances, the routine should be allowed to grow organically up to 100– 200 lines. (A line is a noncomment, nonblank line of source code.) Decades of evidence say that routines of such length are no more error prone than shorter routines. Let issues such as the routine’s cohesion, depth of nesting, number of variables, number of decision points, number of comments needed to explain the routine, and other complexity-related considerations dictate the length of the routine rather than imposing a length restriction per se. That said, if you want to write routines longer than about 200 lines, be careful. None of the studies that reported decreased cost, decreased error rates, or both with larger routines distinguished among sizes larger than 200 lines, and you’re bound to run into an upper limit of understandability as you pass 200 lines of code.

McConnell, Steve (2004-06-09). Code Complete (2nd Edition) (Developer Best Practices) (Kindle Locations 4487-4495). Pearson Education. Kindle Edition.

Từ khóa » Các Dòng Code Cơ Bản