Skip to content

اصول کد تمیز: نام‌گذاری، واحدهای کوچک، توابع خالص و اثرهای جانبی، DRY/YAGNI/KISS و حالت‌های شکست آن‌ها ​

"It is more important that code be easy to read than easy to write." — Google Go Style Guide, "Clarity" (google.github.io/styleguide/go/guide)

خلاصه (Summary): کد تمیز کدی است که فردی ناآشنا بتواند بدون ترس بخواند، تغییر دهد و تست کند: نام‌هایی که قصد را روشن می‌کنند، واحدهای کوچکی که در یک سطح انتزاع می‌مانند، تابع‌هایی که نتیجه‌شان فقط به آرگومان‌ها وابسته است، اثرهای جانبی در مرز سیستم، و حذف تکرار فقط وقتی که یک دانش تکرار شده، نه صرفاً یک شکل. تمرکز (Focus): قواعد روزمرهٔ نام‌گذاری، قالب‌بندی، تابع‌های کوچک و آرگومان‌ها را تا خلوص، جداسازی فرمان و پرس‌وجو، تکرارپذیری بی‌اثر، تغییرناپذیری، شرط‌های نگهبان، comment و کد مرده دنبال می‌کنیم. سپس DRY، WET، قاعدهٔ سه، YAGNI، KISS، قانون اردوگاه و ماژول‌های عمیق را با حالت شکستِ اجرای مکانیکی هر قاعده، ابزارهای Go و PHP/Laravel و آزمایشگاه تمیز کردن یک تابع قیمت‌گذاری در هر دو زبان می‌بینیم. هدف یادگیری (Learning goal): هر قاعده را به کار ببرید، هزینه‌اش را توضیح دهید، افراط در اجرای آن را تشخیص دهید؛ از ریزتابع‌های کم‌عمق تا انتزاع غلط و interfaceهای حدسی. بخش‌های مکانیکی را به CI بسپارید تا زمان بازبینی صرف طراحی شود، نه سبک نوشتن.

این صفحه مرجع کامل قواعد روزمرهٔ کدنویسی است. موضوع‌های همسایه را دوباره درس نمی‌دهد: کاتالوگ بوهای کد (Code smell) و حرکت‌های بازآرایی (Refactoring) در بوهای کد و Refactoring است؛ پنج اصل سطح کلاس در SOLID قرار دارد و مسئولیت واحد در سطح تابع، همتای کوچک SRP است. نظریهٔ وابستگی، انسجام و پنهان‌سازی اطلاعات در کیفیت طراحی، زنجیرهٔ پیام‌ها و قانون Demeter در ترکیب اشیا، و پارادایم‌هایی مثل برنامه‌نویسی تابعی در پارادایم‌های برنامه‌نویسی آمده‌اند. هرم تست، بدل‌های تست و TDD را در راهبرد تست و TDD، جزئیات مقدارهای خطای Go را در خطا، panic، recover و defer، lint و ساختار پروژهٔ Go را در چیدمان پروژه، Linting و Build، سازوکار تست Go را در تست و Benchmark، و جهت وابستگی در سطح معماری را در اصول Clean، Hexagonal و Component بخوانید.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
قواعد، حالت شکست و ابزار بررسی هر کدام در سه جدولهمه‌چیز در یک دقیقه
چرا خواندن کد باید ارزان باشد و کدام سه باور را کنار بگذاریمچرا کد تمیز وجود دارد
سهم Kelly Johnson، Meyer، Beck، Hunt و Thomas، Fowler، Martin، Ousterhout و Sonarاز کجا آمده
نام‌های گویا و قابل‌جست‌وجو، واژگان یکدست و قراردادهای Go و PHPنام‌گذاری
قالب‌بندی با gofmt، Laravel Pint، PSR-12، PER و قرارداد SQLقالب‌بندی
تابع کوچک، یک سطح انتزاع و مسئولیت واحد در سطح تابعتابع‌های کوچک
تعداد آرگومان‌ها و آرگومان‌های پرچمی، null و خروجیآرگومان‌ها
تابع خالص، اثر جانبی و شفافیت ارجاعیتابع‌های خالص
جداسازی فرمان و پرس‌وجو و تکرارپذیری بی‌اثرCQS و Idempotence
تغییرناپذیری و معنای مقداریتغییرناپذیری
هستهٔ تابعی و پوستهٔ دستوریهستهٔ تابعی
شرط نگهبان، بازگشت زودهنگام و exception در برابر مقدار خطامدیریت خطا و مسیر موفق
comment، کد خودتوضیح و کد مردهComment و کد مرده
DRY، WET و قاعدهٔ سه در حذف تکرارDRY
YAGNI، KISS، کلی‌سازی حدسی و انتزاع زودهنگامYAGNI و KISS
کمی تمیزتر رها کردن فایل با قانون اردوگاهقانون اردوگاه
framework در مرز، جهت وابستگی، انسجام و وابستگی بین ماژول‌هاFramework در مرز
ماژول عمیق در برابر کم‌عمق؛ نقد Ousterhout به Martinماژول‌های عمیق
پیچیدگی دوری و شناختی با gocyclo، gocognit و phpmdمعیارهای پیچیدگی
اصول FIRST، تست‌های سریع و مستقل و خوانایی تستتست‌های تمیز
Linter، formatter و تنظیم CI برای Go و PHPابزارها و سازوکار
سؤال‌های انسانی برای بازبینی کدچک‌لیست بازبینی
handler چاق، پارامتر boolean، helper همگانی و انتزاع غلطحل مسئله‌های کلاسیک
وقتی دو قاعده تعارض دارند کدام برنده استانتخاب
مسیر یک پردازه تا سرویس‌های متعدددر معماری
تمیز کردن تابع 52 خطی Go و controller در Laravel با تست و گام‌های کوچکآزمایشگاه
باورهای غلط، چکیده، پرسش‌های مصاحبه و همهٔ اصطلاح‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

قواعد در یک جدول. هر ردیف جلوتر باز می‌شود؛ ستون آخر نشان می‌دهد وقتی قاعده به تعصب تبدیل شود چه خراب می‌شود.

قاعدهبه زبان سادهمثال کوچکحالت شکست در اجرای افراطی
نام‌های گویای قصد (Intention-revealing names)نام بگوید چه و چرا، نه چگونهoverdueInvoices، نه list2نام آن‌قدر بلند می‌شود که منطق را می‌پوشاند؛ یا نامی به سبک Java مثل AbstractInvoiceProcessorFactoryImpl وارد Go می‌شود
تابع‌های کوچک (Small functions)هر تابع یک کار در یک سطح انجام دهدQuote، تابع‌های subtotalOf، tierDiscount و shippingFee را صدا می‌زندریزتابع‌های کم‌عمقی که باید با هم خوانده شوند؛ درهم‌تنیدگی
آرگومان‌های کم (Few arguments)فهرست کوتاه باشد و هر آرگومان ورودی واقعی باشدNewClient(cfg Config)ساختار Config به کیسه‌ای از پرچم‌های نامرتبط تبدیل می‌شود
تابع‌های خالص (Pure functions)آرگومان یکسان، نتیجهٔ یکسان، بدون تغییر دیگرPriceWithTax(net, percent)عبور دادن ساعت و logger از ده لایه
جداسازی فرمان و پرس‌وجو (Command-query separation)متد یا وضعیت را عوض کند یا جواب بدهدIncrement() و Value()شکستن Pop() پشته یا GetAndIncrement اتمیک، جایی که اتمیک بودن ضروری است
شرط‌های نگهبان (Guard clauses)بالا زود شکست را مشخص کن؛ مسیر موفق کنار حاشیه بماندif cancelled { return ErrCancelled }هشت return در تابع 15 خطی؛ فراموشی پاک‌سازی منابع؛ از defer استفاده کنید
Comment برای چراییکد بگوید چه؛ comment بگوید چرا و کجای کار غافلگیرکننده است// Spec: ISO 4217 minor unitsحذف همهٔ commentها و اجبار به مهندسی معکوس هر تصمیم
DRYهر دانش یک نمایش معتبر داشته باشدیک Cents.String()ادغام کدهای شبیه که به دلیل‌های مختلف عوض می‌شوند؛ انتزاع غلط
قاعدهٔ سه (Rule of three)دو نسخه را تحمل کن، در سومی استخراج کنسومین نسخهٔ قانون مالیاتده بار کپی کردن با این بهانه که «این فقط دومی است»
YAGNIچیزی را که هنوز لازم نیست نسازنبود interface به نام PaymentGateway برای یک درگاههیچ نقطهٔ تعویضی باقی نماند و تغییر لازم به بازنویسی تبدیل شود
KISSساده‌ترین راهی را انتخاب کن که کار می‌کندیک switch به جای registry افزونه‌هاساده را ساده‌لوحانه معنی کردن و نادیده گرفتن نیاز شناخته‌شده
قانون اردوگاه (Boy scout rule)فایل را کمی تمیزتر از قبل رها کنبهتر کردن نام یک متغیر هنگام رفع باگRefactor گذری که تغییر اصلی را در diff دفن می‌کند

عددهایی که باید به خاطر بسپارید. این عددها از ابزارها می‌آیند، نه توصیه‌های شفاهی؛ پیش‌فرض همان چیزی است که مستندات ابزار می‌گوید.

ابزارچه چیزی را می‌شماردآستانه یا سطح پیش‌فرض
gocyclo و gocyclo در golangci-lintپیچیدگی دوری (Cyclomatic complexity): مقدار پایهٔ 1 به اضافهٔ هر if، for، case و هر && یا عملگر orgolangci-lint پیش‌فرض از 30 گزارش می‌کند و 10 تا 20 را پیشنهاد می‌دهد
gocognit و gocognit در golangci-lintپیچیدگی شناختی (Cognitive complexity): شکست جریان خطی با جریمهٔ تودرتوییپیش‌فرض 30، پیشنهاد 10 تا 20
funlenطول تابع60 خط و 40 دستور
nestifپیچیدگی دستورهای if تودرتو5
PHPStanنوع‌ها و باگ‌ها در سطح‌های تجمعی11 سطح، از 0 آسان‌ترین تا 10 سخت‌گیرترین؛ پیش‌فرض 0
Psalmنوع‌ها و باگ‌ها در سطح‌های خطااز 1 سخت‌گیرترین تا 8 آسان‌ترین؛ پیش‌فرض 2
PHPMDقواعد اندازه و پیچیدگیCyclomaticComplexity از 10، ExcessiveParameterList از 10 و NPathComplexity از 200 گزارش می‌کنند

هر کار با کدام ابزار است.

کارGoPHP و Laravel
قالب‌بندی (Formatting)gofmt؛ همچنین goimports و gofumpt برای قالب‌بندی سخت‌گیرانه‌ترLaravel Pint با presetِ laravel و نیز psr12، per، symfony، empty؛ PSR-12 و PER Coding Style
بازبینی سبک و نام‌گذاریEffective Go، Go Code Review Comments، Google Go Style Guide، revivePSR-12، PER، قراردادهای Laravel و inspectionهای PHPStorm
باگ و نوعgo vet، staticcheck، کامپایلرPHPStan، Psalm
پیچیدگی و اندازهgocyclo، gocognit، funlen، nestif از طریق golangci-lintPHPMD با CyclomaticComplexity، NPathComplexity و ExcessiveParameterList
تکرار و کد مردهdupl، unused، unparamبررسی کد مردهٔ PHPStan در سطح‌های بالاتر
تستgo test -race، تست‌های جدولیPHPUnit، تست‌های HTTP در Laravel

چرا کد تمیز وجود دارد ​

کد بسیار بیشتر از آنکه نوشته شود خوانده می‌شود. بیشتر این خواندن‌ها هم وقتی است که چیزی خراب شده است. همهٔ قواعد این صفحه هزینهٔ همین خواندن را کم می‌کنند: نامی که پیش از مطرح شدن سؤال جوابش را می‌دهد، تابعی که می‌توان در ذهن نگه داشت، و نتیجه‌ای که بدون اجرای برنامه می‌توان پیش‌بینی کرد.

بدون این انضباطبا این انضباط
برای تغییر، همان فردی که هنوز کد را یادش هست باید راهنمایی کندتازه‌وارد با جست‌وجوی یک نام جای درست را پیدا می‌کند
رفع باگ شش نسخه را تغییر می‌دهد و یکی جا می‌ماندقاعده در یک جا زندگی می‌کند
هر تست دیتابیس، ساعت و سرور ایمیل لازم داردقواعد خالص‌اند و با مقدارهای ساده تست می‌شوند
نظرهای بازبینی دربارهٔ آکولاد و فاصله استنظرهای بازبینی دربارهٔ رفتار و طراحی است
«رفع سریع» یک آرگومان پرچمی و یک شاخه اضافه می‌کندشاخه نام، تست و جای مشخص دارد

تصویر روزمره: آشپزخانه. در آشپزخانهٔ حرفه‌ای آشپز تازه نمک را بدون سؤال پیدا می‌کند. مواد برچسب دارند؛ این همان نام‌گذاری است. هر ایستگاه یک کار می‌کند؛ همان واحد کوچک. کارت دستور از مواد یکسان غذای یکسان می‌دهد؛ همان تابع خالص (Pure function). فقط محل تحویل غذا با سالن حرف می‌زند؛ اثر جانبی (Side effect) در مرز است. کسی هم از یک ادویه سه شیشه با سه برچسب در سه جا نگه نمی‌دارد؛ این DRY است. اما آشپزخانه‌ای را تصور کنید که پوستر «هیچ‌وقت دو شیشه از هیچ چیز نداشته باشید» نصب کرده و آشپز برای «حذف تکرار» نمک و شکر را در یک شیشه می‌ریزد. این تصویر حالت شکست کل این فصل است.

سه بدفهمی رایج، از همان ابتدا ​

  1. «کد تمیز یعنی کد کوتاه.» تمیز یعنی خواندن و تغییر دادنش ارزان باشد. تابع 40 خطی که یک کار را خطی انجام می‌دهد از ده تابع 4 خطی که باید به ترتیب خاصی بخوانید تمیزتر است.
  2. «این قواعد قانون قطعی‌اند.» این‌ها راهنمای تجربی با حالت شکست‌اند و نویسندگان هم اختلاف دارند. Clean Code از Robert C. Martin و A Philosophy of Software Design از John Ousterhout دربارهٔ طول متد و comment توصیه‌های مخالف می‌دهند. بخش انتخاب اختلاف و روش تصمیم‌گیری را توضیح می‌دهد.
  3. «Formatter و linter کد را تمیز می‌کنند.» این دو یک دستهٔ کامل از بحث‌ها، یعنی سبک، را حذف می‌کنند و چند بو را می‌گیرند. تشخیص نمی‌دهند که نامی گمراه‌کننده یا انتزاعی غلط است.

از کجا آمده ​

text
     Year   Who / what                                              What it gave us
1    1938   "Keep it Short and Simple" attested (Minneapolis Star)  early form of KISS (Wikipedia, secondary)
2    1960   Kelly Johnson, Lockheed Skunk Works; U.S. Navy          "KISS": simplicity as a design goal
3    1988   Bertrand Meyer, Object-Oriented Software Construction   command-query separation (CQS)
4    1999   Hunt and Thomas, The Pragmatic Programmer               DRY: single authoritative representation of knowledge
5    1999   Fowler (with Beck), Refactoring                         rule of three, "Three strikes and you refactor"
6    ~2000  Extreme Programming (Beck, Jeffries, Hendrickson)       YAGNI; the four rules of simple design
7    2008   Robert C. Martin, Clean Code                            naming, small functions, comments (positions as quoted by Ousterhout)
8    Go     gofmt, Effective Go, Go Code Review Comments            the formatter and naming conventions as language culture
9    2018   John Ousterhout, A Philosophy of Software Design        deep modules; the strongest published counter-argument to Clean Code
10   2023   SonarSource white paper v1.7 on Cognitive Complexity     a metric for understandability rather than testability

ردیف‌های 1 و 2 از صفحهٔ KISS در Wikipedia، یعنی منبع ثانویه، آمده‌اند؛ ردیف 10 تاریخ چاپ‌شده روی مقاله است. سال‌های ردیف‌های 3 تا 7 و 9 سال انتشار رایج در ارجاع‌ها هستند و روی صفحهٔ ذخیره‌شده بررسی نشده‌اند؛ هیچ ادعای بعدی به آن‌ها وابسته نیست.

آنچه هر منبع واقعاً در صفحه‌های ذخیره‌شده برای این فصل می‌گوید:

  • چهار قاعدهٔ طراحی سادهٔ Kent Beck به روایت Martin Fowler: "Passes the tests", "Reveals intention", "No duplication", "Fewest elements". Fowler اضافه می‌کند: "The rules are in priority order, so 'passes the tests' takes priority over 'reveals intention'". ریشهٔ بیشتر بحث‌های این صفحه همین قواعد است؛ ترتیبشان هم جواب بسیاری از تعارض‌های بعدی است.
  • جداسازی فرمان و پرس‌وجو (Command-query separation). Fowler: "Queries: Return a result and do not change the observable state of the system (are free of side effects). Commands: Change the state of a system but do not return a value." او این اصل را به Bertrand Meyer نسبت می‌دهد.
  • YAGNI. Fowler: "It's a statement that some capability we presume our software needs in the future should not be built now because 'you aren't gonna need it'." عبارت از گفت‌وگوی Kent Beck و Chet Hendrickson در پروژهٔ C3 آمده است.
  • DRY. صورت نقل‌شده در Wikipedia، منبع ثانویه: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system"؛ Andy Hunt و Dave Thomas آن را در The Pragmatic Programmer بیان کرده‌اند. روی knowledge دقت کنید؛ نگفته است هر خط کد.
  • قاعدهٔ سه (Rule of three). Wikipedia، منبع ثانویه: "two instances of similar code do not require refactoring, but when similar code is used three times, it should be extracted". Fowler در Refactoring آن را مشهور کرد و به Don Roberts نسبت داده می‌شود.
  • منابع سبک خود Go. Effective Go، صفحهٔ ویکی Go Code Review Comments و Google Go Style Guide با بخش‌های Guide، Decisions و Best practices سه سندی هستند که تیم‌های Go در بازبینی به آن‌ها استناد می‌کنند. Go proverbs هم می‌گوید: "Clear is better than clever." و "A little copying is better than a little dependency."
  • منابع سبک PHP. PSR-12 راهنمای توسعه‌یافتهٔ سبک کدنویسی است. جانشین آن PER Coding Style دربارهٔ خودش می‌گوید: "extends, expands and replaces PSR-12". مستندات Laravel، Pint را "an opinionated PHP code style fixer for minimalists" معرفی می‌کند که روی PHP CS Fixer ساخته شده است.
  • Ousterhout در برابر Martin. در گفت‌وگوی منتشرشدهٔ آن‌ها در github.com/johnousterhout/aposd-vs-clean-code، Ousterhout دربارهٔ Clean Code می‌نویسد: "advice on method length is so extreme that it encourages programmers to create teeny-tiny methods that suffer from both shallow interfaces and entanglement". بخش ماژول‌های عمیق به آن برمی‌گردد.
  • پیچیدگی شناختی (Cognitive Complexity). مقالهٔ SonarSource، نسخهٔ 1.7، مورخ ۲۹ اوت ۲۰۲۳، از "a new metric" برای جبران کاستی‌های پیچیدگی دوری حرف می‌زند تا "produce a measurement that more accurately reflects the relative difficulty of understanding, and therefore of maintaining methods, classes, and applications".

مطالعهٔ مستقیم کتاب‌ها انجام نشده است. خود Clean Code منتشرشده در ۲۰۰۸، The Pragmatic Programmer و A Philosophy of Software Design کتاب‌اند. نقل‌قول آن‌ها در این صفحه فقط از صفحه‌های دریافت‌شده است: blikiِ Fowler، Wikipedia، سایت خود Ousterhout و گفت‌وگوی بالا. شمارهٔ فصل و صفحه در ادامه از همان نقل‌های ثانویه آمده یا حذف شده است.

کاتالوگ مفاهیم ​

هر قاعده یک بلوک دارد. ترتیب مثل خواندن diff در بازبینی است: اول نام و چیدمان، بعد شکل تابع و آرگومان‌ها، سپس رفتار شامل خلوص، وضعیت و خطا، بعد تکرار و حدس دربارهٔ آینده، و در پایان سطح ماژول و تست. قطعه‌های Go و PHP این بلوک‌ها همگی در آزمایشگاه هستند؛ کد Go آن کامپایل و تست می‌شود.

نام‌گذاری: نام گویا، قابل‌جست‌وجو و واژگان یکدست حیاتی ​

به زبان ساده: نام خوب جواب می‌دهد «این چیست و چرا وجود دارد؟» تا خواننده برای فهمیدن پاسخ مجبور نشود بدنه را باز کند.

بدفهمی رایج: «نام بلندتر همیشه روشن‌تر است.» Go Code Review Comments برای محدوده‌های کوچک برعکس می‌گوید: "Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex." قاعده‌ای که این دو را جمع می‌کند این است: "the further from its declaration that a name is used, the more descriptive the name must be."

تعریف: سه ویژگی مستقل که اغلب با هم اشتباه گرفته می‌شوند.

ویژگیمعنیمحک
نام گویای قصد (Intention-revealing names)نام هدف را بیان می‌کند، نه سازوکار یا نوع رامی‌توانید comment بالای آن را حذف کنید؟
نام قابل‌جست‌وجو (Searchable names)نام به‌اندازه‌ای متمایز است که با grep یا جست‌وجوی IDE پیدا شودجست‌وجوی 5000 قانون ارسال را پیدا می‌کند یا freeShippingThreshold؟
واژگان یکدست (Consistent vocabulary)در کل کد برای هر مفهوم یک واژه داریمبرای یک چیز در چهار فایل fetch، get، load و retrieve نوشته‌اید؟

روند یک نام بد؛ متن ticket می‌گوید «ارسال رایگان از 50»:

text
     Step  Who         What happens
1    Mon   Dev A       writes `if t < 5000 { s = 700 }` (t = total in cents, s = shipping)
2    Tue   Dev B       grep "shipping" finds nothing: the word is not in the file
3    Wed   Dev B       adds a second rule with a hard-coded 5000 in the invoice code
4    Thu   Support     "free shipping" differs between cart and invoice; ticket reopened
5    Fri   Dev C       spends the day proving the two numbers are the same fact

سناریوهای واقعی: ستون status که پنج گردش‌کار مختلف را نگه می‌دارد؛ کلاس Manager، Helper یا Utils که هرچه کسی نتوانسته نام‌گذاری کند در آن ریخته؛ نام پارامترهای data، info و item؛ نفی دوگانهٔ isNotDisabled؛ و userList که در واقع map است.

قراردادهای Go؛ همه از Effective Go و Go Code Review Comments که در pipeline/sources/clean-code-principles/ ذخیره شده‌اند:

موضوعقاعدهمثال
نام چندکلمه‌ای"the convention in Go is to use MixedCaps or mixedCaps rather than underscores"orderTotal، OrderTotal، نه order_total
Getter"it's neither idiomatic nor necessary to put Get into the getter's name"؛ فیلد owner، getter به نام Owner و setter به نام SetOwner داردobj.Owner()، نه obj.GetOwner()
نام package"short, concise, evocative"؛ حروف کوچک، یک کلمه، بدون underscorebytes، http، نه byte_utils
نام package و نماد کنار همنام package همیشه دیده می‌شود؛ تکرارش نکنید. راهنمای Google می‌گوید packageای که یک type هم‌نام خودش export می‌کند برای سازنده از New استفاده کندledger.New، نه ledger.NewLedger
گیرنده (Receiver)یک یا دو حرف برگرفته از نام type؛ هرگز me، this یا selffunc (c *Client) Do()
Interface تک‌متدینام متد با پسوند -erReader، Notifier
سرواژه (Initialism)بزرگی و کوچکی حروف را یکدست نگه دارید: ID، URL، HTTPuserID، نه userId

قراردادهای PHP و Laravel از PSR-1، PSR-12 و مستندات Laravel: کلاس‌ها با StudlyCaps؛ PSR-12 می‌گوید اصطلاح PSR-1 را PascalCase بخوانید. متدها با camelCase، ثابت‌ها با حروف بزرگ و underscore، caseهای enum با PascalCase مثل Tier::Gold آزمایشگاه؛ طبق قرارداد Eloquent نام جدول‌ها جمع و snake_case و نام مدل‌ها مفرد است.

واژگان یکدست در عمل:

go
// Three words for one idea, in three packages: the reader must learn all three.
func (s *Store) Fetch(id string) (Order, error)       { /* ... */ }
func (r *Repo) Get(id string) (Order, error)          { /* ... */ }
func (c *Cache) Retrieve(id string) (Order, error)    { /* ... */ }

// One word, chosen once and written in a short glossary in the package doc.
func (s *Store) Order(id string) (Order, error)       { /* ... */ }
func (r *Repo) Order(id string) (Order, error)        { /* ... */ }
func (c *Cache) Order(id string) (Order, error)       { /* ... */ }
php
// Before: what is $d, what is 7, what is "p"?
$d = Order::where('s', 'p')->where('c', '<', now()->subDays(7))->get();

// After: the query names the business concept; the number has one name and one home.
$staleUnpaidOrders = Order::query()->unpaid()->olderThan(self::UNPAID_GRACE_DAYS)->get();

Linter چه چیزی را می‌فهمد و چه چیزی را نه. revive در golangci-lint جایگزین قابل‌تنظیم golint است؛ PHPStorm و PHPStan می‌توانند نام ناشناخته را گزارش کنند، نه نام بد را. هیچ ابزاری نام گمراه‌کننده را تشخیص نمی‌دهد. این کار بازبین و اولین مورد چک‌لیست بازبینی کد است.

قالب‌بندی: gofmt، Laravel Pint و PSR-12 حیاتی ​

به زبان ساده: قالب‌بندی (Formatting) مسئله‌ای حل‌شده است: استاندارد را انتخاب کنید، ابزار را اجرا کنید و دیگر درباره‌اش بحث نکنید.

بدفهمی رایج: «Formatting فقط ظاهرسازی است.» این بخش از خوانایی را ماشین می‌تواند تضمین کند. وبلاگ Go مزیت‌های gofmt را این‌طور می‌گوید: نوشتن آسان‌تر، "never worry about minor formatting concerns"؛ خواندن آسان‌تر، "when all code looks the same you need not mentally convert others' formatting style"؛ نگه‌داری آسان‌تر، "diffs show only the real changes"؛ و حذف مجادله، "uncontroversial: never have a debate about spacing or brace position ever again!".

تعریف و ابزارها:

اکوسیستمابزارکار آنفرمان
Gogofmtبازنویسی منبع به یک چیدمان استاندارد؛ -l فهرست فایل‌های متفاوت، -d نمایش diff، -w بازنویسی، -s ساده‌سازی؛ []T{T{}, T{}} به []T{{}, {}} تبدیل می‌شودgofmt -l . باید هیچ خروجی ندهد
Gogoimports، gofumptFormatterهای سخت‌گیرتر؛ golangci-lint v2 آن‌ها را زیر formatters: اجرا می‌کندgolangci-lint fmt
PHPPSR-12سبک توسعه‌یافته: 4 فاصله، پایان خط LF، حد نرم طول خط 120 و بدون حد سخت؛ "The soft limit on line length MUST be 120 characters"قاعده است، ابزار نیست
PHPPER Coding Styleجانشین در حال تکامل؛ متنش می‌گوید "extends, expands and replaces PSR-12"قاعده است، ابزار نیست
LaravelLaravel Pint"an opinionated PHP code style fixer for minimalists"، ساخته‌شده روی PHP CS Fixer و نصب‌شده همراه اپ‌های تازهٔ Laravel؛ presetها: laravel پیش‌فرض، per، psr12، symfony، emptyدر CI، ./vendor/bin/pint --test و محلی ./vendor/bin/pint
SQLابزار استانداردی نداردقرارداد تیم که پایین آمدهبازبینی

روند بحثی دربارهٔ سبک که اصلاً رخ نمی‌دهد:

text
     Step  Where           What happens
1    editor    on save     gofmt / Pint rewrites the file
2    pre-commit hook       gofmt -l . and pint --test fail the commit if a file differs
3    CI                    the same two commands fail the build
4    review                nobody comments on spacing; the diff shows only real changes

تنظیم Pint در pint.json ریشهٔ پروژه؛ پیش‌فرض به فایل نیاز ندارد:

json
{
    "preset": "laravel"
}

قالب‌بندی SQL ابزار استانداردی مثل gofmt ندارد، پس قرارداد را بنویسید: کلیدواژه‌ها با حروف بزرگ، هر clause در یک خط، alias معنادار، join با ON صریح، و comment برای قاعده‌ای که واضح نیست:

sql
-- Hard to read and hard to diff: one line, aliases a/b/c, implicit join.
select a.id,sum(b.q*b.p) t from orders a,order_items b where a.id=b.order_id and a.status='paid' and a.created_at>now()-interval '30 days' group by a.id having sum(b.q*b.p)>5000;

-- Clean: one clause per line, names that say what they are, the rule is visible.
SELECT o.id                          AS order_id,
       SUM(i.quantity * i.unit_price) AS subtotal_cents
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.id
WHERE o.status = 'paid'
  AND o.created_at > now() - INTERVAL '30 days'
GROUP BY o.id
HAVING SUM(i.quantity * i.unit_price) > 5000;  -- 5000 cents: the free-shipping threshold

Formatting چه چیزی را تعیین نمی‌کند: شکستن خط داخل فراخوانی، نام‌گذاری و چیدمان فایل‌ها. مثلاً راهنمای Go دربارهٔ فهرست بلند آرگومان‌ها تصمیم را به قضاوت واگذار می‌کند و option struct را بر خط‌های بسیار بلند ترجیح می‌دهد. Formatter سبک را یکدست می‌کند؛ خوب بودن آن را تضمین نمی‌کند.

تابع‌های کوچک: یک سطح انتزاع و مسئولیت واحد در سطح تابع حیاتی ​

به زبان ساده: تابع باید مثل یک بند متن در یک ارتفاع مفهومی خوانده شود: یا گام‌های قاعدهٔ کسب‌وکار را شرح می‌دهد یا با بایت‌ها کار می‌کند؛ نه هر دو با هم.

بدفهمی رایج: «تابع حداکثر باید N خط باشد.» Fowler در bliki می‌گوید: "The argument that makes most sense to me, however, is the separation between intention and implementation. If you have to spend effort into looking at a fragment of code to figure out what it's doing, then you should extract it into a function and name the function after that 'what'." طول نشانهٔ بو است، نه خود قاعده. خود Fowler هم می‌گوید "Any function more than half-a-dozen lines of code starts to smell to me" و هم "size isn't important".

تعریف: سه ایده که معمولاً با هم آموزش داده می‌شوند.

ایدهمعنیمحک
تابع کوچک (Small function)آن‌قدر کوتاه که در ذهن جا شودبدون «و» می‌توانید نامش را بگویید؟
یک سطح انتزاع (One level of abstraction)همهٔ دستورهای تابع در یک ارتفاع مفهومی باشندخطی دربارهٔ مالیات کنار خطی دربارهٔ strings.Builder نشسته؟
مسئولیت واحد در سطح تابع (Single responsibility at function level)یک دلیل برای تغییر؛ همتای کوچک SRPاگر قانون مالیات و متن ایمیل عوض شوند، همان تابع را ویرایش می‌کنید؟

قبل و بعد از آزمایشگاه. بدنهٔ تابع «قبل» اعتبارسنجی، سه قاعدهٔ قیمت‌گذاری، ارسال، مالیات، خواندن ساعت و اعلان را مخلوط کرده است؛ نام‌ها تک‌حرفی‌اند و یک pointer محل نوشتن خروجی است:

go
package before

import (
	"errors"
	"time"
)

// Notify is a package-level hook that tests and callers patch: hidden global state.
var Notify func(to, msg string)

// Item is one order line. P is the unit price in cents, Q the quantity.
type Item struct{ P, Q int }

// Proc computes the order total.
// d is the discount kind, f turns on express shipping, c is a coupon code,
// exp is when the coupon stops working and res receives the total in cents.
func Proc(it []Item, d string, f bool, c string, exp time.Time, res *int) error {
	// check the list
	if len(it) == 0 {
		return errors.New("empty")
	}
	// add up
	t := 0
	for _, i := range it {
		if i.Q > 0 {
			if i.P >= 0 {
				t += i.P * i.Q
			} else {
				return errors.New("bad price")
			}
		} else {
			return errors.New("bad qty")
		}
	}
	x := 0
	if d == "gold" {
		x = t * 10 / 100
	} else if d == "silver" {
		x = t * 5 / 100
	}
	y := 0
	if c == "WELCOME" {
		if time.Now().Before(exp) {
			if t >= 2000 {
				y = 500
			}
		}
	}
	n := t - x - y
	s := 0
	if d != "gold" {
		if t < 5000 {
			s = 700
		}
	}
	if f {
		s += 1500
	}
	v := n * 20 / 100
	r := n + s + v
	if r > 50000 {
		if Notify != nil {
			Notify("ops", "big order")
		}
	}
	*res = r
	return nil
}

متد «بعد» مثل همان قاعده‌ای خوانده می‌شود که پیاده می‌کند. هر گام تابعی نام‌دار در همان فایل است و ساعت به‌صورت آرگومان می‌آید:

go
// Package after is the clean version of before: a pure core (Quote) that
// takes everything it needs as arguments and returns everything it computes.
package after

import (
	"errors"
	"time"
)

// Business rules live in named constants: one place per fact.
const (
	goldDiscountPercent   = 10
	silverDiscountPercent = 5
	taxPercent            = 20

	welcomeCouponCode    = "WELCOME"
	welcomeCouponOff     = Cents(500)
	welcomeCouponMinimum = Cents(2000)

	standardShipping      = Cents(700)
	freeShippingThreshold = Cents(5000)
	expressSurcharge      = Cents(1500)

	// LargeOrderThreshold is the total above which operations is told.
	LargeOrderThreshold = Cents(50000)
)

var (
	ErrNoItems     = errors.New("order has no items")
	ErrBadQuantity = errors.New("quantity must be positive")
	ErrBadPrice    = errors.New("unit price must not be negative")
)

type Tier string

const (
	TierStandard Tier = ""
	TierSilver   Tier = "silver"
	TierGold     Tier = "gold"
)

type Speed int

const (
	SpeedStandard Speed = iota
	SpeedExpress
)

type LineItem struct {
	UnitPrice Cents
	Quantity  int
}

// Coupon's zero value means "no coupon": callers never pass nil.
type Coupon struct {
	Code      string
	ExpiresAt time.Time
}

type Order struct {
	Items  []LineItem
	Tier   Tier
	Speed  Speed
	Coupon Coupon
}

type Quote struct {
	Subtotal, Discount, Shipping, Tax, Total Cents
}

// Quote prices an order. It is pure: the clock arrives as an argument, nothing
// global is read or written, and the same arguments always give the same result.
func (o Order) Quote(now time.Time) (Quote, error) {
	subtotal, err := subtotalOf(o.Items)
	if err != nil {
		return Quote{}, err
	}
	discount := tierDiscount(o.Tier, subtotal) + couponDiscount(o.Coupon, subtotal, now)
	net := subtotal - discount
	shipping := shippingFee(o.Tier, o.Speed, subtotal)
	tax := net * taxPercent / 100
	return Quote{
		Subtotal: subtotal,
		Discount: discount,
		Shipping: shipping,
		Tax:      tax,
		Total:    net + shipping + tax,
	}, nil
}

func subtotalOf(items []LineItem) (Cents, error) {
	if len(items) == 0 {
		return 0, ErrNoItems
	}
	var sum Cents
	for _, it := range items {
		if it.Quantity <= 0 {
			return 0, ErrBadQuantity
		}
		if it.UnitPrice < 0 {
			return 0, ErrBadPrice
		}
		sum += it.UnitPrice * Cents(it.Quantity)
	}
	return sum, nil
}

func tierDiscount(tier Tier, subtotal Cents) Cents {
	switch tier {
	case TierGold:
		return subtotal * goldDiscountPercent / 100
	case TierSilver:
		return subtotal * silverDiscountPercent / 100
	default:
		return 0
	}
}

func couponDiscount(c Coupon, subtotal Cents, now time.Time) Cents {
	if c.Code != welcomeCouponCode {
		return 0
	}
	if !now.Before(c.ExpiresAt) {
		return 0
	}
	if subtotal < welcomeCouponMinimum {
		return 0
	}
	return welcomeCouponOff
}

func shippingFee(tier Tier, speed Speed, subtotal Cents) Cents {
	var fee Cents
	if tier != TierGold && subtotal < freeShippingThreshold {
		fee = standardShipping
	}
	if speed == SpeedExpress {
		fee += expressSurcharge
	}
	return fee
}

سناریوهای واقعی: یک main سیصدخطی که flagها را parse می‌کند، فایل می‌خواند، تبدیلش می‌کند و گزارش می‌نویسد؛ controller لاراول با متد store() شامل اعتبارسنجی، قیمت‌گذاری، DB::transaction، ایمیل و پاسخ JSON؛ handlerِ HTTP در Go که decode، اعتبارسنجی، query، قالب‌بندی و log را در یک بدنه انجام می‌دهد.

کی تابع بلند اشکالی ندارد: یک main خطی که فقط وابستگی‌ها را متصل می‌کند، یک switch که جدول lookup است، parser تولیدشده و تست جدولی با caseهای فراوان. funlen با پیش‌فرض 60 خط و 40 دستور باز هم آن‌ها را گزارش می‌کند. اینجا linter برای تست و اتصال وابستگی‌ها استثنا لازم دارد، نه refactor.

استخراج امن: شرح حرکت‌های Extract Function، Replace Temp with Query و Decompose Conditional در بوهای کد و Refactoring است. حلقه همیشه همین است: تست توصیفی (Characterization test) را اضافه یا اجرا کنید، یک تابع بیرون بکشید، تست‌ها را اجرا کنید و commit کنید.

حالت شکست در ماژول‌های عمیق باز می‌شود: بیش از حد خرد کنید و ریزتابع‌های کم‌عمقی می‌سازید که باید با هم خوانده شوند.

آرگومان‌ها: تعداد، پرچمی، null و خروجی حیاتی ​

به زبان ساده: هر آرگومان چیزی است که فراخواننده باید بداند و درست بدهد. آرگومان‌های کمتر و روشن‌تر یعنی فراخوانی غلط کمتر.

بدفهمی رایج: «سه آرگومان سقف است.» عدد فقط یک نشانه است. مشکل، آرگومان‌های هم‌نوع کنار هم است، مثل host string, port int, useTLS bool, timeout time.Duration, retries int، که فراخواننده می‌تواند جابه‌جا بدهد و خطای کامپایل نگیرد؛ و booleanهایی که معنی‌شان در محل فراخوانی پیدا نیست، مثل Render(r, true).

تعریف: چهار مسئلهٔ مستقل، هر کدام با درمان خودش.

مسئلهشکل آنچرا آزار می‌دهددرمان
تعداد آرگومان‌ها (Arguments count)NewClient(host, port, tls, timeout, retries)جابه‌جا کردن آسان و توسعه دادن سخت استساختار گزینه‌ها (Option struct)؛ Google Go best practices: "An option structure is a struct type that collects some or all of the arguments"؛ یا functional options. در PHP آرگومان نام‌دار یا parameter object. PHPMD، ExcessiveParameterList را از 10 گزارش می‌کند
آرگومان پرچمی (Flag argument)Render(report, detailed bool)Fowler: "A flag argument is a kind of function argument that tells the function to carry out a different operation depending on its value" و "My general reaction to flag arguments is to avoid them"دو تابع با نام کاری که انجام می‌دهند
آرگومان تهی (Null argument)Send(msg, nil) برای نبود فهرست ccهر فراخوانده باید nil را بررسی کند؛ یک بررسی فراموش‌شده یعنی crashمقدار صفر معنادار، مثل Coupon{} برای نبود کوپن، type اختیاری یا دو overload؛ در PHP، nullable type فقط در مرز
آرگومان خروجی (Output argument)Parse(s, &out)خواننده باید حدس بزند کدام آرگومان نوشته می‌شودنتیجه و یک error را برگردانید

روند گسترش آرگومان پرچمی:

text
     Step  Change                                          Result
1    v1    Render(r Report) string                         one behaviour
2    v2    Render(r Report, detailed bool) string          two behaviours in one body
3    v3    Render(r Report, detailed, html bool) string    four combinations, two untested
4    v4    Render(r Report, detailed, html, csv bool)      "html and csv" is undefined

در Go و PHP. قطعهٔ زیر هر چهار درمان را نشان می‌دهد و تست‌ها برابری تابع‌های جدید و قدیمی را ثابت می‌کنند:

go
// Package args shows how to shrink an argument list: split flag arguments,
// return results instead of filling pointers, collect options in a struct and
// let the zero value mean "default" instead of passing nil.
package args

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

type Report struct {
	Title string
	Rows  []string
}

// RenderFlag is a flag argument: the boolean picks between two functions.
func RenderFlag(r Report, detailed bool) string {
	if detailed {
		return r.Title + "\n" + strings.Join(r.Rows, "\n")
	}
	return fmt.Sprintf("%s (%d rows)", r.Title, len(r.Rows))
}

// RenderSummary and RenderDetail say what they do at the call site.
func RenderSummary(r Report) string { return fmt.Sprintf("%s (%d rows)", r.Title, len(r.Rows)) }

func RenderDetail(r Report) string { return r.Title + "\n" + strings.Join(r.Rows, "\n") }

// ParseOut is an output argument: the reader must guess that out is written.
func ParseOut(s string, out *int) error {
	n, err := strconv.Atoi(strings.TrimSpace(s))
	if err != nil {
		return fmt.Errorf("parse %q: %w", s, err)
	}
	*out = n
	return nil
}

// Parse returns what it computes.
func Parse(s string) (int, error) {
	n, err := strconv.Atoi(strings.TrimSpace(s))
	if err != nil {
		return 0, fmt.Errorf("parse %q: %w", s, err)
	}
	return n, nil
}

// NewClientLong has five positional arguments of similar types: easy to swap.
func NewClientLong(host string, port int, useTLS bool, timeout time.Duration, retries int) Client {
	return Client{Host: host, Port: port, TLS: useTLS, Timeout: timeout, Retries: retries}
}

// Config is an option struct: fields are named at the call site and the zero
// value of each field means "use the default".
type Config struct {
	Host    string
	Port    int
	TLS     bool
	Timeout time.Duration
	Retries int
}

type Client struct {
	Host    string
	Port    int
	TLS     bool
	Timeout time.Duration
	Retries int
}

var ErrNoHost = errors.New("host is required")

func NewClient(cfg Config) (Client, error) {
	if cfg.Host == "" {
		return Client{}, ErrNoHost
	}
	if cfg.Port == 0 {
		cfg.Port = 443
	}
	if cfg.Timeout == 0 {
		cfg.Timeout = 5 * time.Second
	}
	return Client(cfg), nil
}
php
// Laravel: named arguments make a call site readable without a parameter object.
$client = new ApiClient(host: 'api.example.test', timeout: 5, retries: 3);

// A flag argument split in two:
$report->renderSummary();   // not $report->render(detailed: false)
$report->renderDetail();

// Null argument: the nullable type belongs at the edge (a request field),
// the domain object receives a real value.
$expiresAt = $request->date('coupon_expires_at') ?? new DateTimeImmutable('@0');

سناریوهای واقعی: http.Client به جای آرگومان سازنده فیلد Timeout دارد تا مقدار صفر کار کند؛ Mail::to($user)->send($mailable) در Laravel به جای تابع هشت‌آرگومانی زنجیره‌ای از گام‌های نام‌دار می‌دهد؛ در Go هم ctx context.Context در جایگاه اول همان آرگومان موقعیتی است که همه بر سرش توافق دارند.

چه چیزی جلویش را می‌گیرد: golangci-lint در مجموعهٔ پیش‌فرض یک linter واحد برای «آرگومان بیش از حد» ندارد. بازبین و راهنمای option structureهای Google این کار را می‌کنند و unparam آرگومان بی‌استفاده را حذف می‌کند. در PHP، بررسی مکانیکی بر عهدهٔ ExcessiveParameterList در PHPMD است.

تابع خالص، اثر جانبی و شفافیت ارجاعی حیاتی ​

به زبان ساده: تابع خالص (Pure function) ماشین‌حساب است: ورودی یکسان همیشه جواب یکسان می‌دهد و هنگام اجرا چیزی دیگر در جهان عوض نمی‌شود.

بدفهمی رایج: «تابعی که خروجی void ندارد خالص است.» تابعی که time.Now()، متغیر سراسری، متغیر محیطی یا ردیف دیتابیس را می‌خواند خالص نیست، حتی اگر مقداری برگرداند. تابعی که log می‌نویسد هم خالص نیست، حتی اگر منطقش خالص باشد. مسئله ورودی پنهان، مثل ساعت، globals و I/O، و خروجی پنهان، مثل تغییر داده، نوشتن و log است.

تعریف: Pure function مقداری برمی‌گرداند که فقط به آرگومان‌هایش وابسته است و اثر جانبی (Side effect) ندارد. Side effect هر تغییر مشاهده‌پذیر بیرون از مقدار بازگشتی تابع است: نوشتن فیلد، متغیر سراسری یا فایل، فراخوانی API، چاپ، خواندن ساعت و تولید عدد تصادفی. نتیجهٔ این ویژگی شفافیت ارجاعی (Referential transparency) است: می‌توان فراخوانی را با نتیجه‌اش جایگزین کرد و رفتار برنامه عوض نشود؛ پس PriceWithTax(100, 20) را هر جا می‌توان با 120 جایگزین کرد.

ورودی یا خروجی پنهانمثال ناخالصجایگزین خالص
ساعتtime.Now() داخل قاعدهآرگومان now time.Time
تصادفrand.Intn داخل قاعدهمقدار تولیدشده به‌صورت آرگومان؛ مولد با seed مشخص قطعی است، اما مصرف آن وضعیتش را عوض می‌کند، پس خالص نیست
متغیر سراسری یا packageخواندن TaxPercent داخل تابعآرگومان taxPercent یا فیلد یک مقدار
محیطos.Getenv در قاعدهیک بار در main بخوانید و مقدار را بدهید
تغییر آرگومانappend به slice متعلق به فراخوانندهمقدار تازه برگردانید
I/Oنوشتن فایل داخل محاسبهچیزی را که باید نوشته شود برگردانید؛ نوشتن با shell باشد
ثبت loglog.Printf داخل قاعدهواقعیت‌ها را برگردانید؛ در مرز log کنید

روند مقایسهٔ قاعدهٔ ناخالص و خالص:

text
     Step  Call                              Impure PriceWithTaxImpure(100)     Pure PriceWithTax(100, 20)
1    t0    TaxPercent = 20                   -                                  -
2    t1    price(100)                        120                                120
3    t2    other code sets TaxPercent = 0    -                                  -
4    t3    price(100)                        100  (same call, new answer)      120

سناریوهای واقعی: قانون تخفیف که time.Now() می‌خواند و برای Black Friday تست‌پذیر نیست؛ accessor مدل Laravel که now() صدا می‌زند و snapshot test را روز اول ماه خراب می‌کند؛ تابع گزارش که slice دریافتی را تغییر می‌دهد و دادهٔ فراخواننده را خراب می‌کند؛ تابع قیمت‌گذاری که feature flag را از دیتابیس می‌خواند.

Go و PHP:

go
// Package purity shows side effects, command-query separation, idempotence and
// immutability in the smallest examples that still compile and test.
package purity

import (
	"fmt"
	"time"
)

// TaxPercent is global state: any code can change it, so PriceWithTaxImpure
// does not return the same answer for the same argument.
var TaxPercent = 20

func PriceWithTaxImpure(net int) int { return net + net*TaxPercent/100 }

// PriceWithTax is pure: the output depends only on the arguments.
func PriceWithTax(net, taxPercent int) int { return net + net*taxPercent/100 }

// GreetingImpure reads the clock; a test cannot choose the answer.
func GreetingImpure() string { return Greeting(time.Now()) }

// Greeting is pure: the clock became an argument.
func Greeting(now time.Time) string {
	if now.Hour() < 12 {
		return "Good morning"
	}
	return "Good afternoon"
}

// Counter mixes a command and a query in Next: asking changes the answer.
type Counter struct{ n int }

func (c *Counter) Next() int { c.n++; return c.n }

// Tally separates them: Increment is a command (no result), Value a query (no change).
type Tally struct{ n int }

func (t *Tally) Increment() { t.n++ }
func (t Tally) Value() int  { return t.n }

// Order status updates: SetStatus is idempotent, Append is not.
type Order struct {
	Status string
	Notes  []string
}

// SetStatus can be retried safely: applying it twice equals applying it once.
func (o *Order) SetStatus(s string) { o.Status = s }

// AppendNote cannot: every retry adds another note.
func (o *Order) AppendNote(n string) { o.Notes = append(o.Notes, n) }

// AppendNoteOnce makes the operation idempotent with a caller-supplied key.
type Ledger struct {
	seen  map[string]bool
	Notes []string
}

func (l *Ledger) AppendNoteOnce(key, note string) bool {
	if l.seen[key] {
		return false
	}
	if l.seen == nil {
		l.seen = map[string]bool{}
	}
	l.seen[key] = true
	l.Notes = append(l.Notes, note)
	return true
}

// Cart is immutable: WithItem returns a new Cart and never touches the receiver.
type Cart struct{ items []string }

func (c Cart) WithItem(item string) Cart {
	next := make([]string, len(c.items), len(c.items)+1)
	copy(next, c.items)
	return Cart{items: append(next, item)}
}

func (c Cart) Items() []string { return append([]string(nil), c.items...) }

func (c Cart) String() string { return fmt.Sprintf("Cart%v", c.items) }
php
// Laravel: the pure rule takes the clock as an argument; the caller passes now().
final class TrialRule
{
    public function isExpired(DateTimeImmutable $startedAt, DateTimeImmutable $now): bool
    {
        return $now >= $startedAt->modify('+14 days');
    }
}
// controller or job: $rule->isExpired($user->trial_started_at->toImmutable(), now()->toImmutable())

خلوص چه می‌دهد: تست‌ها fake لازم ندارند؛ TestPureAnswerDependsOnArguments را ببینید. نتیجه را می‌توان امن cache یا memoise کرد، فراخوانی‌ها بدون قفل (Lock) موازی اجرا می‌شوند و منشأ باگ فقط آرگومان‌ها یا بدنه است. هزینه‌اش چیست: مقدارهای بیشتری را دست‌به‌دست می‌کنید. این برای قواعد هزینهٔ درستی است، برای logger نه؛ به همین دلیل هستهٔ تابعی و پوستهٔ دستوری مرز را در جای مشخصی می‌گذارد.

جداسازی فرمان و پرس‌وجو و تکرارپذیری بی‌اثر مهم ​

به زبان ساده: متد یا کاری انجام دهد یا چیزی بگوید، نه هر دو؛ عملیاتی هم که احتمال اجرای دوباره دارد باید برای تکرار امن باشد.

بدفهمی رایج: «CQS همان CQRS است.» جداسازی فرمان و پرس‌وجو (Command-query separation) قاعده‌ای در سطح متد از Bertrand Meyer است. CQRS الگوی معماری جدا کردن مدل خواندن از مدل نوشتن است؛ از همان ایده رشد کرده، اما تصمیم دیگری است. وجه معماری را در Event Sourcing و CQRS ببینید. Fowler استثنا هم دارد: بیرون آوردن عنصر از پشته هم مقدار برمی‌گرداند و هم state را تغییر می‌دهد؛ جدا کردن این دو، اتمیک بودن را از بین می‌برد.

تعریف: Fowler با نسبت دادن اصل به Meyer می‌گوید queryها "return a result and do not change the observable state of the system (are free of side effects)"؛ commandها "change the state of a system but do not return a value". فایده از زبان او: "you can use queries in many situations with much more confidence, introducing them anywhere, changing their order." تکرارپذیری بی‌اثر (Idempotence) ویژگی دیگری است: دو بار اعمال عملیات همان اثر یک بار را دارد. همین ویژگی retry را امن می‌کند.

عملیاتفرمان یا پرس‌وجوIdempotent است؟چرا
Tally.Value()Queryبله، و تکرارپذیرفقط می‌خواند
Tally.Increment()Commandنههر فراخوانی یکی اضافه می‌کند
Counter.Next()هر دو؛ نقض قاعدهنهسؤال پرسیدن جواب را عوض می‌کند
Order.SetStatus("paid")Commandبلهدو بار تنظیم یک مقدار وضعیت یکسانی می‌گذارد
Order.AppendNote(n)CommandنهRetry یادداشت دیگری اضافه می‌کند
Ledger.AppendNoteOnce(key, n)Commandبلهکلید، تکرار را به no-op تبدیل می‌کند
HTTP PUT و DELETECommandطبق معنای HTTP بله
HTTP POSTCommandنه، مگر از idempotency key استفاده شود

روند retry برای فرمانی که idempotent نیست:

text
     Step  Actor          Action                                  Stored notes
1    t0    client         POST /orders/7/notes  "paid by card"    ["paid by card"]
2    t1    network        response lost
3    t2    client         retries the same request                ["paid by card", "paid by card"]
4    t3    with key       retries with Idempotency-Key: evt-1     ["paid by card"]  (second call is a no-op)

سناریوهای واقعی: iterator در Go با Next() که هم جلو می‌رود و هم برمی‌گرداند؛ Fowler جداسازی advance و current را ترجیح می‌دهد. کلیدهای idempotency به سبک Stripe برای POST پرداخت؛ مصرف‌کنندهٔ صف که با تحویل at-least-once همان پیام را دوبار پردازش می‌کند؛ job لاراول که بعد از timeout دوباره اجرا می‌شود؛ و migration که اجرای دوباره‌اش باید امن باشد، مثل CREATE TABLE IF NOT EXISTS.

نمونهٔ Go در packageِ purity بالاست: Counter در برابر Tally، SetStatus در برابر AppendNote و Ledger کلیددار. وجه پیام‌رسانی را در مصرف‌کنندهٔ Idempotent و الگوی Inbox و وجه HTTP را در Idempotency در API بخوانید.

php
// Laravel: idempotent write with a unique key; the second insert is a no-op.
DB::table('processed_events')->insertOrIgnore(['event_id' => $event->id, 'processed_at' => now()]);

تغییرناپذیری و معنای مقداری مهم ​

به زبان ساده: مقداری که بعد از ساخته شدن نمی‌تواند عوض شود، پشت سر شما هم عوض نمی‌شود.

بدفهمی رایج: «در Go پاس دادن struct به‌صورت مقدار آن را immutable می‌کند.» header و فیلدهای struct کپی می‌شوند، اما فیلد slice یا map هنوز به حافظهٔ فراخواننده اشاره دارد. پس append یا نوشتن از طریق کپی می‌تواند اصل را تغییر دهد. تغییرناپذیری (Immutability) کپی محتوا می‌خواهد، همان کاری که Cart.WithItem با make و copy می‌کند؛ یا فیلد exportنشده‌ای که متد تغییردهنده ندارد.

تعریف: مقدار immutable هیچ عملیات تغییردهنده‌ای ندارد؛ «تغییر» مقدار تازه برمی‌گرداند. Go، final ندارد، پس Immutability قراردادی است که با فیلدهای exportنشده، value receiver و کپی دفاعی ساخته می‌شود. صفحهٔ انتشار PHP 8.2، "readonly classes" را فهرست می‌کند؛ PHP 8.2 امکانات final readonly class، مورد استفادهٔ Quote آزمایشگاه، و DateTimeImmutable را در اختیار می‌گذارد. مدل‌های Eloquent از ابتدا mutable طراحی شده‌اند؛ در مرز نگهشان دارید.

ویژگی زبانبه چه چیزی کمک می‌کندجلوی چه چیزی را نمی‌گیرد
ثابت‌ها و بلوک‌های const در Goمقدار ثابت و نام‌های شبیه enumهر چیزی که constant expression نیست
فیلد exportنشده همراه value receiver در Goدست‌کاری داخل توسط فراخوانندهslice و map مشترک از طریق reference
متد Items() در Go که کپی می‌دهدهم‌نامی حافظه (Aliasing)هزینهٔ کپی برای sliceهای عظیم
property و class با readonly در PHPانتساب دوباره یا مقداردهی property از بیرون، و تغییر غیرمستقیم آرایهٔ داخل آن؛ PHP خطای Cannot indirectly modify readonly property می‌دهد که روی نصب محلی PHP بررسی شده استتغییر object داخل آن؛ propertyهای خود آن object هنوز قابل‌نوشتن‌اند
DateTimeImmutable در PHPغافلگیری کلاسیک DateTime::modify

روند یک باگ Aliasing:

text
     Step  Code                                   items (caller)         items (callee copy)
1    t0    a := []int{1, 2, 3}                    [1 2 3]                -
2    t1    b := a            (slice header copy)  [1 2 3]                [1 2 3] same backing array
3    t2    b[0] = 99                              [99 2 3]  (surprise)   [99 2 3]
4    t3    b := append([]int(nil), a...)  (copy)  [99 2 3]               [99 2 3] independent from now on

سناریوهای واقعی: Cart که تابع قیمت‌گذاری تغییرش می‌دهد و بعد مبلغ غلط از آن دریافت می‌شود؛ DateTime در PHP که به متدی داده شده و متد با ->modify('+1 day') تاریخ فراخواننده را جلو می‌برد؛ map در Go که getter برمی‌گرداند و فراخواننده تغییرش می‌دهد. تست TestImmutableCart در packageِ purity رفتار کپی را ثابت می‌کند.

هستهٔ تابعی، پوستهٔ دستوری حیاتی ​

به زبان ساده: همهٔ تصمیم‌ها را در کد خالصی بگذارید که مقدار می‌گیرد و مقدار می‌دهد. کدی که با جهان، یعنی HTTP، دیتابیس، ساعت و ایمیل، تماس دارد دور آن بماند؛ نازک و بدون منطق تصمیم‌گیری.

بدفهمی رایج: «یعنی همه‌چیز را با زبان تابعی بنویسیم.» این فقط چیدمان کد معمولی است. screencastِ Gary Bernhardt که نام را معرفی کرد می‌گوید: "a Twitter client whose core is functional ... This functional core is surrounded by a shell of imperative code: it manipulates stdin, stdout, the database, and the network, all based on values produced by the functional core." Go و PHP با struct و تابع معمولی هم این کار را می‌کنند.

تعریف: هستهٔ تابعی (Functional core) مجموعهٔ تابع‌های خالص تصمیم‌گیر است؛ پوستهٔ دستوری (Imperative shell) ورودی را می‌خواند، core را صدا می‌زند و اثرهایی را که می‌خواهد اجرا می‌کند. Shell با چند fake یا تست یکپارچگی بررسی می‌شود؛ core را با مقدارهای ساده و پوشش کامل حالت‌ها تست می‌کنیم.

Imperative shell (I/O, clock, framework, mutation)Functional coreOrder.Quote(now)Plan(invoices, now)values in, values outno clock, no DB, no mailtests need no fakesHTTP requestDatabase readClock: time.Now()Save to databaseSend the mail1 read values at the edge 2 decide in the core 3 act on the decision

روند یک درخواست در این الگو؛ Service.PlaceQuote آزمایشگاه:

text
     Step  Layer     What happens                                         Needs a fake?
1    shell     read the request body and the clock                          no (edge)
2    shell     call Order.Quote(now)                                        -
3    core      validate, subtotal, discounts, shipping, tax                 no (pure)
4    shell     compare total with LargeOrderThreshold                       -
5    shell     call Notifier.LargeOrder(total) if above                     yes: one recording fake
6    shell     write the response                                           no (edge)

سناریوهای واقعی: job یادآوری فاکتور، یعنی packageِ core که در آن Plan تصمیم می‌گیرد و Run بارگذاری، ارسال و ثبت می‌کند؛ action class در Laravel که اعتبارسنجی را در Form Request انجام می‌دهد، QuoteCalculator خالص را فراخوانی می‌کند و بعد event می‌فرستد؛ CLI که فایل می‌خواند، Transform خالص را صدا می‌زند و خروجی را می‌نویسد.

go
// Package core is a functional core with an imperative shell: Plan decides,
// Run does. Plan is pure, so its tests need no fakes at all.
package core

import (
	"context"
	"fmt"
	"time"
)

type Invoice struct {
	ID       string
	DueDate  time.Time
	Paid     bool
	Reminded bool
}

type Reminder struct {
	InvoiceID string
	Overdue   int // whole days overdue
}

// Plan is the functional core: values in, values out, no clock, no I/O.
func Plan(invoices []Invoice, now time.Time) []Reminder {
	var out []Reminder
	for _, inv := range invoices {
		if inv.Paid || inv.Reminded || !now.After(inv.DueDate) {
			continue
		}
		days := int(now.Sub(inv.DueDate) / (24 * time.Hour))
		out = append(out, Reminder{InvoiceID: inv.ID, Overdue: days})
	}
	return out
}

// Store and Mailer are the edges the shell talks to.
type Store interface {
	Unpaid(ctx context.Context) ([]Invoice, error)
	MarkReminded(ctx context.Context, id string) error
}

type Mailer interface {
	Send(ctx context.Context, r Reminder) error
}

// Run is the imperative shell: load, decide with Plan, act, record.
func Run(ctx context.Context, s Store, m Mailer, now time.Time) (int, error) {
	invoices, err := s.Unpaid(ctx)
	if err != nil {
		return 0, fmt.Errorf("load unpaid invoices: %w", err)
	}
	sent := 0
	for _, r := range Plan(invoices, now) {
		if err := m.Send(ctx, r); err != nil {
			return sent, fmt.Errorf("send reminder for %s: %w", r.InvoiceID, err)
		}
		if err := s.MarkReminded(ctx, r.InvoiceID); err != nil {
			return sent, fmt.Errorf("mark %s reminded: %w", r.InvoiceID, err)
		}
		sent++
	}
	return sent, nil
}
go
package after

import "time"

// Notifier is the small interface the shell needs; the caller decides how.
type Notifier interface {
	LargeOrder(total Cents)
}

// Service is the imperative shell: it owns the clock and the side effect.
// Everything with a rule in it stays in Order.Quote.
type Service struct {
	Now      func() time.Time
	Notifier Notifier
}

func (s Service) PlaceQuote(o Order) (Quote, error) {
	q, err := o.Quote(s.Now())
	if err != nil {
		return Quote{}, err
	}
	if q.Total > LargeOrderThreshold {
		s.Notifier.LargeOrder(q.Total)
	}
	return q, nil
}
php
// Laravel: the controller is the shell, QuoteCalculator is the core (see the lab).
$quote = $calculator->quote(items: $items, tier: $tier, express: $express, now: now()->toImmutable(), /* ... */);
if ($quote->total > self::LARGE_ORDER_FROM) {
    LargeOrderQuoted::dispatch($quote->total);   // the side effect stays in the shell
}

حد این ایده. Core فقط وقتی خالص می‌ماند که همهٔ داده‌های لازم پیش از اجرای آن بارگذاری شده باشند. قاعده‌ای که وسط تصمیم باید دیتابیس را بپرسد، مثلاً «این ایمیل قبلاً گرفته شده؟»، یا مقدار ازپیش‌بارگذاری‌شده می‌خواهد، یا repository interface که core صدایش بزند و دیگر کاملاً خالص نباشد، یا constraint داخل دیتابیس. ارزان‌ترین گزینهٔ صادقانه را انتخاب کنید و نامش را روشن بگویید.

مدیریت خطا و مسیر موفق: شرط نگهبان، بازگشت زودهنگام، exception و مقدار خطا حیاتی ​

به زبان ساده: اول بالای تابع سراغ چیزهایی بروید که می‌توانند خراب شوند و برگردید؛ آنچه باقی می‌ماند کار اصلی است که مستقیم تا پایین خوانده می‌شود.

بدفهمی رایج: «یک return در هر تابع تمیزتر است.» قاعدهٔ تک‌خروجی از زبان‌های بدون امکانات پاک‌سازی مثل defer، finally و RAII می‌آید. در Go و PHP بازگشت زودهنگام روش معمول است. Effective Go: "The code reads well if the successful flow of control runs down the page, eliminating error cases as they arise." بخش Indent Error Flow در Go Code Review Comments: "Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first."

تعریف: شرط نگهبان (Guard clause) یک if ابتدایی است که وضعیت نامعتبر را رد می‌کند و برمی‌گردد یا exception می‌اندازد. بازگشت زودهنگام (Early return) نام تکنیک است. دو مدل خطا داریم:

مدلGoPHP و Laravel
مقدار خطا (Error value)تابع error می‌دهد؛ فراخواننده if err != nil را بررسی می‌کند؛ wrap با fmt.Errorf("...: %w", err) از Go 1.13، ترکیب با errors.Join از Go 1.20، تشخیص با errors.Is و errors.As؛ وبلاگ Go می‌گوید "Errors are values"، پس می‌توان روی آن‌ها برنامه نوشتکمتر رایج؛ در برخی دامنه‌ها برای result object استفاده می‌شود
استثنا (Exception)panic و recover وجود دارند، اما برای خطای برنامه‌نویس و کنترل جریان داخلی package هستند؛ Code Review Comments: "Do not discard errors using _ variables. If a function returns an error, check it"روش معمول است: exception دامنه را throw و در مرز catch کنید؛ handler لاراول آن را با render و report نمایش و گزارش می‌کند؛ Form Request خودش validation exception می‌اندازد

روند مقایسهٔ تودرتویی و guard؛ همان تابع Ship، در نمودار و قطعهٔ کد:

text
     Step  Nested                              Guarded
1    t0    if !cancelled {                     if cancelled { return ErrCancelled }
2    t1      if paid {                         if !paid { return ErrNotPaid }
3    t2        if items > 0 {                  if items <= 0 { return ErrEmpty }
4    t3          if !shipped {                 if shipped { return ErrShipped }
5    t4            ship()   // depth 4          ship()       // depth 0
Nested: success at the deepest levelif !cancelled {if paid {if items > 0 {if !shipped {ship() // the real work} else { return ErrShipped }} else { return ErrEmpty }} else { return ErrNotPaid }} else { return ErrCancelled }4 levels; each error is far from its checkGuard clauses: success runs down the pageif cancelled { return ErrCancelled }if !paid { return ErrNotPaid }if items <= 0 { return ErrEmpty }if shipped { return ErrShipped }ship() // the real workreturn nil1 level; the happy path stays at the margin
go
// Package guard compares nested conditionals with guard clauses and shows
// error values that callers can test with errors.Is.
package guard

import (
	"errors"
	"fmt"
)

type Order struct {
	ID        string
	Paid      bool
	Items     int
	Shipped   bool
	Cancelled bool
}

var (
	ErrCancelled = errors.New("order is cancelled")
	ErrNotPaid   = errors.New("order is not paid")
	ErrEmpty     = errors.New("order has no items")
	ErrShipped   = errors.New("order already shipped")
)

// ShipNested keeps the happy path at the deepest indentation.
func ShipNested(o *Order) error {
	if !o.Cancelled {
		if o.Paid {
			if o.Items > 0 {
				if !o.Shipped {
					o.Shipped = true
					return nil
				} else {
					return ErrShipped
				}
			} else {
				return ErrEmpty
			}
		} else {
			return ErrNotPaid
		}
	} else {
		return ErrCancelled
	}
}

// Ship handles each failure first and lets the success path run down the page.
func Ship(o *Order) error {
	if o.Cancelled {
		return ErrCancelled
	}
	if !o.Paid {
		return ErrNotPaid
	}
	if o.Items <= 0 {
		return ErrEmpty
	}
	if o.Shipped {
		return ErrShipped
	}
	o.Shipped = true
	return nil
}

// ShipAll wraps each failure with the order id; callers still match with errors.Is.
func ShipAll(orders []*Order) error {
	var errs []error
	for _, o := range orders {
		if err := Ship(o); err != nil {
			errs = append(errs, fmt.Errorf("ship %s: %w", o.ID, err))
		}
	}
	return errors.Join(errs...)
}

سناریوهای واقعی: متد PHP با پنج لایهٔ if دور نوشتن دیتابیس؛ handler در Go که err را با _ می‌بلعد؛ else پس از return، در حالی که Effective Go می‌گوید اگر بدنهٔ if با return تمام شد، else حذف می‌شود؛ controller لاراول با abort_unless($order->isPaid(), 402) به‌عنوان Guard clause.

php
// Guard clauses in a Laravel action; the happy path is the last four lines.
public function handle(Order $order): void
{
    abort_if($order->cancelled_at !== null, 409, 'Order is cancelled.');
    abort_unless($order->isPaid(), 402, 'Order is not paid.');
    abort_if($order->items->isEmpty(), 422, 'Order has no items.');
    abort_if($order->shipped_at !== null, 409, 'Order already shipped.');

    $order->forceFill(['shipped_at' => now()])->save();
    ShipmentCreated::dispatch($order);
}

بده‌بستان Exception و Error value. Error value هر شکست را در signature و هر بررسی را صریح می‌کند، به قیمت تکرار. Rob Pike در "Errors are values" نشان می‌دهد چگونه با برنامه‌نویسی روی خطاها، مثلاً writer نگه‌دارندهٔ خطا، این تکرار را کم کنیم. Exception مسیر موفق را از بررسی‌ها خالی می‌کند و به یک handler اجازه می‌دهد چند شکست را مدیریت کند، به قیمت جریان کنترل نامرئی. هیچ‌کدام ذاتاً تمیزتر نیست؛ مخلوط کردنشان کد را سخت‌خوان می‌کند، مثل panic در Go برای وضعیت قابل‌بازیابی یا exception در PHP برای شاخه‌بندی عادی.

حالت‌های شکست: Guard clause بدون defer در Go نشت منابع می‌دهد؛ فایل را باز کنید و بلافاصله defer f.Close() بگذارید. Returnهای بیش از حد شکل تابع را پنهان می‌کنند. Wrap کردن با %w در همهٔ لایه‌ها پیامی مثل a: b: c: d: not found می‌سازد که کسی نمی‌خواند. Google Go best practices می‌گوید: "avoid redundant information that the underlying error already provides".

Comment در برابر کد خودتوضیح، و کد مرده مهم ​

به زبان ساده: بگذارید کد بگوید چه می‌کند؛ comment برای چرایی است: دلیل، دام و پیوند به مشخصات.

بدفهمی رایج: «کد خوب comment نمی‌خواهد.» اینجا دو کتاب اصلی اختلاف دارند. Ousterhout از صفحهٔ 54 کتاب Clean Code نوشتهٔ Robert C. Martin نقل می‌کند: "The proper use of comments is to compensate for our failure to express ourselves in code ... Comments are always failures." پاسخ Ousterhout این است که این حرف "stigmatizes writing comments" و برنامه‌نویس تازه‌کار نتیجه می‌گیرد "the safest thing is to write no comments". Martin در همان گفت‌وگو پاسخ می‌دهد که فصل با "Nothing can be quite so helpful as a well placed comment" شروع می‌شود و comment را شر ضروری می‌نامد. هر دو قبول دارند بازگویی خود کد نویز است. موضع این صفحه: هیچ commentی نباید کد را تکرار کند؛ هر API عمومی doc comment دارد؛ هر تصمیم غیرآشکار توضیح چرایی دارد.

نوع commentنگه داریم؟مثال
بازگویی کدحذف؛ به جایش نام را بهتر کنید// loop over items بالای for
توضیح مستندات (Doc comment) برای نام عمومینگه دارید؛ در Go جملهٔ کامل با شروع نام نماد، طبق بخش Comment Sentences در Go Code Review Comments// Quote prices an order. It is pure: ...
چرایی، نه چیستینگه دارید// Spec: ISO 4217 minor units, so 1999 means 19.99
هشدار یا دامنگه دارید// Not safe for concurrent use.
TODO دارای مالک یا ticketنگه دارید و پیگیری کنید// TODO(ORD-412): remove after the v1 API is gone
کد commentشدهحذف؛ version control یادش می‌ماند// oldTotal := t * 1.2
عذرخواهی برای نام بدنام را عوض کنید// x is the discount

کد مرده (Dead code) کدی است که هرگز اجرا نمی‌شود یا نتیجه‌اش را کسی استفاده نمی‌کند: شاخهٔ دسترس‌ناپذیر، تابع بی‌استفاده، feature flag که دو سال پیش کامل فعال شده، یا پارامتری که کسی نمی‌خواند. وقت خواندن می‌گیرد و جست‌وجو را گمراه می‌کند. کامپایلر Go از همان ابتدا import و متغیر محلی بی‌استفاده را رد می‌کند. unused و unparam در golangci-lint تابع، type و پارامتر بی‌استفاده را پیدا می‌کنند. PHPStan از سطح 4 بررسی همیشه‌غلط، شاخهٔ else مرده و کد دسترس‌ناپذیر پس از return را پیدا می‌کند. کد commentشده همان Dead code با روکشی از comment است.

go
// Before: the comment repeats the code and the number has no name.
// check if total is above 50000
if r > 50000 {
	Notify("ops", "big order")
}

// After: the constant names the rule; the doc comment on it says why.
// LargeOrderThreshold is the total above which operations is told.
const LargeOrderThreshold = Cents(50000)

روند یک comment دروغ‌گو:

text
     Step  Date       Change                                          Comment says         Code does
1    v1    Jan        threshold 50000, comment "orders over 500"      correct              correct
2    v2    Jun        threshold changed to 75000                      still "over 500"     wrong
3    v3    Dec        new dev trusts the comment, writes a test       wrong                wrong

DRY، WET و قاعدهٔ سه حیاتی ​

به زبان ساده: هر واقعیت را یک بار بنویسید. اما دو قطعه‌کد که فقط شبیه‌اند یک واقعیت نیستند؛ ادغام زودهنگامشان از خود تکرار گران‌تر تمام می‌شود.

بدفهمی رایج: «DRY یعنی خط تکراری نداشته باشیم.» عبارت نقل‌شده در Wikipedia، منبع ثانویه، دربارهٔ دانش است: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." دو تابع با چهار خط یکسان که به دلایل متفاوت، مثلاً حسابداری و چاپ برچسب، تغییر می‌کنند دو واقعیت‌اند که فعلاً شبیه‌اند. ادغامشان تیم‌ها را به هم وابسته می‌کند و به‌محض نیاز یکی به رفتار متفاوت، یک flag اضافه می‌شود.

تعریف:

اصطلاحمعنی
DRY، کوتاه‌شدهٔ Don't Repeat Yourselfهر دانش یک نمایش معتبر دارد: قاعده، ثابت، schema یا قالب
WETمقابل DRY؛ معمولاً "write everything twice" و گاهی "we enjoy typing"؛ در عمل تعبیر منفی برای کد دارای قواعد کپی‌شده
تکرار دانش (Duplication of knowledge)همان قاعدهٔ کسب‌وکار در دو جا که باید همیشه سازگار بمانند؛ ادغامش کنید
تکرار شکل (Duplication of shape)دو بلوک شبیه که به دلایل مختلف تغییر می‌کنند؛ جدا بمانند
قاعدهٔ سه (Rule of three)"Three strikes and you refactor"؛ دو نمونهٔ شبیه refactor لازم ندارند، در سومی استخراج کنید؛ مشهورشده توسط Fowler و منسوب به Don Roberts
انتزاع غلط (Wrong abstraction)تابع مشترکی که با flag و شرط خم شده تا به فراخواننده‌هایی خدمت کند که از هم فاصله گرفته‌اند

روند یک Wrong abstraction در packageِ dry:

text
     Step  Change                                                        Result
1    v1    InvoiceLine and ShippingLabel both print an amount             two 1-line functions
2    v2    "They look the same" -> FormatAmount(c)                        one shared function
3    v3    labels need brackets -> FormatAmount(c, forLabel bool)         flag argument
4    v4    invoices need padding and currency -> forInvoice, withCurrency four flags, five branches
5    v5    a change for invoices breaks labels                            two owners, one function
6    v6    split again, keeping only Cents.String() shared                 the real shared fact, once

Go و PHP: واقعیت مشترک روش نوشتن مبلغ، یعنی Cents.String، است؛ آن را یک جا نگه می‌داریم و دو قالب خروجی جدا می‌مانند.

go
// Package dry contrasts duplication of knowledge (merge it) with duplication of
// shape (leave it until the rule of three says otherwise).
package dry

import "fmt"

// Cents is money in the smallest unit.
type Cents int64

// FormatAmount is the result of merging two look-alike functions too early.
// Every new caller adds a flag, and the branches now serve two different owners.
func FormatAmount(c Cents, forInvoice, forLabel, withCurrency bool) string {
	s := fmt.Sprintf("%d.%02d", c/100, c%100)
	if forInvoice {
		if withCurrency {
			s += " EUR"
		}
		return fmt.Sprintf("%12s", s)
	}
	if forLabel {
		return "[" + s + "]"
	}
	return s
}

// String is the shared knowledge: how an amount of cents is written. One place.
func (c Cents) String() string { return fmt.Sprintf("%d.%02d", c/100, c%100) }

// InvoiceLine and ShippingLabel look alike today but change for different
// reasons (accounting rules versus label printer width), so they stay separate
// and share only the one fact that really is the same.
func InvoiceLine(c Cents) string { return fmt.Sprintf("%12s", c.String()+" EUR") }

func ShippingLabel(c Cents) string { return "[" + c.String() + "]" }
Two pieces of code look alikeSame knowledge,changes together?noLeave apart:coincidental duplicationyesThird occurrence?noTolerate it, leave anote, watch for a thirdyesExtract; name the sharedknowledge, not the shapeFlags creeping in to make it fit?Inline it again: wrong abstraction
php
// Duplication of knowledge: the same tax rule in two classes. Merge it.
// Before:  Invoice::tax() { return intdiv($net * 20, 100); }  and  Cart::tax() { return intdiv($net * 20, 100); }
// After:   one constant and one method.
final class Tax
{
    public const PERCENT = 20;

    public static function on(int $netCents): int
    {
        return intdiv($netCents * self::PERCENT, 100);
    }
}

سناریوهای واقعی تکرار دانش: آستانهٔ ارسال رایگان در سبد، فاکتور و ایمیل؛ قانون اعتبارسنجی در JavaScript و Form Request که باید یکی را از دیگری تولید یا هر دو را با caseهای یکسان تست کرد؛ فهرست وضعیت‌ها در enum، قید CHECK و dropdown رابط کاربر؛ مقدار پیش‌فرض ستون دیتابیس که در کد هم تکرار شده است.

سناریوهای واقعی تکرار شکل که باید بماند: دو handlerِ API که هر دو decode، اعتبارسنجی و encode می‌کنند ولی برای resourceهای متفاوت؛ دو تست جدولی با ردیف‌های شبیه، چون راهنمای Go خوانایی تست را بر زرنگی ترجیح می‌دهد، طبق تست‌های تمیز؛ سرویس و adapter آن که هر دو فیلدها را map می‌کنند. صفحهٔ Go decisions در Google می‌گوید کد "can also be unnecessarily repetitive if the same or a similar code segment appears multiple times in close proximity"؛ از سوی دیگر Go proverb می‌گوید "A little copying is better than a little dependency". هر دو در یک راهنمای سبک هستند چون هر دو درست‌اند.

چه چیزی آن را پیدا می‌کند: dupl در golangci-lint شباهت tokenها را می‌سنجد، پس شکل را گزارش می‌کند نه دانش را. goconst literalهای تکراری رشته و عدد را پیدا می‌کند و بخشی از تکرار دانش را می‌گیرد. در منابع ذخیره‌شدهٔ این فصل معادل PHP معرفی نشده است. انسان تصمیم می‌گیرد کدام نوع تکرار است؛ سؤال نمودار بالا همین است.

YAGNI، KISS، کلی‌سازی حدسی و انتزاع زودهنگام حیاتی ​

به زبان ساده: نیاز امروز را به ساده‌ترین شکل درست بسازید. برای فردا یک نقطهٔ تعویض تمیز بگذارید، نه یک framework.

بدفهمی رایج: «YAGNI یعنی طراحی نکن.» Fowler در bliki صریحاً از قابلیت‌های فرضی (Presumptive features) حرف می‌زند: "any code that supports a feature that isn't yet being made available for use". حتی اگر حدس درست باشد سه هزینه داریم: ساخت، تأخیر یعنی ارزشی که می‌توانستید به جایش تحویل دهید، و حمل یعنی کدی که باید خوانده شود و کار کند. این اصل refactor کردن به سمت طراحی منعطف را در آینده منع نمی‌کند. فرضش وجود تست و عادت refactoring است تا تغییر آینده ارزان باشد؛ بدون آن‌ها YAGNI فقط قمار است.

تعریف:

اصطلاحمعنیمنبع
YAGNIYou Aren't Gonna Need It؛ قابلیتی را که فقط گمان می‌کنید لازم خواهد شد نسازیدXP؛ blikiِ Fowler
KISSKeep It Simple, Stupid؛ سادگی به‌عنوان هدف طراحیمرتبط با Kelly Johnson؛ Wikipedia، منبع ثانویه
کلی‌سازی حدسی (Speculative generality)hook، interface، پارامتر و subclass برای «شاید روزی» که هیچ استفاده‌کننده‌ای ندارد؛ از بوهای Fowler در بوهای کد و Refactoringکاتالوگ بوها
انتزاع زودهنگام (Premature abstraction)ساختن انتزاع پیش از داشتن دو یا سه مورد واقعی برای تعمیمقاعدهٔ سه
کمترین سازوکار (Least mechanism)راهنمای Go در Google: "Sophisticated machinery often exists, but should not be employed without reason. It is easy to add complexity to code as needed, whereas it is much harder to remove existing complexity"Go Style Guide
روشنی بهتر از زرنگی است (Clear is better than clever)یکی از Go proverbهاGo proverbs

روند یک interface حدسی:

text
     Step  Week   Change                                              Cost
1    w1    "We may add PayPal later" -> PaymentGateway interface       2 files, 1 mock
2    w2    Stripe implementation, bent to fit the interface            a `Raw map` escape hatch added
3    w8    PayPal arrives with a redirect flow                         the interface does not fit; rewritten
4    w9    interface now has 14 methods, 9 of them no-ops for Stripe   every change touches two types

نقطهٔ تعویض، نه framework. YAGNI نمی‌گوید driver دیتابیس را داخل قاعده hard-code کنید. در مرز یک interface کوچک بگذارید جایی که پیاده‌سازی دوم همین حالا دیده می‌شود: Notifier در after/service.go آزمایشگاه وجود دارد چون تست امروز به پیاده‌سازی دوم نیاز دارد. Google Go best practices می‌گوید interface بپذیرید و type عینی برگردانید، طبق GoTip #49. ترتیب Least mechanism در راهنما هم این است: اول سازهٔ خود زبان، بعد کتابخانهٔ استاندارد، بعد dependency.

KISS به معنی ساده‌لوحی نیست. ساده‌ترین چیزی که کار می‌کند نیازهای شناخته‌شده را هم پوشش می‌دهد: پول به‌صورت سنت صحیح، ساعت قابل‌کنترل و خطایی که بتوان تشخیصش داد. کنار گذاشتن این‌ها سادگی نیست؛ باگی است که منتظر رخ دادن است.

سناریوهای واقعی: repository interface با یک پیاده‌سازی و یک mock «برای تست» در زبانی که خود پیاده‌سازی واقعی سریع است؛ سیستم افزونه برای قابلیتی با یک افزونه؛ کلاس BaseService با چهار hook خالی؛ package لاراول که از helper سه‌خطی بیرون کشیده شده؛ microservice برای تیم سه‌نفره.

Linterها: unparam که "reports unused function parameters" نمونهٔ معمول آرگومان حدسی را می‌گیرد؛ unused تابع و type مرده را گزارش می‌کند؛ PHPStan در سطح‌های بالاتر متد و property خصوصی بی‌استفاده را گزارش می‌کند.

قانون اردوگاه تکمیلی ​

به زبان ساده: وقتی به فایلی دست می‌زنید، کمی تمیزتر رهایش کنید: یک نام بهتر، یک تابع استخراج‌شده یا یک شاخهٔ مردهٔ حذف‌شده.

بدفهمی رایج: «اجازه داریم هر چیزی را سر راه refactor کنیم.» تغییر باید کوچک و محلی باشد، در commit جدا یا PRِ بازآرایی آماده‌سازی (Preparatory refactoring)، با تست‌های سبز. بازنویسی گذری فایلی که برای اصلاح غلط تایپی باز کرده‌اید، تغییر اصلی و بازبینی را دفن می‌کند. دو کلاه (Two hats) Fowler را جدا نگه دارید: افزودن رفتار یا refactor، نه هر دو در یک commit؛ بوهای کد و Refactoring را ببینید.

تعریف: قانون اردوگاه (Boy scout rule) عادت تیمی است که معمولاً با "leave the campground cleaner than you found it" بیان می‌شود. این صفحه آن را به کتاب مشخصی نسبت نمی‌دهد چون منبع دست‌اولی دریافت نشده است. شکل عملی آن: هر تغییر ارزان‌ترین بهبودی را همراه داشته باشد که تغییر بعدی را آسان‌تر می‌کند.

روند:

text
     Step  Commit                                      Size    Reviewer sees
1    c1    refactor: rename t -> subtotal in Quote     6 lines   "nothing changed", merges in a minute
2    c2    fix: coupon expiry uses now() argument      9 lines   the real fix, no noise
3    c3    chore: delete unused helper isOddPrice      12 lines  a deletion, trivial to verify

کمک ابزارها: سازوکار جلوگیری از پسرفت (Ratchet) در lint که فقط مسئله‌های جدید را شکست می‌دهد، مثل new-from-rev در golangci-lint و baseline در PHPStan، این عادت را به سیاست تبدیل می‌کند: بدهی قدیمی مجاز است، بدهی تازه نه.

Framework در مرز، جهت وابستگی، انسجام و وابستگی بین ماژول‌ها مهم ​

به زبان ساده: قواعد کسب‌وکار را در کدی نگه دارید که framework وب، ORM یا SDK فروشنده را import نمی‌کند. Framework باید کد شما را صدا بزند.

بدفهمی رایج: «Framework در مرز یعنی دور همه‌چیز interface بپیچیم.» فقط یک معنی دارد: قانون قیمت‌گذاری باید بدون بالا آوردن framework قابل‌فراخوانی و تست باشد. مدل‌های Eloquent، contextهای Gin و Request لاراول در یک CRUD کوچک می‌توانند همه‌جا باشند؛ در موتور قیمت‌گذاری نباید وارد قواعد شوند.

تعریف: جهت وابستگی (Dependency direction) یعنی وابستگی منبع از جزئیات، مثل HTTP، دیتابیس و فروشنده، به سمت سیاست یا قواعد باشد. قانون وابستگی Robert C. Martin و معماری شش‌ضلعی در اصول Clean، Hexagonal و Component است. نظریهٔ انسجام (Cohesion)، یعنی شدت تعلق اجزای یک ماژول به هم، و وابستگی بین ماژول‌ها (Coupling)، یعنی میزان دانستن جزئیات یکدیگر، در کیفیت طراحی آمده است. اینجا از آن‌ها به‌عنوان محک روزانه استفاده می‌کنیم:

سؤالCohesion بالا چه شکلی استCohesion پایین چه شکلی است
نام package چه می‌گوید؟pricing، ledgerutils، common، helpers
تابع‌ها از همان داده‌ها استفاده می‌کنند؟type و invariant مشترک دارندفقط directory مشترک دارند
یک تغییر به یک جا دست می‌زند؟قانون مالیات جدید فقط pricing را ویرایش می‌کندقانون مالیات جدید شش package را ویرایش می‌کند
سؤالCoupling کم چه شکلی استCoupling زیاد چه شکلی است
قاعده را بدون سرور تست می‌کنید؟Quote(now) با یک structقاعده request() و DB:: را صدا می‌زند
دامنه framework را import می‌کند؟نهuse Illuminate\Http\Request داخل قاعده
ماژول‌ها چه مبادله می‌کنند؟مقدار ساده و interface کوچکمدل کامل و وضعیت سراسری

Go و Laravel در عمل: کامپایلر Go چرخهٔ import را ممنوع می‌کند و internal/ نمی‌گذارد بیرونی‌ها جزئیات داخلی را import کنند، پس خطای لایه‌بندی زود دیده می‌شود. در Laravel، controller، Form Request، job و event listener مرزند؛ کلاس‌های سادهٔ app/Orders هسته‌اند که در آزمایشگاه QuoteCalculator، Tier و Quote هستند. تست معماری می‌تواند تضمین کند namespace دامنه Illuminate\Http را import نمی‌کند.

سناریوی واقعی: قانون قیمت‌گذاری داخل controller به Request و Auth::user() نیاز دارد؛ تستش به اپ بالا‌آمده و دیتابیس وابسته است؛ تغییر نسخهٔ framework تست دوبارهٔ قانون قیمت‌گذاری را لازم می‌کند. پس از جابه‌جایی، همان قاعده فقط struct و ساعت می‌خواهد.

ماژول‌های عمیق و کم‌عمق مهم ​

به زبان ساده: ماژول خوب رابط کوچکی دارد که کار زیادی پشت آن انجام می‌شود. ماژول بد رابطی به بزرگی همان کدی دارد که پنهان می‌کند.

بدفهمی رایج: «کوچک‌تر همیشه بهتر است.» Ousterhout در گفت‌وگوی منتشرشده می‌گوید: "As methods get smaller and smaller there is less and less benefit to further subdivision. The amount of functionality hidden behind each interface drops, while the interfaces often become more complex. I call these interfaces 'shallow': they don't help much in terms of reducing what the programmer needs to know."

تعریف: از A Philosophy of Software Design نوشتهٔ John Ousterhout، از طریق سایت او و همان گفت‌وگو: ماژول عمیق (Deep module) "replaces a large cognitive load (reading the detailed implementation) with a much smaller cognitive load (learning the interface)". ماژول کم‌عمق (Shallow module) رابطی تقریباً هم‌پیچیدگی پیاده‌سازی دارد. درهم‌تنیدگی (Entanglement)، یا "conjoined" در اصطلاح او، یعنی دو متد که بدون خواندن یکدیگر فهمیده نمی‌شوند: "If you've ever found yourself flipping back and forth between the implementations of two methods as you read code, that's a red flag". درمان او: "Entangled methods can usually be improved by combining them so that all the code is in one place."

Shallow moduleIsBlank IsComment HasSeparator SplitPairfour one-line bodieswide interface, thin implementationthe caller re-assembles the parserDeep moduleParseConfig(r)blank lines and comments skippedkeys and values trimmedmissing '=' reported with the line numberscanner errors surfacedlarge implementation hiddennarrow interface, much hidden behind itOusterhout: a good module is deep. Shallow splits add names without hiding anything.

روند خرد کردن بیش از حد:

text
     Step  Reader action                                            What the reader learns
1    t0    reads ParseConfig() calls IsBlank, IsComment, ...        names only
2    t1    jumps to IsBlank                                         a one-line TrimSpace test
3    t2    jumps to IsComment                                       must know IsBlank ran first
4    t3    jumps to SplitPair                                       must know HasSeparator ran first
5    t4    returns to ParseConfig                                   has re-assembled the parser in their head
go
// Package deep contrasts a shallow decomposition with a deep module
// (John Ousterhout, A Philosophy of Software Design).
package deep

import (
	"bufio"
	"fmt"
	"io"
	"strings"
)

// The shallow version exports four tiny helpers. A caller must know the order
// to call them in and what each one assumes: the interface is as big as the
// implementation it hides.

func IsBlank(line string) bool      { return strings.TrimSpace(line) == "" }
func IsComment(line string) bool    { return strings.HasPrefix(strings.TrimSpace(line), "#") }
func HasSeparator(line string) bool { return strings.Contains(line, "=") }
func SplitPair(line string) (k, v string) {
	k, v, _ = strings.Cut(line, "=")
	return strings.TrimSpace(k), strings.TrimSpace(v)
}

// ParseConfig is the deep version: one function, one idea (key=value lines
// with comments), and the caller never learns how blank lines or comments are
// recognised. Errors carry the line number.
func ParseConfig(r io.Reader) (map[string]string, error) {
	out := map[string]string{}
	sc := bufio.NewScanner(r)
	for n := 1; sc.Scan(); n++ {
		line := strings.TrimSpace(sc.Text())
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		key, value, ok := strings.Cut(line, "=")
		if !ok {
			return nil, fmt.Errorf("line %d: missing '=' in %q", n, line)
		}
		out[strings.TrimSpace(key)] = strings.TrimSpace(value)
	}
	return out, sc.Err()
}

اختلاف واقعی دو کتاب و نقطهٔ توافقشان:

موضوعClean Code از Robert C. MartinA Philosophy of Software Design از John Ousterhoutنقطهٔ مشترک
طول تابعبسیار کوچک؛ یک کار انجام دهدتا جایی بشکنید که رابط ساده شود، نه بیشترطراحی ماژولار خوب است؛ خرد کردن بیش از حد ممکن است
Comment"Comments are always failures" طبق نقل‌قولComment اطلاعات طراحی‌ای را حمل می‌کند که کد نمی‌تواندComment تکرارکنندهٔ کد نویز است
نام‌گذاریقصد را آشکار کنددقیق و یکدست باشدنام‌ها بسیار مهم‌اند
رابط‌هاکوچک و متمرکزباریک ولی عمیقچیزی را که فراخواننده لازم نیست بداند پنهان کنید

جمع‌بندی خود گفت‌وگو: "We agree that it is possible to over-decompose, and that Clean Code 1st ed. doesn't provide much guidance on how to recognize over-decomposition." همین را محک کنید: اگر برای فهمیدن یک ایده مرتب بین دو تابع رفت‌وبرگشت می‌کنید، آن‌ها را ادغام کنید.

معیارهای پیچیدگی: دوری، شناختی و ابزارها مهم ​

به زبان ساده: ابزار پیچیدگی حس «این تابع سخت است» را به عدد قابل‌پیگیری و آستانهٔ قابل‌اعمال تبدیل می‌کند.

بدفهمی رایج: «امتیاز کم یعنی خوانایی.» امتیاز شاخه‌ها را می‌شمارد، نه نام، انتزاع یا comment را. تابعی با امتیاز 3 می‌تواند ناخوانا باشد؛ switch تخت با امتیاز 20 کاملاً روشن. مقالهٔ Sonar هم در نقد پیچیدگی دوری همین را می‌گوید: دو متد هر دو امتیاز 4 دارند ولی "it is intuitively obvious that the control flow of sumOfPrimes is more difficult to understand than that of getWords".

تعریف:

معیارروش محاسبهقوتضعفابزار Goابزار PHP
پیچیدگی دوری (Cyclomatic complexity)gocyclo: "1 is the base complexity of a function, +1 for each 'if', 'for', 'case', '&&' or ''"تعداد مسیر مستقل، پس حد پایین تعداد caseهای تستswitch تخت امتیاز زیاد می‌گیرد؛ تودرتویی دیده نمی‌شود
پیچیدگی شناختی (Cognitive complexity)Sonar: شکل کوتاه را نادیده بگیر، برای هر شکست جریان خطی یکی و برای تودرتویی بیشتر اضافه کنبا شهود هماهنگ است؛ تودرتویی گران‌تر استجزئیات به ابزار وابسته استgocognitقواعد Sonar، PHPStorm و ابزارهای دیگر
پیچیدگی مسیر بی‌چرخه (NPath complexity)تعداد مسیرهای اجرای بدون چرخهانفجار ترکیب‌ها را نشان می‌دهدرشد نمایی داردابزار رایج نداردPHPMD، NPathComplexity با 200
طول تابع (Function length)خط و دستورخام ولی ارزانچیزی دربارهٔ ساختار نمی‌گویدfunlen با 60 خط و 40 دستورPHPMD، ExcessiveMethodLength
عمق تودرتویی (Nesting depth)پیچیدگی if تودرتوشکل هرمی را هدف می‌گیردnestif با 5وابسته به قاعده
تعداد پارامتر (Parameter count)تعداد پارامترهافهرست بلند را هدف می‌گیرددر مجموعهٔ پیش‌فرض نیستPHPMD، ExcessiveParameterList با 10

مثال محاسبه‌شده: GetWords(number int) در READMEِ gocognit، برای شکل switch امتیاز دوری 4 و شناختی 1 می‌گیرد؛ کل switch یک بار حساب می‌شود، نه هر case. شمارش دستی before.Proc آزمایشگاه با قواعد gocyclo برابر 15 است: پایهٔ 1 و یکی برای هر کدام از 14 شرط. تابع‌های تمیز after حداکثر 5 می‌گیرند؛ در subtotalOf پایه، len، for و دو if. این‌ها شمارش دستی‌اند و ابزار اجرا نشده است؛ توضیح در آزمایشگاه آمده.

text
     Line in the function                      cyclomatic   cognitive (nesting adds)
1    func GetWords(number int) string {          1            0
2    switch number {                             0            +1   (one for the whole switch)
3      case 1: return "one"                      +1           0
4      case 2: return "a couple"                 +1           0
5      case 3: return "a few"                    +1           0
6      default: return "lots"                    0            0
7    }                                           total 4      total 1

واقعیت ابزارها از مستندات ذخیره‌شده: referenceِ golangci-lint برای gocyclo و gocognit توضیح "Default: 30 (but we recommend 10-20)" دارد؛ پیش‌فرض funlen برابر 60 خط و 40 دستور و nestif برابر 5 است. rulesetِ codesize در PHPMD برای CyclomaticComplexity مقدار reportLevel برابر 10 می‌دهد، برای NPathComplexity عدد 200 را "generally considered the point where measures should be taken" می‌نامد و برای ExcessiveParameterList حداقل 10 دارد. PHPStan یازده سطح 0 تا 10 دارد، با "0 is the loosest and 10 is the strictest" و پیش‌فرض 0؛ Psalm سطح خطای 1 سخت‌گیرترین تا 8 و پیش‌فرض 2 دارد. این دو بررسی‌کنندهٔ نوع هستند، نه معیار پیچیدگی، اما نیمهٔ دیگر «ابزار پیش از بازبین خبر بدهد» را می‌سازند.

چگونه از عددها استفاده کنیم: آستانه را کمی بالاتر از بدترین تابع امروز بگذارید؛ CI فقط برای نقض‌های جدید شکست بخورد؛ با refactor کردن آستانه را پایین بیاورید. آستانهٔ 10 برای کدی با میانهٔ 25، ظرف یک هفته خاموش می‌شود.

تست‌های تمیز: اصول FIRST، سرعت، استقلال و خوانایی مهم ​

به زبان ساده: تست هم کدی است که وقت شکست می‌خوانیم. باید سریع، خودبسنده و بدون باز کردن فایل گویای مشکل باشد.

بدفهمی رایج: «کد تست لازم نیست تمیز باشد.» این کد را در بدترین لحظه می‌خوانید: build قرمز است و deadline نزدیک. صفحهٔ تصمیم‌های Go در Google می‌گوید: "It should be possible to diagnose a test's failure without reading the test's source."

تعریف: اصول FIRST یادآوری پنج ویژگی از مجموعهٔ Agile in a Flash نوشتهٔ Tim Ottinger و Jeff Langr است؛ صفحه در first-ottinger.txt ذخیره شده: Fast، Independent، Repeatable، Self-validating، Timely.

حرفمعنیعادت Goعادت Laravel و PHP
سریع (Fast)در چند میلی‌ثانیه تا افراد اجرا کنندتابع خالص setup نمی‌خواهد؛ t.Parallel()TestCase سادهٔ PHPUnit برای کلاس خالص؛ feature test فقط جایی که HTTP مهم است
مستقل (Independent)هیچ تستی به دیگری یا ترتیب وابسته نیستهر case ورودی خودش را دارد؛ بدون state مشترک packageRefreshDatabase یا DatabaseTransactions برای هر تست
تکرارپذیر (Repeatable)هر جا و هر زمان همان نتیجهتزریق ساعت؛ بدون شبکهhelperهای زمان Laravel مثل travel، همچنین Http::fake و Queue::fake
خودارزیاب (Self-validating)قبول یا رد؛ انسان خروجی را تفسیر نمی‌کندt.Errorf با got و wantassertion به جای dd()
به‌موقع (Timely)همراه کد یا پیش از آن نوشته می‌شودتست جدولی کنار تابعتست PHPUnit در همان PR

خوانایی تست (Test readability). پیام شکست نام تابع، ورودی، نتیجهٔ واقعی و نتیجهٔ مورد انتظار را می‌گوید. قرارداد Go، Slugify(%q) = %q, want %q است و تست آزمایشگاه از آن پیروی می‌کند. تست جدولی با فیلد name به هر case زیر go test -run برچسب خوانا می‌دهد. راهنمای Go در Google پیام مفیدی می‌خواهد که "detailing what caused the failure, what inputs resulted in an error, the actual result, what was expected".

go
// Package firsttest holds one function and a test written to the FIRST
// principles: fast, independent, repeatable, self-validating, timely.
package firsttest

import (
	"strings"
	"unicode"
)

// Slugify lower-cases s and joins its letter and digit runs with single dashes.
func Slugify(s string) string {
	var b strings.Builder
	dash := false
	for _, r := range strings.ToLower(s) {
		if unicode.IsLetter(r) || unicode.IsDigit(r) {
			if dash && b.Len() > 0 {
				b.WriteByte('-')
			}
			b.WriteRune(r)
			dash = false
			continue
		}
		dash = true
	}
	return b.String()
}
go
package firsttest

import "testing"

// Fast: pure function, no I/O. Independent: each case owns its input.
// Repeatable: no clock, no network, no shared state. Self-validating: a plain
// comparison, no human reads output. Readable: the failure names input, got, want.
func TestSlugify(t *testing.T) {
	t.Parallel()
	tests := []struct {
		name string
		in   string
		want string
	}{
		{"spaces become one dash", "Clean  Code Principles", "clean-code-principles"},
		{"punctuation is dropped", "DRY, YAGNI & KISS!", "dry-yagni-kiss"},
		{"leading and trailing noise is trimmed", "  --Go--  ", "go"},
		{"digits are kept", "Go 1.24 notes", "go-1-24-notes"},
		{"empty stays empty", "", ""},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()
			if got := Slugify(tt.in); got != tt.want {
				t.Errorf("Slugify(%q) = %q, want %q", tt.in, got, tt.want)
			}
		})
	}
}

روند یک مجموعه‌تست کند و وابسته:

text
     Step  Test                          Depends on                    Time
1    t1    TestCreateUser                a real database               380 ms
2    t2    TestSendWelcome               the user created by t1        120 ms  (fails if t1 is skipped)
3    t3    TestExpiredCoupon             the wall clock                50 ms   (fails after midnight)
4    -     whole suite                   order and shared state        4 min   -> run once a day, ignored

هرم تست، بدل‌ها، TDD و تست ناپایدار در راهبرد تست و TDD است؛ سازوکار Go شامل testing، -race، benchmark و b.Loop در تست و Benchmark آمده است.

رفتار هر زبان و ابزار ​

هیچ قاعده‌ای را بدون گفتن ابزارش نام نبرید. یک قاعده در Go و PHP شکل متفاوتی پیدا می‌کند و برخی قواعد اصلاً ابزار ندارند.

قاعدهچه چیزی در Go اعمالش می‌کندچه چیزی در PHP و Laravel اعمالش می‌کندبدون ابزار؛ انسان باید
قالب‌بندی (Formatting)gofmt -l .؛ اگر چیزی چاپ کرد CI شکست بخوردpint --testدربارهٔ چیدمان SQL تصمیم بگیرد
قرارداد نام‌گذاری (Naming conventions)revive، Go Code Review Comments و go vet برای برخی خطاهای printfPSR-12 و PER با Pint، inspectionهای PHPStormتشخیص دهد نام صادقانه است یا نه
کد بی‌استفاده (Unused code)کامپایلر برای import و متغیر محلی، unused و unparamPHPStan در سطح‌های بالاتر، PHPStormتشخیص دهد تابع عمومی واقعاً مرده است یا نه
پیچیدگی (Complexity)gocyclo، gocognit، cyclop، nestif، funlenPHPMD با CyclomaticComplexity، NPathComplexity، ExcessiveMethodLengthتشخیص دهد امتیاز بالا از جدول آمده یا از کد درهم
تکرار (Duplication)dupl، goconstدر منابع ذخیره‌شده ابزار استانداردی نیستدانش را از شکل جدا کند
نوع و ایمنی null (Types and null safety)کامپایلر، go vet، staticcheck، nilnilPHPStan با سطح 0 تا 10، Psalm با سطح 8 تا 1تصمیم بگیرد type باید چه باشد
مدیریت خطا (Error handling)linterهای errcheck، errorlint، wrapcheck و go vetPHPStan برای @throws، handler لاراولمالک رسیدگی به هر خطا را تعیین کند
اثر جانبی و خلوص (Side effects and purity)ابزار مستقیم ندارد؛ gochecknoglobals وضعیت تغییرپذیر package را گزارش می‌کندابزار مستقیم نداردبا بازبینی core را خالص نگه دارد
معماری و جهت وابستگی (Dependency direction)خطای چرخهٔ import در کامپایلر، internal/ و depguardتست معماری اختصاصیجای مرز را تعیین کند
تستgo test -race، t.Parallel، testing/synctest برای زمان که اینجا پوشش داده نشدهPHPUnit، fakeهای Laravelدربارهٔ خوانایی تست قضاوت کند

نام linterهای بالا از صفحهٔ Linters و reference configِ golangci-lint ذخیره‌شده برای این فصل است؛ نام قواعد PHPMD از صفحهٔ codesize ذخیره‌شدهٔ آن آمده است.

قراردادهای نام‌گذاری کنار هم:

مفهومGoPHP با PSR-1 و PSR-12Laravel
Type و کلاسOrderQuote برای exportشده، orderQuote برای خصوصی در packageOrderQuote با StudlyCapsOrderQuote؛ مدل مفرد مثل Order
تابع و متدQuote، quotequote() با camelCasequote()
ثابتMaxRetries با MixedCaps، بدون ALL_CAPSMAX_RETRIESMAX_RETRIES؛ کلید config با snake_case
Package و namespacepricing با حروف کوچک و یک کلمهApp\OrdersApp\Orders، Illuminate\...
فایلquote.go، quote_test.goQuoteCalculator.php؛ طبق PSR-4 نام فایل برابر کلاس استهمان
تستTestQuote، TestQuote_Expired؛ subtest با t.RunQuoteCalculatorTest، test_expired_coupon_is_ignoredهمان
BooleanisPaid، hasItems؛ بدون نفی مثل notDisabledisPaid()، hasItems()در Eloquent ستون is_paid و accessor به نام isPaid()
خطاErrNotPaid برای sentinel، *PaymentError برای typePaymentFailedExceptionexception با نام شکست

سازوکار: ابزارها چگونه کار می‌کنند و چگونه متصلشان کنیم ​

gofmt چگونه کار می‌کند مهم ​

gofmt فایل را به درخت نحو انتزاعی (Abstract syntax tree) parse می‌کند و درخت را با یک چیدمان ثابت چاپ می‌کند. بنابراین گزینه‌ای برای بحث باقی نمی‌ماند: tab برای تورفتگی و هم‌ترازی ستونی برای commentها و فیلدهای struct. این کار تکرارپذیری بی‌اثر (Idempotence) دارد؛ Formatting کدِ قالب‌بندی‌شده چیزی را عوض نمی‌کند. flagهای مستند: -l نام فایل‌های متفاوت را چاپ می‌کند، -d یک diff می‌دهد، -w فایل را بازنویسی می‌کند، -s ساده‌سازی می‌کند، -r 'pattern -> replacement' پیش از Formatting قاعدهٔ بازنویسی را روی منبع اعمال می‌کند و -e همهٔ خطاها را نشان می‌دهد. در CI از test -z "$(gofmt -l .)" یا golangci-lint fmt --diff استفاده کنید، هرگز -w نزنید.

bash
# CI step: fail if any file is not gofmt-clean
test -z "$(gofmt -l .)" || { gofmt -d . ; exit 1; }

پیچیدگی دوری و شناختی چگونه شمرده می‌شوند مهم ​

پیچیدگی دوری (Cyclomatic complexity) از 1 شروع می‌شود و برای هر نقطهٔ تصمیم 1 اضافه می‌کند. دربارهٔ پیچیدگی شناختی (Cognitive complexity)، مقالهٔ Sonar می‌گوید: "A Cognitive Complexity score is assessed according to three basic rules: 1. Ignore structures that allow multiple statements to be readably shorthanded into one 2. Increment (add one) for each break in the linear flow of the code 3. Increment when flow-breaking structures are nested". چهار نوع افزایش داریم: nesting، structural، fundamental و hybrid.

text
     Code                                         gocyclo   gocognit
1    if a {                                       +1        +1
2        if b {                                   +1        +2   (nesting level 1)
3            for ... {                            +1        +3   (nesting level 2)
4    } else if c {                                +1        +1   (else-if: no nesting increment)
5    x := a && b                                  +1        +1   (a sequence of the same operator counts once in cognitive)

قواعد else if و عملگر boolean در ستون آخر از مثال‌های READMEِ gocognit و ایده‌های "ignore shorthand" و "sequence of like operators" در مقالهٔ Sonar پیروی می‌کنند. جزئیات حالت‌های مرزی به نسخه وابسته است؛ اگر تصمیم آستانه به آن وابسته شد، README همان نسخه را بررسی کنید.

اتصال همه‌چیز به CI حیاتی ​

یک .golangci.yml کامل برای golangci-lint v2 که قالبش با version: "2" آغاز می‌شود و فقط موارد بحث‌شدهٔ این فصل را فعال می‌کند:

yaml
version: "2"
linters:
  default: standard            # errcheck, govet, ineffassign, staticcheck, unused
  enable:
    - gocognit
    - gocyclo
    - funlen
    - nestif
    - dupl
    - unparam
    - revive
    - errorlint
  settings:
    gocognit:
      min-complexity: 15       # default 30, recommended 10 to 20
    gocyclo:
      min-complexity: 15
    funlen:
      lines: 60                # the default; keep or lower
      statements: 40
      ignore-comments: true
    nestif:
      min-complexity: 5
  exclusions:
    rules:
      - path: _test\.go
        linters: [funlen, dupl]  # table tests are long and repetitive on purpose
formatters:
  enable:
    - gofmt
    - goimports
issues:
  new-from-rev: origin/main      # the boy-scout ratchet: only new problems fail

خط default: standard، بلوک formatters: و new-from-rev همگی در referenceِ ذخیره‌شدهٔ golangci-lint آمده‌اند. syntax دقیق exclusions را با نسخه‌ای که نصب می‌کنید تطبیق دهید.

سمت PHP سه فایل کوچک داریم:

json
{ "preset": "laravel" }
yaml
# phpstan.neon  (PHPStan: 11 levels, 0 loosest and 10 strictest; start where the code passes)
parameters:
    level: 6
    paths: [app]
includes:
    - phpstan-baseline.neon     # existing errors; raise the level one step per PR
xml
<!-- phpmd.xml: size and complexity rules with explicit thresholds -->
<ruleset name="clean-code" xmlns="http://pmd.sf.net/ruleset/1.0.0">
    <rule ref="rulesets/codesize.xml/CyclomaticComplexity">
        <properties><property name="reportLevel" value="10"/></properties>
    </rule>
    <rule ref="rulesets/codesize.xml/ExcessiveParameterList">
        <properties><property name="minimum" value="6"/></properties>
    </rule>
</ruleset>
bash
# CI for a Laravel app: style, types, tests (Psalm is the alternative to PHPStan)
./vendor/bin/pint --test
./vendor/bin/phpstan analyse --memory-limit=1G
./vendor/bin/phpmd app text phpmd.xml
php artisan test --parallel

Hook پیش از commit؛ فقط بررسی سریع، بررسی کند در CI بماند:

bash
#!/bin/sh
# .git/hooks/pre-commit
test -z "$(gofmt -l .)" || { echo "gofmt needed"; exit 1; }
./vendor/bin/pint --test || exit 1

چک‌لیست بازبینی کد ​

چک‌لیست بازبینی (Code review checklist) کار انسان پس از سبز شدن ابزارهاست. آن‌قدر کوتاه نگهش دارید که واقعاً استفاده شود.

#سؤالقاعدهٔ پشت آن
1هر نام چه و چرا را می‌گوید؟ با جست‌وجو پیدایش می‌کنید؟نام‌گذاری
2هر تابع در یک سطح انتزاع است و بدون «و» می‌توان نامش را گفت؟تابع‌های کوچک
3آرگومان flag، null یا خروجی داریم؟ فهرست آرگومان‌های هم‌نوع چطور؟آرگومان‌ها
4اثرهای جانبی کجا هستند؟ در مرز مانده‌اند؟تابع‌های خالص، هستهٔ تابعی
5متد query وضعیت را عوض می‌کند؟ هر command قابل‌retry، idempotent است؟CQS
6اول شکست‌ها رسیدگی می‌شوند و مسیر موفق کنار حاشیه است؟ خطا با context بسته‌بندی شده یا متن تکراری؟مدیریت خطا
7هر comment چرایی را می‌گوید؟ کد commentشده یا مرده وجود دارد؟Commentها
8هر تکرار یک دانش است یا فقط شکل مشابه؟DRY
9Interface، گزینه یا لایه‌ای با دقیقاً یک استفاده‌کننده داریم؟YAGNI
10قاعده framework را import می‌کند؟Framework در مرز
11اگر این را بشکنم، مجبور می‌شوم بین دو تابع رفت‌وبرگشت کنم؟ماژول‌های عمیق
12پیام شکست تست، ورودی، got و want را می‌گوید؟ تست‌ها سریع و مستقل‌اند؟تست‌های تمیز
13Diff یک تغییر است و refactorها در commit جدا هستند؟قانون اردوگاه

سبک، import، Formatting و کد بی‌استفاده در فهرست نیستند: مسئولشان ابزارها هستند.

حل مسئله‌های کلاسیک ​

مسئلهراه‌حلچگونهمزیتهزینه یا محدودیت
Handler شصت‌خطیجداسازی فازها و هستهٔ خالص (Pure core)Decode، فراخوانی Quote، encode؛ طبق آزمایشگاهقواعد بدون HTTP تست می‌شوندفایل بیشتر
پارامتر booleanدو تابع نام‌دارRenderSummary، RenderDetailمحل فراخوانی خواناستنام بیشتر در API
فهرست بلند آرگومانOption struct یا آرگومان نام‌دارConfig با پیش‌فرض مقدار صفرمصون از جابه‌جایی و قابل‌گسترشStruct می‌تواند فیلد نامرتبط جمع کند
ساعت پنهانپاس دادن nowQuote(now)تست قطعییک آرگومان بیشتر
Hook سراسریتزریق interface کوچکNotifier در Serviceتست‌پذیر بدون patchنگه‌داری interface
هرم ifهاشرط نگهبان (Guard clause)بازگشت در هر شکستکد تختdefer برای پاک‌سازی لازم است
Helper که همه import می‌کنندانتقال به تنها فراخواننده یا نام‌گذاری با مفهوم دامنهutils به pricing یا money تبدیل شودانسجامجابه‌جایی کوتاه‌مدت کد
انتزاعی که کسی نخواستهحذف و inlineفقط جایی نقطهٔ تعویض نگه دارید که پیاده‌سازی دوم داردکد کمتر برای خواندندوباره‌کاری اگر حدس درست بوده باشد
انتزاع غلط (Wrong abstraction)Inline و استخراج دوبارهکپی به هر فراخواننده و حذف flagهاهر فراخواننده دوباره ساده می‌شودتکرار موقت
Comment دروغ‌گوحذف یا تغییر نامجایگزینی با ثابت یا تابع نام‌داریک منبع حقیقتبرای اطمینان تست لازم است
تست کند و وابستهPure core با ساعت تزریق‌شدهPlan(invoices, now)اجرا در میلی‌ثانیهابتدا تغییر طراحی لازم است

Handler چاق و controller چاق ​

آزمایشگاه هر دو را نشان می‌دهد: منطق handlerِ Go به Order.Quote(now) و یک Service تبدیل می‌شود؛ calc() لاراول به Form Request، یک QuoteCalculator خالص و controller باریک قابل‌فراخوانی تبدیل می‌شود. کاتالوگ کامل حرکت‌ها در بوهای کد و Refactoring است.

Helper که همه import می‌کنند ​

text
     Step  Action                                                          Check
1    1     list the callers of utils.FormatMoney (grep, gopls references)  how many packages?
2    2     if one package: move it there and make it unexported            compiler finds the rest
3    3     if several: create a package named for the concept (money)      Cents.String() lives here
4    4     delete utils.FormatMoney in the same PR                         no dead copy left

انتزاع غلط، گام‌به‌گام ​

text
     Step  Symptom                                                    Move
1    1     a shared function with 3 or more flags                     stop adding; list each caller's real path
2    2     callers pass literals that skip branches                   inline the function into each caller
3    3     delete the branches each caller does not use               each copy is now small
4    4     look for the knowledge that is still identical             extract only that (Cents.String)

انتخاب: وقتی دو قاعده اختلاف دارند کدام برنده است ​

وضعیتپیشنهادتکنیک تکمیلیدلیل
DRY در برابر خواناییخوانایی، مگر همان دانش باشدقاعدهٔ سه (Rule of three)تکرار شکل ارزان است؛ انتزاع غلط گران
تابع کوچک در برابر ماژول عمیق (Deep module)تا جایی بشکنید که رابط ساده‌تر شود، نه بیشترمحک رفت‌وبرگشت بین دو تابععلامت خطر Ousterhout
Comment در برابر کد خودتوضیحنام برای چیستی، comment برای چراییDoc comment روی هر نام عمومیدو کتاب تا اینجا توافق دارند
YAGNI در برابر «می‌دانیم در راه است»وقتی برنامه‌ریزی شد بسازید؛ فقط با وجود پیاده‌سازی دوم نقطهٔ تعویض بگذاریدتغییر بعدی را با تست ارزان کنیدهزینهٔ حمل و تأخیر از دید Fowler
خلوص (Purity) در برابر راحتیهستهٔ خالص و پوستهٔ نازکساعت و config را پاس دهیدتست fake نمی‌خواهد
بازگشت زودهنگام (Early return) در برابر خروجی واحدEarly returndefer برای پاک‌سازیEffective Go و Code Review Comments
Exception در برابر Error valueروش معمول زبان: مقدار در Go، exception در LaravelWrap با context و رسیدگی در یک مرزمخلوط کردن مدل‌ها مشکل واقعی است
آستانهٔ سخت‌گیرانه در برابر کد قدیمیRatchet؛ فقط نقض جدید شکست بخوردnew-from-rev، baseline در PHPStanبدهی قدیمی جلوی تحویل را نمی‌گیرد
قاعده در برابر deadlineتحویل دهید، بدهی را بنویسید، در تغییر بعدی رفع کنیدقانون اردوگاه (Boy scout rule)تمیزی وسیلهٔ سرعت است
سلیقهٔ سبک در برابر formatterFormatter برنده استgofmt، Pintوگرنه بحث تمام نمی‌شود

ترتیب حل تعارض از چهار قاعدهٔ Beck به روایت Fowler: پاس شدن تست‌ها؛ روشن شدن قصد؛ نبود تکرار؛ کمترین عناصر. اگر دو قاعدهٔ این صفحه با هم برخورد کردند، آن‌که در این ترتیب بالاتر است برنده می‌شود.

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

قواعد کد تمیز در سطح تابع‌اند، اما زمینهٔ معماری را می‌سازند. هستهٔ خالص (Pure core) را می‌توان به پردازه‌ای دیگر برد؛ هسته‌ای که ساعت و دیتابیس را می‌خواند این قابلیت را ندارد.

Monolith: یک پردازه، یک دیتابیس ​

چگونه دیده می‌شود: همهٔ قواعد با تمام توان اعمال می‌شوند. کامپایلر یا PHPStan هر refactor را بررسی می‌کند و تغییر نام در یک commit تمام می‌شود.

ساده‌ترین استفادهٔ درست: اجرای gofmt یا Pint هنگام ذخیره، linter در CI، شرط نگهبان (Guard clause)، تابع قیمت‌گذاری خالص و یک تست برای هر قاعده.

مثال ساده: PostController@store یک وبلاگ منطق تولید slug پیدا می‌کند. Slugify را استخراج کنید، با جدول تست کنید، مثل packageِ firsttest آزمایشگاه، و ادامه دهید.

مثال پیچیده: آزمایشگاه؛ تابع قیمت‌گذاری 52 خطی به Order.Quote(now) خالص تبدیل می‌شود و فقط notifier ثبت‌کننده fake است.

Monolith ماژولار و چند دیتابیس ​

چگونه دیده می‌شود: انسجام (Cohesion) و وابستگی (Coupling) به سطح ماژول می‌روند. هر ماژول نمای کوچک یا facade عرضه می‌کند؛ یک ماژول عمیق. ماژول‌های دیگر آن را با مقدار ساده صدا می‌زنند و بقیه internal می‌ماند.

قواعد: هر ماژول واژگان خودش را دارد؛ معنی Order در Billing با Shipping متفاوت است. هیچ ماژولی جدول دیگری را نمی‌خواند. Importها را در Go با internal/ و depguard و در PHP با تست معماری کنترل کنید.

مثال: Billing جمع سفارش را می‌خواهد. orders.Totals(ctx, id) را صدا می‌زند؛ query است و مقدار برمی‌گرداند. هرگز جدول orders را نمی‌خواند. Commandِ orders.MarkInvoiced جدا و idempotent است.

Microservice: چه چیزی آن سوی شبکه باقی می‌ماند ​

چه می‌ماند: تابع‌های خالص (Pure functions) بدون تغییر به آن سوی شبکه منتقل می‌شوند؛ هستهٔ بدون I/O را به دلخواه می‌توان سرویس یا کتابخانه کرد. چه می‌شکند: وابستگی پنهان، مثل متغیر سراسری، ساعت مشترک یا دیتابیس مشترک، باید قرارداد صریح شود و نام تابع به API تبدیل می‌شود.

قاعدهداخل سرویسبین سرویس‌ها
جداسازی فرمان و پرس‌وجو (Command-query separation)سطح متدHTTP GET یک query و POST یک command است؛ CQRS در سطح معماری
تکرارپذیری بی‌اثر (Idempotence)Append کلیددارIdempotency key برای هر POST قابل‌retry؛ مصرف‌کننده تکرار را حذف می‌کند؛ مصرف‌کنندهٔ Idempotent و Inbox
نام‌گذارییک واژگان در هر packageیک واژگان در هر bounded context؛ واژهٔ یکسان می‌تواند معنی متفاوت داشته باشد
DRYیک ثابتنه بین سرویس‌ها؛ کپی value object کوچک بهتر از کتابخانهٔ مشترک با چرخهٔ انتشار است
مقدار خطا (Error value)errorکد وضعیت، problem details و قواعد retry؛ Idempotency در API

جریان مثال: POST /orders در shell، Order.Quote(now) را در core صدا می‌زند و OrderQuoted را به‌عنوان اثر جانبی منتشر می‌کند. سرویس دوم event را می‌گیرد، با event_id تکرار را حذف می‌کند تا idempotent باشد، سپس Plan خالص خودش را اجرا می‌کند.

دادهٔ توزیع‌شده: Replica، Cache و Schema مشترک ​

کجا می‌شکند: قاعدهٔ «خالصی» که از replica می‌خواند، تکرارپذیری‌اش به lag همان replica محدود است. Cache نتیجهٔ تابع ناخالص باگی است که ساعت 03:00 ظاهر می‌شود. ورودی را صریح کنید: timestamp یا نسخهٔ خواندن replica را به core بدهید؛ تابع خالص را فقط با آرگومان‌هایش cache کنید.

بوهای این سطح: دیتابیس مشترک به‌عنوان API، یعنی coupling از راه جدول‌ها؛ مقدار cacheشده‌ای که قالبش زیر پای readerهای قدیمی عوض شده، پس کلید را نسخه‌دار کنید؛ retry غیرidempotent روی صف تکثیرشده.

مسیر مقیاس: 1x، 10x، 100x ​

مقیاسساختارروش کد تمیز
1x، یک تیم و یک اپMonolithFormatter و linter در CI، guard clause و یک هستهٔ خالص برای قواعد پول
10x، چند تیم و یک repoMonolith ماژولارFacade ماژول، depguard یا تست معماری، ratchet پیچیدگی، چک‌لیست بازبینی
100x، تیم‌ها و سرویس‌های فراوانسرویس بر اساس قابلیتتنظیم lint هر سرویس در قالب مشترک، تست قرارداد، idempotency key و واژگان مکتوب هر bounded context

آزمایشگاه: تمیز کردن تابع قیمت‌گذاری 52 خطی Go و controller لاراول ​

از کدی شروع می‌کنید که کار می‌کند ولی نیمی از قواعد این صفحه را می‌شکند. رفتار آن را با تست توصیفی (Characterization test) تثبیت می‌کنید و بعد گام‌به‌گام بازنویسی می‌کنید. مجموعه‌تست، کد Go «بعد» را با «قبل» مقایسه می‌کند تا تغییر رفتار پنهانی وارد نشود. اینجا Docker و دیتابیس لازم نیست.

بخش A: Go ​

راه‌اندازی. از ریشهٔ repository اجرا کنید؛ Go 1.24 یا جدیدتر لازم است. Module، go 1.24 اعلام می‌کند؛ این صفحه با Go 1.27.4 تهیه شده است:

bash
cd docs/snippets/design/clean-code-principles/go
gofmt -l .            # prints nothing
go vet ./...
go test -race -count=1 ./...
# ok  academy/clean-code-principles/after
# ok  academy/clean-code-principles/args
# ok  academy/clean-code-principles/before
# ok  academy/clean-code-principles/core
# ok  academy/clean-code-principles/deep
# ok  academy/clean-code-principles/dry
# ok  academy/clean-code-principles/firsttest
# ok  academy/clean-code-principles/guard
# ok  academy/clean-code-principles/purity

نقطهٔ شروع. before.Proc در تابع‌های کوچک آمده است. پیش از ادامه، مشکل‌ها را فهرست کنید: نام‌های تک‌حرفی it، d، f، c، t، x، y، n، s، v، r؛ آرگومان پرچمی f؛ آرگومان خروجی res *int؛ ساعت پنهان time.Now()؛ hook در سطح package به نام Notify؛ هرم‌های if؛ عددهای جادویی 5000، 700، 1500، 50000؛ و commentهای تکرارکنندهٔ کد.

گام 1: تور ایمنی. Characterization test رفتار فعلی را تثبیت می‌کند: هفت حالت قیمت‌گذاری، سه ورودی نامعتبر و اعلان. توصیفش این است که کد چه می‌کند، نه اینکه چه باید بکند.

go
package before

import (
	"testing"
	"time"
)

// A characterization test: it pins what the code does today, not what it should do.
func TestProcCharacterization(t *testing.T) {
	future := time.Now().Add(time.Hour)
	past := time.Now().Add(-time.Hour)
	cases := []struct {
		name  string
		items []Item
		d     string
		f     bool
		c     string
		exp   time.Time
		want  int
	}{
		{"plain below free shipping", []Item{{1000, 2}}, "", false, "", future, 2000 + 700 + 400},
		{"gold gets 10 percent and free shipping", []Item{{1000, 2}}, "gold", false, "", future, 1800 + 0 + 360},
		{"silver gets 5 percent", []Item{{3000, 2}}, "silver", false, "", future, 5700 + 0 + 1140},
		{"express adds 1500 even for gold", []Item{{1000, 2}}, "gold", true, "", future, 1800 + 1500 + 360},
		{"valid coupon takes 500 off", []Item{{3000, 1}}, "", false, "WELCOME", future, 2500 + 700 + 500},
		{"expired coupon is ignored", []Item{{3000, 1}}, "", false, "WELCOME", past, 3000 + 700 + 600},
		{"coupon needs a 2000 subtotal", []Item{{1500, 1}}, "", false, "WELCOME", future, 1500 + 700 + 300},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var got int
			if err := Proc(tc.items, tc.d, tc.f, tc.c, tc.exp, &got); err != nil {
				t.Fatalf("Proc returned %v", err)
			}
			if got != tc.want {
				t.Errorf("Proc total = %d, want %d", got, tc.want)
			}
		})
	}
}

func TestProcRejectsBadInput(t *testing.T) {
	var out int
	for name, items := range map[string][]Item{
		"empty":     nil,
		"zero qty":  {{100, 0}},
		"neg price": {{-1, 1}},
	} {
		if err := Proc(items, "", false, "", time.Now(), &out); err == nil {
			t.Errorf("%s: want an error, got nil", name)
		}
	}
}

func TestProcNotifiesOnBigOrders(t *testing.T) {
	var calls int
	Notify = func(to, msg string) { calls++ }
	t.Cleanup(func() { Notify = nil })
	var out int
	if err := Proc([]Item{{100000, 1}}, "", false, "", time.Now(), &out); err != nil {
		t.Fatal(err)
	}
	if calls != 1 {
		t.Errorf("notify calls = %d, want 1", calls)
	}
}

گام 2: به چیزها نام بدهید. t به subtotal، d به tier و f به express تغییر نام می‌دهد؛ res در گام 5 حذف می‌شود. تست‌ها را اجرا کنید. این ارزان‌ترین گام است و بیشتر commentها را حذف می‌کند.

گام 3: عددها را نام‌گذاری کنید. 5000، 700، 1500، 500، 2000، 10، 5، 20 و 50000 ثابت‌هایی می‌شوند که نامشان قاعده را می‌گوید: freeShippingThreshold، expressSurcharge، LargeOrderThreshold. آستانهٔ اعلان حالا یک تعریف دارد.

گام 4: برای مجموعه‌های بسته type بسازید. d string به Tier و f bool به Speed تبدیل می‌شود؛ آرگومان پرچمی به type نام‌دار تبدیل شده است. پول Cents می‌شود. کوپن مقدار Coupon است که مقدار صفرش «بدون کوپن» معنی می‌دهد؛ دیگر کسی nil یا "" نمی‌فرستد.

گام 5: آرگومان خروجی را حذف کنید. Proc(..., res *int) error به Quote(now) (Quote, error) تبدیل می‌شود. نتیجه برمی‌گردد و جزئیات subtotal، discount، shipping، tax و total هم همراهش می‌آید.

گام 6: خالصش کنید. time.Now() جای خود را به آرگومان now می‌دهد. متغیر سراسری Notify کاملاً از تابع خارج می‌شود. آنچه باقی می‌ماند هیچ اثر جانبی ندارد.

گام 7: تابع‌ها را در یک سطح انتزاع استخراج کنید. subtotalOf، tierDiscount، couponDiscount و shippingFee، هر کدام با شرط نگهبان. Quote مثل قاعدهٔ قیمت‌گذاری خوانده می‌شود.

گام 8: اثر جانبی را به shell ببرید. Service.PlaceQuote مالک ساعت و Notifier است. فقط همین کد در تست fake می‌خواهد.

وضعیت نهایی:

go
package after

import "fmt"

// Cents is an amount of money in the smallest currency unit.
type Cents int64

func (c Cents) String() string {
	return fmt.Sprintf("%d.%02d", c/100, c%100)
}
go
// Package after is the clean version of before: a pure core (Quote) that
// takes everything it needs as arguments and returns everything it computes.
package after

import (
	"errors"
	"time"
)

// Business rules live in named constants: one place per fact.
const (
	goldDiscountPercent   = 10
	silverDiscountPercent = 5
	taxPercent            = 20

	welcomeCouponCode    = "WELCOME"
	welcomeCouponOff     = Cents(500)
	welcomeCouponMinimum = Cents(2000)

	standardShipping      = Cents(700)
	freeShippingThreshold = Cents(5000)
	expressSurcharge      = Cents(1500)

	// LargeOrderThreshold is the total above which operations is told.
	LargeOrderThreshold = Cents(50000)
)

var (
	ErrNoItems     = errors.New("order has no items")
	ErrBadQuantity = errors.New("quantity must be positive")
	ErrBadPrice    = errors.New("unit price must not be negative")
)

type Tier string

const (
	TierStandard Tier = ""
	TierSilver   Tier = "silver"
	TierGold     Tier = "gold"
)

type Speed int

const (
	SpeedStandard Speed = iota
	SpeedExpress
)

type LineItem struct {
	UnitPrice Cents
	Quantity  int
}

// Coupon's zero value means "no coupon": callers never pass nil.
type Coupon struct {
	Code      string
	ExpiresAt time.Time
}

type Order struct {
	Items  []LineItem
	Tier   Tier
	Speed  Speed
	Coupon Coupon
}

type Quote struct {
	Subtotal, Discount, Shipping, Tax, Total Cents
}

// Quote prices an order. It is pure: the clock arrives as an argument, nothing
// global is read or written, and the same arguments always give the same result.
func (o Order) Quote(now time.Time) (Quote, error) {
	subtotal, err := subtotalOf(o.Items)
	if err != nil {
		return Quote{}, err
	}
	discount := tierDiscount(o.Tier, subtotal) + couponDiscount(o.Coupon, subtotal, now)
	net := subtotal - discount
	shipping := shippingFee(o.Tier, o.Speed, subtotal)
	tax := net * taxPercent / 100
	return Quote{
		Subtotal: subtotal,
		Discount: discount,
		Shipping: shipping,
		Tax:      tax,
		Total:    net + shipping + tax,
	}, nil
}

func subtotalOf(items []LineItem) (Cents, error) {
	if len(items) == 0 {
		return 0, ErrNoItems
	}
	var sum Cents
	for _, it := range items {
		if it.Quantity <= 0 {
			return 0, ErrBadQuantity
		}
		if it.UnitPrice < 0 {
			return 0, ErrBadPrice
		}
		sum += it.UnitPrice * Cents(it.Quantity)
	}
	return sum, nil
}

func tierDiscount(tier Tier, subtotal Cents) Cents {
	switch tier {
	case TierGold:
		return subtotal * goldDiscountPercent / 100
	case TierSilver:
		return subtotal * silverDiscountPercent / 100
	default:
		return 0
	}
}

func couponDiscount(c Coupon, subtotal Cents, now time.Time) Cents {
	if c.Code != welcomeCouponCode {
		return 0
	}
	if !now.Before(c.ExpiresAt) {
		return 0
	}
	if subtotal < welcomeCouponMinimum {
		return 0
	}
	return welcomeCouponOff
}

func shippingFee(tier Tier, speed Speed, subtotal Cents) Cents {
	var fee Cents
	if tier != TierGold && subtotal < freeShippingThreshold {
		fee = standardShipping
	}
	if speed == SpeedExpress {
		fee += expressSurcharge
	}
	return fee
}
go
package after

import "time"

// Notifier is the small interface the shell needs; the caller decides how.
type Notifier interface {
	LargeOrder(total Cents)
}

// Service is the imperative shell: it owns the clock and the side effect.
// Everything with a rule in it stays in Order.Quote.
type Service struct {
	Now      func() time.Time
	Notifier Notifier
}

func (s Service) PlaceQuote(o Order) (Quote, error) {
	q, err := o.Quote(s.Now())
	if err != nil {
		return Quote{}, err
	}
	if q.Total > LargeOrderThreshold {
		s.Notifier.LargeOrder(q.Total)
	}
	return q, nil
}

گام 9: ثابت کنید چیزی عوض نشده است. TestParityWithBefore تعداد 72 ترکیب را از هر دو نسخه عبور می‌دهد: 3 tier، 2 سرعت ارسال، 2 وضعیت کوپن و 6 قیمت؛ سپس totalها را مقایسه می‌کند:

go
package after_test

import (
	"errors"
	"testing"
	"time"

	"academy/clean-code-principles/after"
	"academy/clean-code-principles/before"
)

var noon = time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)

func TestQuoteTotals(t *testing.T) {
	tests := []struct {
		name  string
		order after.Order
		want  after.Cents
	}{
		{"plain below free shipping", after.Order{Items: items(1000, 2)}, 3100},
		{"gold gets 10 percent and free shipping", after.Order{Items: items(1000, 2), Tier: after.TierGold}, 2160},
		{"express adds a surcharge even for gold", after.Order{Items: items(1000, 2), Tier: after.TierGold, Speed: after.SpeedExpress}, 3660},
		{"valid coupon takes 500 off", after.Order{Items: items(3000, 1), Coupon: coupon(noon.Add(time.Hour))}, 3700},
		{"expired coupon is ignored", after.Order{Items: items(3000, 1), Coupon: coupon(noon.Add(-time.Hour))}, 4300},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.order.Quote(noon)
			if err != nil {
				t.Fatalf("Quote() error = %v", err)
			}
			if got.Total != tt.want {
				t.Errorf("Quote().Total = %v, want %v", got.Total, tt.want)
			}
		})
	}
}

func TestQuoteErrorsAreSentinels(t *testing.T) {
	tests := []struct {
		name  string
		items []after.LineItem
		want  error
	}{
		{"no items", nil, after.ErrNoItems},
		{"zero quantity", []after.LineItem{{UnitPrice: 100, Quantity: 0}}, after.ErrBadQuantity},
		{"negative price", []after.LineItem{{UnitPrice: -1, Quantity: 1}}, after.ErrBadPrice},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := after.Order{Items: tt.items}.Quote(noon)
			if !errors.Is(err, tt.want) {
				t.Errorf("Quote() error = %v, want %v", err, tt.want)
			}
		})
	}
}

// The refactoring is safe only if the old behaviour survives: compare both versions.
func TestParityWithBefore(t *testing.T) {
	exp := noon.Add(time.Hour)
	for _, tier := range []string{"", "silver", "gold"} {
		for _, express := range []bool{false, true} {
			for _, code := range []string{"", "WELCOME"} {
				for _, price := range []int{1, 999, 2000, 4999, 5000, 40000} {
					var old int
					if err := before.Proc([]before.Item{{P: price, Q: 1}}, tier, express, code, exp.Add(time.Hour*24*365*10), &old); err != nil {
						t.Fatal(err)
					}
					o := after.Order{
						Items:  items(after.Cents(price), 1),
						Tier:   after.Tier(tier),
						Coupon: after.Coupon{Code: code, ExpiresAt: exp.Add(time.Hour * 24 * 365 * 10)},
					}
					if express {
						o.Speed = after.SpeedExpress
					}
					got, err := o.Quote(noon)
					if err != nil {
						t.Fatal(err)
					}
					if int(got.Total) != old {
						t.Errorf("tier=%q express=%v code=%q price=%d: after=%d before=%d", tier, express, code, price, got.Total, old)
					}
				}
			}
		}
	}
}

type recordingNotifier struct{ totals []after.Cents }

func (r *recordingNotifier) LargeOrder(total after.Cents) { r.totals = append(r.totals, total) }

func TestServiceNotifiesOnlyAboveTheThreshold(t *testing.T) {
	n := &recordingNotifier{}
	svc := after.Service{Now: func() time.Time { return noon }, Notifier: n}

	if _, err := svc.PlaceQuote(after.Order{Items: items(1000, 1)}); err != nil {
		t.Fatal(err)
	}
	if len(n.totals) != 0 {
		t.Fatalf("small order notified: %v", n.totals)
	}
	if _, err := svc.PlaceQuote(after.Order{Items: items(100000, 1)}); err != nil {
		t.Fatal(err)
	}
	if len(n.totals) != 1 {
		t.Fatalf("large order notifications = %d, want 1", len(n.totals))
	}
}

func TestCentsString(t *testing.T) {
	if got, want := after.Cents(3105).String(), "31.05"; got != want {
		t.Errorf("Cents(3105).String() = %q, want %q", got, want)
	}
}

func items(price after.Cents, qty int) []after.LineItem {
	return []after.LineItem{{UnitPrice: price, Quantity: qty}}
}

func coupon(expires time.Time) after.Coupon {
	return after.Coupon{Code: "WELCOME", ExpiresAt: expires}
}

گام 10: اندازه بگیرید. شمارش دستی با قواعد بخش معیارهای پیچیدگی؛ ابزارها برای این صفحه اجرا نشده‌اند، طبق توضیح پایین.

معیارقبل، Procبعد، Quote و helperها
بلندترین تابع52 خط17 خط، Order.Quote
پیچیدگی دوری، شمارش دستی15حداکثر 5، subtotalOf
پیچیدگی شناختی، شمارش دستی با قواعد Sonarحدود 24حداکثر حدود 6
متغیر تغییرپذیر در سطح package1، Notify0
آرگومان تابع اصلی6، شامل pointer خروجی1، به اضافهٔ receiver
ورودی پنهانساعت، hook سراسریدر Quote هیچ؛ هر دو در Service
نسخه‌های آستانهٔ سفارش بزرگ1 literal1 ثابت
تست قواعد fake می‌خواهدبله، patch سراسرینه، struct و ساعت
تست توصیفی و برابریپاسپاس؛ 72 ترکیب برابر

گام 11، اختیاری، نتیجهٔ مورد انتظار و اجرا‌نشده: اعمال محدودیت. ابزارها را بیرون module نصب کنید: go install github.com/fzipp/gocyclo/cmd/gocyclo@latest و go install github.com/uudashr/gocognit/cmd/gocognit@latest؛ سپس اجرا کنید:

bash
gocyclo -over 10 ./before ./after
# expected: before/order.go ... Proc ... (15 by hand count) and nothing from ./after
gocognit -over 10 ./before ./after
# expected: Proc only
golangci-lint run --enable gocognit,gocyclo,funlen,nestif,unparam ./...
# expected: nestif and gocognit on before.Proc; nothing on after

بخش B: Laravel ​

همان قواعد قیمت‌گذاری در اپ Laravel 13 روی PHP 8.3 یا جدیدتر. فایل‌های PHP فقط با php -l بررسی شده‌اند و داخل اپ اجرا نشده‌اند. Route این است: Route::post('/quote', QuoteController::class) در routes/api.php.

نقطهٔ شروع. متد calc همه‌چیز را از $request->all() می‌خواند، از helper ساعت now() استفاده می‌کند، مستقیم ایمیل می‌فرستد، پرچم $x می‌گیرد و یک ساختار آرایهٔ خام برمی‌گرداند:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class OrderController extends Controller
{
    // computes the total
    public function calc(Request $r, $x = false)
    {
        $d = $r->all();
        $t = 0;
        foreach ($d['items'] as $i) {
            if ($i['q'] > 0) {
                if ($i['p'] >= 0) {
                    $t += $i['p'] * $i['q'];
                } else {
                    return response()->json(['error' => 'bad price'], 422);
                }
            } else {
                return response()->json(['error' => 'bad qty'], 422);
            }
        }
        $disc = 0;
        if ($d['tier'] == 'gold') {
            $disc = intdiv($t * 10, 100);
        } elseif ($d['tier'] == 'silver') {
            $disc = intdiv($t * 5, 100);
        }
        $c = 0;
        if (($d['coupon'] ?? null) == 'WELCOME' && now()->lt($d['expires'])) {
            if ($t >= 2000) {
                $c = 500;
            }
        }
        $n = $t - $disc - $c;
        $s = 0;
        if ($d['tier'] != 'gold' && $t < 5000) {
            $s = 700;
        }
        if ($x) {
            $s += 1500;
        }
        $res = $n + $s + intdiv($n * 20, 100);
        if ($res > 50000) {
            Mail::raw('big order', fn ($m) => $m->to('ops@example.test'));
        }

        return response()->json(['total' => $res]);
    }
}

گام 1: Characterization test برای controller با تست HTTP لاراول: $this->postJson('/quote', ...)->assertJson(['total' => 3100]). برای کوپن helperهای سفر در زمان Laravel و برای سفارش بزرگ Mail::fake() را استفاده کنید. اول آن‌ها را بنویسید و سبز نگهشان دارید.

گام 2: یک backed enum برای مجموعهٔ بسته که مقایسهٔ رشته‌ها را جایگزین می‌کند و قاعدهٔ متعلق به خودش را حمل می‌کند:

php
<?php

namespace App\Orders;

enum Tier: string
{
    case Standard = '';
    case Silver = 'silver';
    case Gold = 'gold';

    public function discountPercent(): int
    {
        return match ($this) {
            self::Gold => 10,
            self::Silver => 5,
            self::Standard => 0,
        };
    }

    public function shipsFree(): bool
    {
        return $this === self::Gold;
    }
}

گام 3: یک value object با readonly برای نتیجه؛ final readonly class در PHP 8.2:

php
<?php

namespace App\Orders;

/** A priced order. All amounts are integer cents. */
final readonly class Quote
{
    public function __construct(
        public int $subtotal,
        public int $discount,
        public int $shipping,
        public int $tax,
        public int $total,
    ) {}
}

گام 4: محاسبه‌گر خالص. نه facade دارد، نه now() و نه ایمیل. ساعت آرگومان است و ورودی نامعتبر InvalidArgumentException می‌اندازد. ثابت نام‌دار جای هر literal را می‌گیرد:

php
<?php

namespace App\Orders;

use DateTimeImmutable;
use InvalidArgumentException;

/**
 * Pure pricing rules: no facade, no clock, no mail. The caller passes "now",
 * so a unit test can choose the answer without booting the framework.
 */
final class QuoteCalculator
{
    private const TAX_PERCENT = 20;
    private const WELCOME_CODE = 'WELCOME';
    private const WELCOME_OFF = 500;
    private const WELCOME_MINIMUM = 2000;
    private const STANDARD_SHIPPING = 700;
    private const FREE_SHIPPING_FROM = 5000;
    private const EXPRESS_SURCHARGE = 1500;

    /**
     * @param  list<array{price: int, quantity: int}>  $items
     */
    public function quote(
        array $items,
        Tier $tier,
        bool $express,
        ?string $couponCode,
        DateTimeImmutable $couponExpiresAt,
        DateTimeImmutable $now,
    ): Quote {
        $subtotal = $this->subtotal($items);
        $discount = intdiv($subtotal * $tier->discountPercent(), 100)
            + $this->couponDiscount($couponCode, $couponExpiresAt, $subtotal, $now);
        $net = $subtotal - $discount;
        $shipping = $this->shipping($tier, $express, $subtotal);
        $tax = intdiv($net * self::TAX_PERCENT, 100);

        return new Quote($subtotal, $discount, $shipping, $tax, $net + $shipping + $tax);
    }

    private function subtotal(array $items): int
    {
        if ($items === []) {
            throw new InvalidArgumentException('Order has no items.');
        }

        $sum = 0;
        foreach ($items as $item) {
            if ($item['quantity'] <= 0) {
                throw new InvalidArgumentException('Quantity must be positive.');
            }
            if ($item['price'] < 0) {
                throw new InvalidArgumentException('Unit price must not be negative.');
            }
            $sum += $item['price'] * $item['quantity'];
        }

        return $sum;
    }

    private function couponDiscount(?string $code, DateTimeImmutable $expiresAt, int $subtotal, DateTimeImmutable $now): int
    {
        if ($code !== self::WELCOME_CODE) {
            return 0;
        }
        if ($now >= $expiresAt) {
            return 0;
        }
        if ($subtotal < self::WELCOME_MINIMUM) {
            return 0;
        }

        return self::WELCOME_OFF;
    }

    private function shipping(Tier $tier, bool $express, int $subtotal): int
    {
        $fee = (! $tier->shipsFree() && $subtotal < self::FREE_SHIPPING_FROM) ? self::STANDARD_SHIPPING : 0;

        return $express ? $fee + self::EXPRESS_SURCHARGE : $fee;
    }
}

گام 5: تست سادهٔ PHPUnit برای آن. از PHPUnit\Framework\TestCase ارث می‌برد، نه TestCase لاراول، چون هیچ‌چیز container نمی‌خواهد؛ پس در میلی‌ثانیه اجرا می‌شود:

php
<?php

namespace Tests\Unit;

use App\Orders\QuoteCalculator;
use App\Orders\Tier;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;

/** A plain PHPUnit TestCase: the calculator needs no container, so this is fast. */
class QuoteCalculatorTest extends TestCase
{
    private const NOON = '2026-03-01 12:00:00';

    public function test_plain_order_below_free_shipping(): void
    {
        $quote = $this->calculate([['price' => 1000, 'quantity' => 2]], Tier::Standard);

        $this->assertSame(3100, $quote->total);
    }

    public function test_gold_gets_discount_and_free_shipping_but_pays_for_express(): void
    {
        $quote = $this->calculate([['price' => 1000, 'quantity' => 2]], Tier::Gold, express: true);

        $this->assertSame(3660, $quote->total);
    }

    public function test_expired_coupon_is_ignored(): void
    {
        $quote = $this->calculate(
            [['price' => 3000, 'quantity' => 1]],
            Tier::Standard,
            coupon: 'WELCOME',
            expires: '2026-03-01 11:00:00',
        );

        $this->assertSame(4300, $quote->total);
    }

    public function test_empty_order_is_rejected(): void
    {
        $this->expectException(InvalidArgumentException::class);

        $this->calculate([], Tier::Standard);
    }

    private function calculate(array $items, Tier $tier, bool $express = false, ?string $coupon = null, string $expires = '2026-03-01 13:00:00')
    {
        return (new QuoteCalculator)->quote(
            $items,
            $tier,
            $express,
            $coupon,
            new DateTimeImmutable($expires),
            new DateTimeImmutable(self::NOON),
        );
    }
}

گام 6: اعتبارسنجی در مرز. Form Request شکل ورودی را اعتبارسنجی می‌کند تا محاسبه‌گر بتواند روی آن حساب کند:

php
<?php

namespace App\Http\Requests;

use App\Orders\Tier;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/** Input validation lives here, at the edge, not inside the pricing rules. */
class QuoteOrderRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'items' => ['required', 'array', 'min:1'],
            'items.*.price' => ['required', 'integer', 'min:0'],
            'items.*.quantity' => ['required', 'integer', 'min:1'],
            'tier' => ['sometimes', Rule::enum(Tier::class)],
            'express' => ['sometimes', 'boolean'],
            'coupon' => ['nullable', 'string'],
            'coupon_expires_at' => ['nullable', 'date'],
        ];
    }
}

گام 7: controller باریک و event برای اثر جانبی. Controller قابل‌فراخوانی shell است. ایمیل دیگر همان‌جا ارسال نمی‌شود؛ listener می‌تواند مشترک LargeOrderQuoted شود و خود listener هم می‌تواند صف‌بندی شود:

php
<?php

namespace App\Http\Controllers;

use App\Http\Requests\QuoteOrderRequest;
use App\Orders\LargeOrderQuoted;
use App\Orders\QuoteCalculator;
use App\Orders\Tier;
use DateTimeImmutable;
use Illuminate\Http\JsonResponse;

/** The imperative shell: read the request, call the core, publish the side effect. */
class QuoteController extends Controller
{
    private const LARGE_ORDER_FROM = 50000;

    public function __invoke(QuoteOrderRequest $request, QuoteCalculator $calculator): JsonResponse
    {
        $now = new DateTimeImmutable('now');
        $quote = $calculator->quote(
            items: $request->validated('items'),
            tier: Tier::from($request->validated('tier', '')),
            express: $request->boolean('express'),
            couponCode: $request->validated('coupon'),
            couponExpiresAt: new DateTimeImmutable($request->validated('coupon_expires_at') ?? '@0'),
            now: $now,
        );

        if ($quote->total > self::LARGE_ORDER_FROM) {
            LargeOrderQuoted::dispatch($quote->total);
        }

        return response()->json(['total' => $quote->total]);
    }
}
php
<?php

namespace App\Orders;

use Illuminate\Foundation\Events\Dispatchable;

final class LargeOrderQuoted
{
    use Dispatchable;

    public function __construct(public readonly int $total) {}
}

گام 8: ابزارها.

bash
./vendor/bin/pint --test              # style
./vendor/bin/phpstan analyse          # types (start at the level the code passes)
./vendor/bin/phpmd app text phpmd.xml # complexity and argument count
php artisan test                      # the characterization tests from step 1
# all four: expected, not run

محدودیت‌های صریح آزمایشگاه. کد Go کامپایل، vet و تست شده است؛ عددهای پیچیدگی دستی شمرده شده‌اند؛ PHP فقط از نظر syntax بررسی شده است. همچنین Tier::from(...) در controllerِ after برای tier ناشناخته exception می‌اندازد، در حالی که کد قدیمی بی‌صدا آن را standard می‌گرفت. این تغییر رفتار است؛ Characterization test آن را می‌گیرد و باید commit خودش را داشته باشد.

بدفهمی‌های رایج ​

باورواقعیت
کد تمیز یعنی تابع کوتاهیعنی تابع در یک سطح انتزاع با رابط ساده؛ علامت خطر Ousterhout رفت‌وبرگشت بین دو تابع برای فهم یک ایده است
DRY یعنی خط تکراری نداشته باشیمیعنی دانش تکراری نداشته باشیم؛ کد شبیهی که به دلایل متفاوت تغییر می‌کند جدا می‌ماند
Comment همیشه شکست استبازگویی کد نویز است؛ توضیح چرایی، محدودیت و دام مستندات طراحی است؛ دو کتاب تا اینجا توافق دارند
یک return در هر تابع تمیزتر استدر Go و PHP شرط نگهبان و بازگشت زودهنگام مسیر موفق را کنار حاشیه نگه می‌دارد؛ برای پاک‌سازی defer یا finally بگذارید
YAGNI یعنی طراحی نکنقابلیت فرضی نساز؛ با تست و refactoring تغییر کد را آسان نگه دار
KISS یعنی راه‌حل ساده‌لوحانهساده‌ترین راهی که نیاز شناخته‌شده را برآورده می‌کند، از جمله پول صحیح و ساعت قابل‌کنترل
Formatter و linter کد را تمیز می‌کنندبحث سبک را تمام می‌کنند و چند بو را می‌گیرند؛ نام، انتزاع و مرز هنوز قضاوت می‌خواهند
تابع خالص کار مفیدی نمی‌کندبرنامه اثر لازم دارد؛ خلوص دربارهٔ جای تصمیم‌گیری است: هستهٔ تابعی، پوستهٔ دستوری
پیچیدگی دوری کم یعنی خواناییمسیر را می‌شمارد، نه نام را؛ switch تخت امتیاز زیاد دارد ولی خواناست، تابع عمیقاً تودرتو ممکن است امتیاز کم بگیرد
Struct در Go اگر با مقدار پاس داده شود immutable استفیلد slice و map هنوز حافظهٔ مشترک دارند؛ محتوا را کپی یا فیلد را پنهان کنید
Interface برای هر وابستگی تمیز استیک پیاده‌سازی و یک mock کلی‌سازی حدسی است؛ interface را جایی اضافه کنید که پیاده‌سازی دوم وجود دارد
کد تست می‌تواند شلخته باشدوقتی چیزی خراب است خوانده می‌شود؛ پیام شکست باید input، got و want را بگوید و تست سریع و مستقل اجرا شود
CQS و CQRS یکی هستندCQS قاعدهٔ سطح متد است؛ CQRS الگوی معماری با ایده‌ای مرتبط
هم‌زمان با رفع باگ refactor کن تا وقت ذخیره شودCommit مخلوط، رفع باگ را دفن و بازبینی و revert را سخت می‌کند؛ گام قانون اردوگاه commit جدا داشته باشد

چکیده ​

موضوعبه خاطر بسپارید
نام‌ها (Names)گویا، قابل‌جست‌وجو، یک واژه برای هر مفهوم؛ Go: کوتاه در محدودهٔ کوچک، MixedCaps، بدون پیشوند Get؛ PHP: PSR-1 و PSR-12
قالب‌بندی (Formatting)gofmt -l . هیچ چاپ نکند؛ pint --test پاس شود؛ در بازبینی دربارهٔ فاصله بحث نکنید
شکل تابع (Function shape)یک سطح انتزاع؛ نام‌گذاری بدون «و»؛ جداسازی قصد از پیاده‌سازی، نه تقسیم با تعداد خط
آرگومان‌ها (Arguments)پیش‌فرض با مقدار صفر، option struct یا آرگومان نام‌دار؛ بدون آرگومان flag، null یا خروجی
خلوص (Purity)آرگومان یکسان، نتیجهٔ یکسان، بدون اثر جانبی؛ ساعت، config و تصادف آرگومان هستند
اثر جانبی (Side effect)در مرز: functional core و imperative shell؛ shell به fake نیاز دارد
CQSQuery جواب می‌دهد و هرگز تغییر نمی‌دهد؛ command تغییر می‌دهد و چیزی برنمی‌گرداند؛ استثناها: pop و عملیات اتمیک
تکرارپذیری بی‌اثر (Idempotence)Command قابل‌retry کلید یا عملیات از نوع set لازم دارد
خطاها (Errors)اول guard clause، مسیر موفق کنار حاشیه؛ wrap با %w، context را یک بار اضافه کنید؛ یک مدل خطا در هر لایه
Commentکد را بازگو نکنید، چرایی را بگویید، کد commentشده را حذف کنید
DRYیک واقعیت، یک جا؛ دانش را ادغام کنید نه شکل را؛ قاعدهٔ سه
YAGNI و KISSنیاز امروز را بسازید؛ نقطهٔ تعویض فقط جایی که پیاده‌سازی دوم هست
ماژول عمیق (Deep module)رابط باریک و جزئیات پنهان زیاد؛ ریزتابع کم‌عمق بو است
پیچیدگی (Complexity)gocyclo و gocognit از 10 تا 20 برای کد جدید، ratchet برای کد قدیمی؛ CyclomaticComplexity در PHPMD برابر 10
ابزارها (Tools)golangci-lint v2 با version: "2"؛ Pint و PHPStan از 0 تا 10 یا Psalm از 8 تا 1 در CI
تست‌ها (Tests)FIRST: سریع، مستقل، تکرارپذیر، خودارزیاب و به‌موقع؛ پیام، input و got و want را بگوید
بازبینی (Review)پس از سبز شدن ابزارها، چک‌لیست 13 پرسشی را به کار ببرید

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — چه چیزی تابع را خالص می‌کند و چرا برای تست مهم است؟ حیاتی ​

پاسخ

پاسخ: نتیجهٔ تابع خالص (Pure function) فقط به آرگومان‌هایش وابسته است و اثر جانبی ندارد: نه نوشتن، نه I/O، نه ساعت و نه متغیر سراسری. حاصل، شفافیت ارجاعی (Referential transparency) است؛ فراخوانی را می‌توان با مقدارش جایگزین کرد. تست fake نمی‌خواهد، نتیجه قابل‌cache است و اجرای موازی امن می‌ماند. در آزمایشگاه Order.Quote(now) خالص است چون ساعت آرگومان شده؛ تابع‌های خالص را ببینید.

۲ — هستهٔ تابعی و پوستهٔ دستوری را با مثال توضیح دهید؟ حیاتی ​

پاسخ

پاسخ: تصمیم‌ها در هستهٔ تابعی (Functional core) هستند: تابع‌های خالصی که مقدار می‌گیرند و مقدار می‌دهند. پوستهٔ دستوری (Imperative shell) باریک، ورودی درخواست، ساعت و دیتابیس را می‌خواند، core را صدا می‌زند و اثرها را انجام می‌دهد. در آزمایشگاه Order.Quote هسته است و Service.PlaceQuote پوستهٔ مالک ساعت و Notifier؛ فقط پوسته fake لازم دارد. هستهٔ تابعی را ببینید.

۳ — چه زمانی کد تکراری را استخراج می‌کنید؟ حیاتی ​

پاسخ

پاسخ: وقتی دانش تکراری است، یعنی همان قاعده‌ای که باید همیشه یکسان بماند؛ و به‌عنوان راهنما در تکرار سوم، طبق قاعدهٔ سه (Rule of three). کدهای شبیه که به دلایل متفاوت تغییر می‌کنند باید جدا بمانند؛ ادغامشان انتزاع غلطی می‌سازد که مدام آرگومان پرچمی اضافه می‌کند. واقعیت مشترک، یعنی روش نوشتن مبلغ، یک بار استخراج می‌شود؛ مثل packageِ dry. DRY را ببینید.

۴ — چرا آرگومان پرچمی بو است و چه چیزی جایش را می‌گیرد؟ حیاتی ​

پاسخ

پاسخ: آرگومان پرچمی (Flag argument) با یک boolean از تابع می‌خواهد عملیات دیگری انجام دهد، ولی Render(r, true) در محل فراخوانی نمی‌گوید کدام عملیات. Fowler: "My general reaction to flag arguments is to avoid them." جایگزینش دو تابع نام‌دار، یعنی RenderSummary و RenderDetail، یا type نام‌داری مثل Speed است. آرگومان‌ها را ببینید.

۵ — شرط نگهبان یا if تودرتو؛ Effective Go و Code Review Comments چه می‌گویند؟ حیاتی ​

پاسخ

پاسخ: شرط نگهبان (Guard clause). Effective Go می‌گوید خواندن کد خوب پیش می‌رود "if the successful flow of control runs down the page, eliminating error cases as they arise"؛ Code Review Comments هم می‌گوید مسیر عادی کمترین تورفتگی را داشته باشد و اول به خطا رسیدگی کنید. با defer جلوی نشت منابع در بازگشت زودهنگام را بگیرید. مدیریت خطا و مسیر موفق را ببینید.

۶ — جداسازی فرمان و پرس‌وجو چیست و کی آن را می‌شکنید؟ مهم ​

پاسخ

پاسخ: در جداسازی فرمان و پرس‌وجو (Command-query separation)، query نتیجه می‌دهد و وضعیت مشاهده‌پذیر را عوض نمی‌کند؛ command وضعیت را عوض می‌کند و چیزی برنمی‌گرداند. بنابراین query را هر جا و با هر ترتیبی می‌توان فراخوانی کرد. استثناهای Fowler عملیات نیازمند اتمیک بودن‌اند، مثل pop پشته یا get-and-increment اتمیک؛ جدا کردنشان غلط است. CQS و Idempotence را ببینید.

۷ — تفاوت idempotent و pure چیست؟ مهم ​

پاسخ

پاسخ: خلوص (Purity) یعنی قطعی بودن نتیجه بر اساس آرگومان‌ها و نداشتن اثر جانبی. تکرارپذیری بی‌اثر (Idempotence) ویژگی مستقلی است: اثر دو بار اعمال عملیات با یک بار برابر باشد، یعنی f(f(x)) = f(x). تابع خالص لازم نیست idempotent باشد؛ x + 1 خالص است ولی f(f(x)) با f(x) فرق دارد. Commandِ idempotent می‌تواند اثر جانبی داشته باشد، مثل تنظیم وضعیت یا insert با کلید یکتا؛ همین ویژگی retry را امن می‌کند.

۸ — پیچیدگی دوری و شناختی چه فرقی دارند و با چه ابزاری سنجیده می‌شوند؟ مهم ​

پاسخ

پاسخ: پیچیدگی دوری (Cyclomatic complexity) مسیرهای مستقل را می‌شمارد؛ در gocyclo پایهٔ 1 به اضافهٔ هر if، for، case، && و ||. پیچیدگی شناختی (Cognitive complexity) در Sonar و gocognit برای تودرتویی بیشتر امتیاز می‌دهد و switch را یک بار حساب می‌کند، پس سختی خواندن را دنبال می‌کند. پیش‌فرض هر دو در golangci-lint عدد 30 و پیشنهادش 10 تا 20 است؛ PHPMD از 10 برای CyclomaticComplexity گزارش می‌دهد. معیارهای پیچیدگی را ببینید.

۹ — Clean Code و A Philosophy of Software Design کجا اختلاف دارند؟ مهم ​

پاسخ

پاسخ: در طول متد و comment. Martin تابع بسیار کوچک را ترجیح می‌دهد و comment را شکست در بیان منظور می‌نامد؛ Ousterhout می‌گوید خرد کردن زیاد، متد کم‌عمق و درهم‌تنیده می‌سازد و comment اطلاعات طراحی‌ای را منتقل می‌کند که کد قادر به بیانش نیست. هر دو قبول دارند خرد کردن افراطی ممکن است و comment تکرارکنندهٔ کد نویز است. ماژول‌های عمیق را ببینید.

۱۰ — YAGNI چیست و چه چیزهایی را منع نمی‌کند؟ مهم ​

پاسخ

پاسخ: قابلیت فرضی نسازید؛ حدس ممکن است غلط باشد و حتی حدس درست هزینهٔ تأخیر و حمل دارد. YAGNI طراحی، refactoring یا باقی گذاشتن نقطهٔ تعویض کوچک در حضور پیاده‌سازی دوم را منع نمی‌کند. فرض آن وجود تست‌هایی است که تغییر بعدی را ارزان کنند. YAGNI و KISS را ببینید.

۱۱ — برای سرویس Go و اپ Laravel چه ابزارهایی در CI می‌گذارید؟ مهم ​

پاسخ

پاسخ: در Go، gofmt -l . که باید هیچ چاپ نکند، go vet، golangci-lint v2 با gocognit، gocyclo، funlen، nestif، unparam، errorlint و ratchetِ new-from-rev، همراه go test -race. در Laravel، pint --test، PHPStan یا Psalm در سطحی که کد با baseline پاس می‌شود، آستانه‌های PHPMD و php artisan test. اتصال همه‌چیز به CI را ببینید.

۱۲ — اصول FIRST از تست چه می‌خواهند؟ تکمیلی ​

پاسخ

پاسخ: سریع (Fast)، مستقل (Independent)، تکرارپذیر (Repeatable)، خودارزیاب (Self-validating) و به‌موقع (Timely). در عمل شبکه و ساعت واقعی نداشته باشد، به state مشترک یا ترتیب وابسته نباشد، مقایسهٔ ساده داشته باشد و پیام شکستش طبق راهنمای Go، ورودی، got و want را نام ببرد. تست‌های تمیز را ببینید.

۱۳ — چرا struct در Go با پاس دادن به‌صورت مقدار خودبه‌خود immutable نمی‌شود؟ تکمیلی ​

پاسخ

پاسخ: کپی، فیلدها را تکثیر می‌کند، ولی فیلدهای slice و map هنوز به حافظهٔ اصلی اشاره می‌کنند؛ پس نوشتن از راه کپی برای فراخواننده هم دیده می‌شود. تغییرناپذیری (Immutability) کپی دفاعی می‌خواهد، مثل Cart.WithItem، یا فیلد پنهانی که mutator ندارد. تغییرناپذیری را ببینید.

واژه‌نامه ​

اصطلاحمعنی
Clean Code از Robert C. Martinکتاب سال 2008 دربارهٔ نام‌گذاری، تابع کوچک و comment؛ مواضع Clean Code از نقل‌های Ousterhout گرفته شده و اینجا فقط از صفحه‌های مطالعه‌شده نقل می‌شود
A Philosophy of Software Design از John Ousterhoutکتاب مدافع ماژول عمیق و comment به‌عنوان مستندات طراحی؛ وزنهٔ مقابل Clean Code
نام‌گذاری (Naming)انتخاب شناسه‌ای که هدف را بگوید؛ ارزان‌ترین و ارزشمندترین عادت کد تمیز
نام گویای قصد (Intention-revealing names)نام بگوید چیزی برای چیست، نه چگونه پیاده شده یا چه typeای دارد
نام قابل‌جست‌وجو (Searchable names)به‌اندازه‌ای متمایز که جست‌وجوی متن همان مفهوم را پیدا کند و نه چیز دیگر
واژگان یکدست (Consistent vocabulary)یک واژه برای هر مفهوم در کل کد؛ نه fetch، get و load برای یک چیز
قالب‌بندی (Formatting)چیدمان متن کد؛ با formatter حل می‌شود، نه بحث
gofmtFormatter استاندارد Go؛ flagهای -l برای فهرست، -d برای diff، -w برای نوشتن، -s برای ساده‌سازی و -r برای قاعدهٔ بازنویسی
Laravel Pintاصلاح‌گر سبک PHP با انتخاب‌های ازپیش‌تعیین‌شده، ساخته‌شده روی PHP CS Fixer و نصب‌شده با اپ تازهٔ Laravel؛ presetهای laravel، per، psr12، symfony و empty
PSR-12سبک توسعه‌یافتهٔ PHP-FIG؛ 4 فاصله، LF، حد نرم 120 نویسه
PER Coding Styleسبک در حال تکامل PHP-FIG که "extends, expands and replaces PSR-12"
تابع‌های کوچک (Small functions)تابع آن‌قدر کوتاه باشد که با یک نگاه فهمیده شود؛ هدف روشنی است، نه شمارش خط
یک سطح انتزاع (One level of abstraction)همهٔ دستورهای تابع در یک ارتفاع مفهومی هستند
مسئولیت واحد در سطح تابع (Single responsibility at function level)تابع یک دلیل برای تغییر دارد؛ همتای کوچک SRP
تعداد آرگومان‌ها (Arguments count)تعداد پارامترها؛ زیاد بودن پارامترهای هم‌نوع جابه‌جایی اشتباه را آسان می‌کند
آرگومان پرچمی (Flag arguments)پارامتر boolean که بین دو رفتار انتخاب می‌کند؛ با دو تابع جایگزینش کنید
آرگومان تهی (Null arguments)پاس دادن nil یا null به معنی «هیچ»؛ مقدار صفر معنادار یا type را ترجیح دهید
آرگومان خروجی (Output arguments)پارامتری که تابع نتیجه را داخلش می‌نویسد؛ به جایش نتیجه را برگردانید
ساختار گزینه‌ها (Option struct)Struct جمع‌کنندهٔ آرگومان‌ها تا محل فراخوانی نام آن‌ها را بگوید و مقدار صفر به معنی پیش‌فرض باشد
تابع خالص (Pure functions)نتیجه فقط به آرگومان‌ها وابسته است و اثر جانبی ندارد
اثر جانبی (Side effects)هر تغییر مشاهده‌پذیر فراتر از مقدار بازگشتی: نوشتن، I/O، خواندن ساعت، تغییر داده، log
شفافیت ارجاعی (Referential transparency)جایگزینی فراخوانی با نتیجهٔ آن بدون تغییر برنامه
جداسازی فرمان و پرس‌وجو (Command-query separation)متد یا وضعیت را عوض می‌کند، command، یا سؤال را جواب می‌دهد، query؛ نه هر دو؛ از Bertrand Meyer
CQRSCommand Query Responsibility Segregation؛ معماری جداسازی مدل خواندن و نوشتن؛ مرتبط با CQS ولی متفاوت
تکرارپذیری بی‌اثر (Idempotence)اثر دو بار اعمال عملیات برابر یک بار است
کلید تکرارپذیری بی‌اثر (Idempotency key)شناسه‌ای از طرف فراخواننده تا سرور command تکراری را نادیده بگیرد
تغییرناپذیری (Immutability)مقدار پس از ساخت عوض نمی‌شود؛ «تغییر» مقدار تازه برمی‌گرداند
معنای مقداری (Value semantics)کپی مقدار، مقداری مستقل می‌دهد؛ مراقب slice و map در Go باشید
هستهٔ تابعی، پوستهٔ دستوری (Functional core imperative shell)کد تصمیم‌گیری خالص درون لایهٔ نازک انجام‌دهندهٔ I/O و اثرها
مدیریت خطا و مسیر موفق (Error handling vs happy path)اول رسیدگی به شکست تا جریان موفق مستقیم تا پایین خوانده شود
استثنا و مقدار خطا (Exceptions vs error values)دو مدل خطا: throw و catch در PHP، در برابر return و check در Go؛ در یک لایه مخلوط نکنید
بازگشت زودهنگام (Early return)به‌محض معلوم شدن نتیجه یا شکست برگردید
شرط نگهبان (Guard clauses)if ابتدایی که وضعیت نامعتبر را بالای تابع رد می‌کند
خطای نشانگر (Sentinel error)مقدار خطا در سطح package، مثل ErrNotPaid، که فراخواننده با errors.Is مقایسه می‌کند
Comment در برابر کد خودتوضیح (Comments vs self-documenting code)بحث دربارهٔ چیزی که کد می‌گوید و چیزی که فقط comment می‌گوید؛ چرایی
کد مرده (Dead code)کدی که اجرا نمی‌شود یا نتیجه‌اش مصرف نمی‌شود؛ شامل کد commentشده
تکرار (Duplication)کد یکسان یا دانش یکسان در چند جا؛ فقط نوع دوم الزاماً باید ادغام شود
DRYDon't Repeat Yourself؛ یک نمایش معتبر برای هر دانش
WETمقابل DRY؛ "write everything twice"
قاعدهٔ سه (Rule of three)دو نمونهٔ شبیه را تحمل کنید؛ در سومی استخراج کنید
انتزاع غلط (Wrong abstraction)تابع مشترک با flagها خم شده تا نیاز فراخواننده‌های واگرا را پاسخ دهد
YAGNIYou Aren't Gonna Need It؛ قابلیت فرضی نسازید
KISSKeep It Simple, Stupid؛ سادگی به‌عنوان هدف طراحی
انتزاع زودهنگام (Premature abstraction)انتزاعی که پیش از وجود موارد واقعی برای تعمیم ساخته شده
کلی‌سازی حدسی (Speculative generality)Hook، interface یا پارامتر «برای شاید»؛ یکی از بوهای Fowler
قانون اردوگاه (Boy scout rule)کد را کمی تمیزتر از چیزی که یافتید رها کنید
Framework در مرز (Framework at the edge)Controller، مدل ORM و SDK در مرز بمانند تا قواعد importشان نکنند
جهت وابستگی (Dependency direction)وابستگی کد منبع از جزئیات به سمت سیاست باشد
انسجام (Cohesion)شدت تعلق اجزای ماژول به یکدیگر
وابستگی بین ماژول‌ها (Coupling)میزان وابستگی ماژول به جزئیات ماژول دیگر
ماژول عمیق (Deep modules)رابط باریک که کارکرد فراوانی را پنهان می‌کند
ماژول کم‌عمق (Shallow modules)رابطی تقریباً هم‌پیچیدگی پیاده‌سازی
درهم‌تنیدگی (Entanglement)دو متد که بدون خواندن یکدیگر فهمیده نمی‌شوند
پیچیدگی دوری (Cyclomatic complexity)تعداد مسیرهای مستقل تابع؛ 1 به اضافهٔ هر نقطهٔ تصمیم
پیچیدگی شناختی (Cognitive complexity)معیار فهم‌پذیری Sonar؛ افزایش با شکست جریان خطی و افزایش بیشتر با تودرتویی
پیچیدگی مسیر بی‌چرخه (NPath complexity)تعداد مسیرهای اجرای بی‌چرخهٔ یک متد در PHPMD
gocycloابزار Go برای محاسبهٔ پیچیدگی دوری؛ یکی از linterهای golangci-lint هم هست
gocognitابزار Go برای محاسبهٔ پیچیدگی شناختی؛ یکی از linterهای golangci-lint هم هست
golangci-lintاجراکنندهٔ linterهای Go؛ تنظیم v2 با version: "2" شروع می‌شود و linters: و formatters: دارد
funlen، nestifLinterهای golangci-lint برای طول تابع، 60 خط و 40 دستور، و if تودرتو، 5
PHPMDPHP Mess Detector؛ قواعد اندازه و پیچیدگی مثل CyclomaticComplexity و ExcessiveParameterList
PHPStanتحلیل‌گر ایستای PHP با سطح 0 آسان‌ترین تا 10 سخت‌گیرترین
Psalmتحلیل‌گر ایستای PHP با سطح خطای 1 سخت‌گیرترین تا 8 آسان‌ترین
چک‌لیست بازبینی کد (Code review checklist)فهرست کوتاه سؤال‌های انسانی پس از سبز شدن ابزارها
اصول FIRSTFast، Independent، Repeatable، Self-validating، Timely؛ ویژگی‌های تست واحد (Unit test) خوب
تست سریع (Fast tests)تستی که در میلی‌ثانیه اجرا می‌شود تا افراد اجرا کنند
تست مستقل (Independent tests)تستی که به تست دیگر یا ترتیب اجرا وابسته نیست
خوانایی تست (Test readability)تست شکست‌خورده ورودی، مقدار واقعی و مورد انتظار را می‌گوید تا بدون باز کردنش تشخیص ممکن باشد
تست توصیفی (Characterization test)تستی که رفتار امروز کد موجود را تثبیت می‌کند تا ایمنی refactor ثابت شود
Go Code Review Commentsصفحهٔ ویکی Go برای نظرهای رایج بازبینی: نام‌گذاری، جریان خطا، receiver و جمله‌های comment
Effective Goراهنمای پروژهٔ Go برای کدنویسی مطابق روش‌های معمول زبان

منابع ​

ساخته‌شده توسط Morteza Negahi