Skip to content

Code Smells, Anti-Patterns & Refactoring (the 14 smells and their moves) ​

"Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior." — Martin Fowler، refactoring.com

خلاصه (Summary): «بوی بد کد» (Code smell) نشانه‌ای است که زود به چشم می‌آید و می‌گوید شاید طراحی جایی خراب باشد؛ «بازآرایی» (Refactoring) تغییری کوچک، نام‌دار و بدون تغییر رفتار است که آن را درست می‌کند؛ «ضدالگو» (Anti-pattern) راه‌حلی تکراری است که بیشتر ضرر دارد تا فایده. تمرکز (Focus): کاتالوگ بوهای Fowler (نام‌های ۱۹۹۹ و ۲۰۱۸) در پنج خانواده، ۱۴ بویی که این فصل تمرین می‌کند با مثال Go و Laravel، حرکت‌های refactoring که هر کدام را درمان می‌کنند، ضدالگوها، بوهای معماری، ابزارها و یک آزمایشگاه کامل با characterization test. هدف یادگیری (Learning goal): بویی را که جلوی شماست نام ببرید، تنها حرکتی را که آن را برمی‌دارد انتخاب کنید، آن را در گامی آن‌قدر کوچک بردارید که تست‌ها سبز بمانند، و بدانید کی یک «بو» اشکالی ندارد و باید به حالش گذاشت.

این صفحه مرجع کامل بوها و refactoring است: تاریخچه (Opdyke، Beck و Fowler، کتاب AntiPatterns، Kerievsky، Feathers)، کل کاتالوگ بوها با نام‌های هر دو ویرایش، حرکت‌های کاتالوگ ویرایش دوم Fowler، ضدالگوهای Brown و همکاران، بوهای معماری، ابزارهای Go و PHP، و اینکه refactoring وقتی کد یک monolith در حال شکستن به سرویس‌هاست چه معنایی دارد. همسایه‌ها را دوباره درس نمی‌دهیم: coupling، cohesion و پنهان‌سازی اطلاعات در Design Quality است؛ message chain و قانون Demeter در Composing Objects؛ پنج اصلی که بیشتر بوها نقضشان می‌کنند در SOLID (divergent change همان نقض SRP است، repeated switches نقض OCP و refused bequest نقض LSP)؛ الگوهای نام‌دار به‌عنوان مقصد refactoring در Applying Patterns؛ و مهاجرت تکه‌تکهٔ یک سیستم کامل در Strangler Fig.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
۱۴ بو، حرکت‌ها و قاعده‌های زمان‌بندی در سه جدولهمه‌چیز در یک دقیقه
اصلاً چرا refactor می‌کنیم و هزینه‌اش چیستچرا refactoring وجود دارد
Opdyke، Beck، Fowler ۱۹۹۹ و ۲۰۱۸، Brown و همکاران، Kerievsky، Feathersاز کجا آمده
تعریف، گام کوچک، دو کلاه، قاعدهٔ سه، refactoring آماده‌سازی و زباله‌برداریخود refactoring
همهٔ بوها در پنج خانواده، نام‌های ۱۹۹۹ و ۲۰۱۸ کنار همکاتالوگ بوها
long method، large class، primitive obsession ... feature envy، هر کدام یک بلوک۱۴ بو، یکی‌یکی
temporary field، message chains، middle man، global data و بقیهبوهای دیگر
Extract Function، Replace Conditional with Polymorphism، Introduce Special Case و رفقاکاتالوگ حرکت‌ها
god object، lava flow، golden hammer، boat anchor، cargo cultضدالگوها
وابستگی چرخه‌ای، hub-like و ناپایدار، دیتابیس مشترک، distributed monolithبوهای معماری
حلقه، تور ایمنی، انضباط commit، تغییرهای بزرگسازوکار
gofmt، gopls، golangci-lint، staticcheck، PHPStan، Rector، Pint، PhpStormابزارها
controller چاق، پولِ string، همان switch در شش فایلحل مسئله‌های کلاسیک
refactor، بازنویسی یا رها کردنانتخاب
refactor در monolith در برابر بیرون کشیدن یک میکروسرویسدر معماری
یک handler بدبوی ۲۰۰ خطی در Go و یک controller در Laravel، قدم‌به‌قدم با تستآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، همهٔ اصطلاح‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

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

#بو (نام refactoring.guru / ۱۹۹۹)نام Fowler در ۲۰۱۸خانوادهبه زبان سادهاولین حرکت
1Long MethodLong FunctionBloatersیک تابع چند کار می‌کندExtract Function
2Large ClassLarge ClassBloatersیک type بیش از حد می‌داندExtract Class
3Primitive ObsessionPrimitive ObsessionBloatersپول در float64، وضعیت در stringReplace Primitive with Object
4Long Parameter ListLong Parameter ListBloatersنُه آرگومان، نصفشان پرچمIntroduce Parameter Object
5Data ClumpsData ClumpsBloatersهمان ۳ تا ۴ مقدار همیشه با هم می‌آیندExtract Class
6Switch StatementsRepeated SwitchesOO Abusersهمان switch در چند جاReplace Conditional with Polymorphism
7Refused BequestRefused BequestOO Abusersزیرنوعی که ارثش را نمی‌خواهدReplace Superclass with Delegate
8Divergent ChangeDivergent ChangeChange Preventersیک ماژول به دلایل زیاد تغییر می‌کندSplit Phase، Extract Class
9Shotgun SurgeryShotgun SurgeryChange Preventersیک تغییر به ماژول‌های زیاد دست می‌زندMove Function، Move Field
10Duplicate CodeDuplicated CodeDispensablesهمان منطق دو بارExtract Function، Pull Up Method
11CommentsCommentsDispensablesتوضیحی برای کدی که باید خودش توضیح بدهدExtract Function، Rename
12Data ClassData ClassDispensablesفیلد و getter؛ رفتار جای دیگرMove Function به داخلش
13Speculative GeneralitySpeculative GeneralityDispensablesقلاب برای آینده‌ای که نیامدCollapse Hierarchy، Inline، Remove Dead Code
14Feature EnvyFeature EnvyCouplersتابعی که به دادهٔ type دیگر علاقهٔ بیشتری داردMove Function

حرکت‌هایی که ۹۰ درصد وقت به کار می‌برید. نام‌ها از کاتالوگ ویرایش دوم Fowler است؛ نام‌های قدیمی روی همان کارت کاتالوگ به‌عنوان alias آمده‌اند.

حرکتنام قدیمی / aliasچه چیزی را درمان می‌کندمعکوس
Extract FunctionExtract Methodتابع بلند، comment، کد تکراریInline Function
Extract VariableIntroduce Explaining Variableعبارت‌های ناخواناInline Variable
Change Function DeclarationRename Function، Add/Remove Parameter، Change Signatureنام‌های مرموز، پارامترهای حدسیخودش
Move Function / Move FieldMove Methodfeature envy، shotgun surgeryخودش
Extract Classlarge class، data clumps، divergent changeInline Class
Introduce Parameter Objectlong parameter list، data clumps
Replace Primitive with ObjectReplace Data Value with Object، Replace Type Code with Classprimitive obsession
Replace Conditional with Polymorphismrepeated switches
Introduce Special CaseIntroduce Null Objectچک‌های تکراری if x == nil
Separate Query from Modifierتابعی که هم جواب می‌دهد هم state را عوض می‌کند

کی refactor کنیم.

لحظهنامچه می‌کنید
پیش از یک قابلیتPreparatory refactoring (آماده‌سازی)تغییر را آسان کنید، بعد تغییر آسان را بدهید
هنگام خواندن کدComprehension refactoring (فهمیدن)rename و extract تا وقتی بفهمید
در گذرLitter-pickup (قانون اردوگاه)کمی بهتر از آنچه پیدا کردید رهایش کنید
بعد از سبز شدن در TDDگام refactorآنچه همین الان نوشتید را تمیز کنید، تست‌ها سبز
نسخهٔ سوم همان چیزقاعدهٔ سه (Rule of three)اولی بنویس، دومی اخم کن، سومی refactor کن
مشکل بزرگ شناخته‌شدهPlanned / long-term refactoringکاری ثبت‌شده که در گام‌های کوچکِ قابل‌انتشار انجام می‌شود

چرا refactoring وجود دارد ​

کدی که امروز کار می‌کند فردا هم باید تغییر کند. هر تغییری ارزان‌تر است وقتی کد بگوید چه می‌کند، هر تصمیم را یک جا نگه دارد و بگذارد جداگانه تستش کنید. کد از این شکل دور می‌شود چون قابلیت‌ها زیر فشار زمان اضافه می‌شوند. refactoring عادتی است که آن را برمی‌گرداند، بی‌آنکه کار روی قابلیت‌ها متوقف شود، با تغییر ساختار و هرگز رفتار. بوها به شما می‌گویند کجا را بکشید.

استدلال خود Fowler در صفحهٔ اول refactoring.com: "When a software system is successful, there is always a need to keep enhancing it". بدون refactoring، بهبودها روی هم تلنبار می‌شوند و "new work slows to a crawl."

هرگز refactor نکردنrefactor پیوسته
هفتهٔ اول سریعدر هفتهٔ پنجاهم همان سرعت
هر تغییر کل تابع را دوباره می‌خواندهر تغییر یک تکهٔ نام‌دار را می‌خواند
اصلاح در یک نسخه به نسخه‌های دیگر نمی‌رسدیک نسخه، یک اصلاح
تست‌ها دیتابیس، mailer و ساعت را لازم دارندقاعده‌های خالص تنها تست می‌شوند
هر چند سال یک بازنویسی بزرگبی‌بازنویسی؛ کد تکامل می‌یابد
خطر: دیگر اصلاً نمی‌شود تغییرش دادخطر: صیقل دادن کدی که دیگر کسی به آن دست نمی‌زند

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

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

  1. «refactoring یعنی هر جور تمیزکاری، بازنویسی یا طراحی دوباره.» Fowler: "If somebody talks about a system being broken for a couple of days while they are refactoring, you can be pretty sure they are not refactoring." اگر رفتار عوض شد یا build ساعت‌ها قرمز ماند، کاری که کردید بازسازی (Restructuring) بود، نه refactoring.
  2. «بو یعنی کد غلط است.» "smells don't always indicate a problem" (Fowler، CodeSmell). بو دلیلی برای نگاه کردن است. تابعی ۶۰ خطی که یک frame پروتکل را از بالا تا پایین parse می‌کند شاید روشن‌ترین کدی باشد که می‌شود نوشت.
  3. «refactoring تیکت جدا و یک sprint می‌خواهد.» بیشتر refactoringها چند دقیقه قبل یا بعد از یک قابلیت، به دست همان کسی که آن را می‌نویسد، انجام می‌شوند. فقط مشکل‌های ساختاری بزرگ برنامه‌ریزی لازم دارند، و آن‌ها هم در گام‌های کوچک تحویل می‌شوند.

از کجا آمده ​

Opdyke و Johnson ۱۹۹۰؛ Griswold ۱۹۹۱؛ Opdyke ۱۹۹۲. واژهٔ «refactoring» در نوشته به مقالهٔ ۱۹۹۰ William Opdyke و Ralph Johnson در SOOPPA برمی‌گردد؛ رسالهٔ ۱۹۹۱ William Griswold بازسازی برنامه‌های رویه‌ای را بررسی کرد و رسالهٔ ۱۹۹۲ Opdyke با عنوان Refactoring Object-Oriented Frameworks refactoringهای حافظ رفتار را برای ++C تعریف کرد (تاریخ‌ها از مقالهٔ Code refactoring در Wikipedia، منبعی ثانویه).

Beck و Fowler، ۱۹۹۹. Kent Beck واژهٔ «بو» را وقتی به Fowler در ویرایش اول Refactoring: Improving the Design of Existing Code کمک می‌کرد ساخت:

"A code smell is a surface indication that usually corresponds to a deeper problem in the system. The term was first coined by Kent Beck while helping me with my Refactoring book." — Martin Fowler، CodeSmell، bliki، ۲۰۰۶

فصل ۳، «Bad Smells in Code»، را هر دو نوشتند و با این هشدار شروع می‌شود که هیچ معیاری به جای شما تصمیم نمی‌گیرد:

"In our experience, no set of metrics rivals informed human intuition." — Fowler و Beck، Refactoring، ویرایش دوم، فصل ۳ (گزیدهٔ InformIT، ۲۰۱۸)

Brown، Malveau، McCormick و Mowbray، ۱۹۹۸. کتاب AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis راه‌حل‌های بد تکراری را از سه زاویه (برنامه‌نویس، معمار، مدیر) فهرست کرد؛ خود اصطلاح anti-pattern را Wikipedia (منبع ثانویه) به Andrew Koenig در ۱۹۹۵ نسبت می‌دهد. ضدالگوهای توسعهٔ کتاب از Mike Akroyd آمده‌اند و سایت نویسندگان تأکید دارد هر کدام راه خروج خودش را دارد: "Name the problem, then say how to get out of it."

Kerievsky، ۲۰۰۴. کتاب Refactoring to Patterns دو دنیا را به هم وصل کرد: "Refactoring to Patterns suggests that using patterns to improve an existing design is better than using patterns early in a new design." (صفحهٔ کتاب در Industrial Logic). الگوها مقصدهایی‌اند که وقتی یک بو آن‌ها را طلب می‌کند به سمتشان refactor می‌کنید.

Feathers، ۲۰۰۴. کتاب Working Effectively with Legacy Code «تست توصیفی» (Characterization test) را به ما داد: تستی که آنچه کد الان انجام می‌دهد را ثبت می‌کند تا بتوانید کدی بی‌تست را refactor کنید (Wikipedia اصطلاح را به Feathers نسبت می‌دهد؛ منبع ثانویه).

Fowler، ویرایش دوم، ۲۰۱۸. مثال‌ها به JavaScript رفتند، کاتالوگ به refactoring.com/catalog منتقل شد، چند refactoring نام تازه گرفتند (Extract Method شد Extract Function) و فهرست بوها بازبینی شد: چهار بوی تازه، چهار تغییر نام و دو حذف. مقایسهٔ کامل در کاتالوگ است.

خود refactoring ​

تعریف: حافظ رفتار، گام کوچک، تست حیاتی ​

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

بدفهمی رایج: «اگر نتیجهٔ نهایی همان رفتار را دارد، مسیر مهم نیست.» مسیر خودِ این تکنیک است. صفحهٔ اول Fowler: "Its heart is a series of small behavior preserving transformations." بازنویسی دوروزه‌ای که با همان رفتار تمام شود refactoring نیست؛ قماری است که این بار برد.

تعریف: Fowler در bliki دو شکل می‌دهد. اسم: "a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior." فعل: "to restructure software by applying a series of refactorings without changing its observable behavior." تور ایمنی مجموعه‌تستی است که بعد از هر گام اجرا می‌کنید؛ قاعدهٔ سرانگشتی او در Refactoring Malapropism: "If you are doing refactoring your system should not be broken for more than a few minutes at a time".

text
     Minute   Step                                   Tests   Commit
1    00       spot: 40-line discount block in handler  green
2    02       Extract Function -> discount()          green   refactor: extract discount
3    05       Extract Variable -> isStaff             green
4    07       Replace magic 0.30 with staffPercent    green   refactor: name discount rates
5    09       Move discount() to CustomerType         RED     (forgot the coupon rule)
6    10       git restore; smaller step: move only the percent lookup  green
7    13       move coupon rule next                   green   refactor: move discount to CustomerType

راه درست: هر بار یک حرکت نام‌دار؛ بعد از هر حرکت تست‌ها را اجرا کنید؛ روی سبز commit کنید؛ روی قرمز، به جای debug کردن یک وضعیت نیمه‌refactorشده، revert کنید.

دو کلاه (Two hats) مهم ​

به زبان ساده: در هر لحظه یا رفتار اضافه می‌کنید یا refactor می‌کنید، هرگز هر دو. استعارهٔ Kent Beck که Fowler هم به کار می‌برد: هر بار فقط یک کلاه سرتان است.

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

تعریف: (Fowler مقالهٔ preparatory refactoring را با بخشی به نام "The Two Hats" شروع می‌کند.) وقتی قابلیت اضافه می‌کنید، تست اضافه می‌کنید و رفتار را عوض می‌کنید؛ وقتی refactor می‌کنید، رفتاری اضافه نمی‌کنید و فقط تست‌هایی را عوض می‌کنید که ساختارشان را شکسته‌اید (مثلاً تابعی که rename شده). مدام کلاه عوض کنید، اما بدانید کدام سرتان است. در git این یعنی commitهای جدا: commitهای refactor: که همهٔ تست‌ها را سبز نگه می‌دارند، و commitهای feat:/fix: که رفتار را عوض می‌کنند.

کی refactor کنیم: جریان‌های کار حیاتی ​

به زبان ساده: وقتی تغییرِ پیش رو را آسان‌تر می‌کند، وقتی به فهمیدن کدی که می‌خوانید کمک می‌کند، و هر بار که از کنار چیزی کوچک و نامرتب رد می‌شوید.

بدفهمی رایج: «refactoring یک فاز است.» Fowler در Opportunistic Refactoring: "Although there are places for some scheduled refactoring efforts, I prefer to encourage refactoring as an opportunistic activity, done whenever and wherever code needs to cleaned up - by whoever."

تعریف: infodeck Workflows of Refactoring از Fowler (۲۰۱۴) جریان‌ها را نام می‌برد و نوشته‌های دیگرش تعریفشان می‌کنند:

جریانماشهعبارت منبع
TDD refactoringهمین الان سبز شدگام سوم TDD: "Refactor both new and old code to make it well structured."
Preparatory refactoringاضافه کردن قابلیت سخت استKent Beck: "make the change easy (warning: this may be hard), then make the easy change"
Comprehension refactoringخواندن کد سخت است"If I struggle to understand this code, I refactor it so I won't have to struggle again next time I look at it." (refactoring.com)
Litter-pickup refactoringاز کنار چیز نامرتبی رد می‌شویدقانون اردوگاه: "always leave the code behind in a better state than you found it."
Planned refactoringتیم توافق می‌کند مشکلی شناخته‌شده وقت لازم داردکاری ثبت‌شده؛ Fowler هشدار می‌دهد نادیده گرفتن refactoring فرصت‌طلبانه به "difficult conversations with sponsors about refactoring iterations" ختم می‌شود
Long-term refactoringتغییری بزرگ (عوض کردن کتابخانه، شکستن ماژول)هفته‌ها گام کوچک، اغلب با Branch by Abstraction

همهٔ جریان‌ها یک پیش‌شرط دارند: "you should only refactor when your tests are green."

قاعدهٔ سه (Rule of three) مهم ​

به زبان ساده: روی نسخهٔ اول و دوم انتزاع نسازید؛ روی سومی بسازید، وقتی بالاخره می‌بینید واقعاً چه چیزی فرق می‌کند.

بدفهمی رایج: «DRY یعنی روی نسخهٔ دوم extract کن.» دو نسخه اغلب تکرار تصادفی است؛ ادغام زودهنگام انتزاع غلط می‌سازد که برگرداندنش از خود تکرار سخت‌تر است.

تعریف: صفحهٔ When to refactor در refactoring.guru، در خلاصهٔ Fowler: "When you’re doing something for the third time, start refactoring." Wikipedia (ثانویه) هشدار Sandi Metz را اضافه می‌کند که ادغام زودهنگام "risks selecting a wrong abstraction".

text
     Copy   Where                         What you do
1    1st    checkout pricing              just write it
2    2nd    quote endpoint                copy it, wince, leave a TODO with a link to copy 1
3    3rd    admin re-price tool           now you see what varies (shipping) and what does not (discount)
4           Extract Function + parameter for the varying part; delete the three copies

کی refactor نکنیم مهم ​

وضعیتبه جایشچرا
تست ندارد و وقت نوشتن characterization test هم نیستاول تست بنویسید، یا رهایش کنیدبدون تور نمی‌توانید ثابت کنید رفتار حفظ شده
کدی که ماه بعد حذف می‌شودرهایش کنیدپول دادن برای ساختاری که کسی استفاده نمی‌کند
بازنویسی واقعاً ارزان‌تر است (ماژول کوچک، فناوری غلط)پشت همان interface بازنویسی کنیدrefactoring فرض می‌کند رفتار فعلی ارزش نگه داشتن دارد
وسط حادثه یا یک ساعت مانده به انتشاریادداشت کنید، بعداً برگردیددو کلاه؛ ریسک در بدترین لحظه
API منتشرشده‌ای که تیم‌های دیگر استفاده می‌کنندParallel Changerename آن تغییر قرارداد است، نه refactoring

کاتالوگ بوها ​

Code smells: five families (refactoring.guru grouping of Fowler's catalogue)Bloatersgrew too bigLong Method *Large Class *Primitive Obsession *Long Parameter List *Data Clumps *OO AbusersOOP applied wronglySwitch Statements *Temporary FieldRefused Bequest *Alternative Classes with Different InterfacesChange Preventersone change, many editsDivergent Change *Shotgun Surgery *Parallel Inheritance HierarchiesDispensablescould be deletedComments *Duplicate Code *Lazy ClassData Class *Dead CodeSpeculative Generality *Couplerstoo much couplingFeature Envy *Inappropriate IntimacyMessage ChainsMiddle ManIncomplete Library ClassFowler 2nd ed. (2018): new smellsMysterious Name: names that hide intentGlobal Data: modifiable from anywhereMutable Data: updates with far-away effectsLoops: replace with a pipeline (map, filter)Fowler 2nd ed. (2018): renamed or droppedLong Method to Long Function; Lazy Class to Lazy ElementSwitch Statements to Repeated SwitchesInappropriate Intimacy to Insider TradingNot in the 2018 list: Parallel Inheritance, IncompleteLibrary Class, Dead Code. * = one of this chapter's 14

این تصویر پنج جعبه دارد که دسته‌بندی refactoring.guru از بوهای ۱۹۹۹ است (دسته‌بندی کار خود سایت است، نه Fowler؛ فصل Fowler یک فهرست ساده است): Bloaters (چیزهایی که بیش از حد بزرگ شده‌اند)، OO Abusers (OOP که غلط به کار رفته)، Change Preventers (یک تغییر، ویرایش‌های زیاد)، Dispensables (چیزهایی که می‌شود حذفشان کرد) و Couplers (وابستگی بیش از حد). بوهای ستاره‌دار همان ۱۴ بوی این فصل‌اند. دو جعبهٔ پایین نشان می‌دهند فهرست ۲۰۱۸ Fowler چه فرقی دارد: چهار بوی تازه (Mysterious Name، Global Data، Mutable Data، Loops)، چهار تغییر نام، و سه بو که اصلاً در فهرست ۲۰۱۸ نیستند.

تعریف خانواده‌ها به قلم refactoring.guru:

خانوادهتعریف refactoring.guruبوها
Bloaters (متورم‌ها)"code, methods and classes that have increased to such gargantuan proportions that they are hard to work with"Long Method، Large Class، Primitive Obsession، Long Parameter List، Data Clumps
Object-Orientation Abusers (سوءاستفاده از OO)"incomplete or incorrect application of object-oriented programming principles"Switch Statements، Temporary Field، Refused Bequest، Alternative Classes with Different Interfaces
Change Preventers (مانع تغییر)"if you need to change something in one place in your code, you have to make many changes in other places too"Divergent Change، Shotgun Surgery، Parallel Inheritance Hierarchies
Dispensables (زائدها)"something pointless and unneeded whose absence would make the code cleaner"Comments، Duplicate Code، Lazy Class، Data Class، Dead Code، Speculative Generality
Couplers (جفت‌کننده‌ها)"contribute to excessive coupling between classes or show what happens if coupling is replaced by excessive delegation"Feature Envy، Inappropriate Intimacy، Message Chains، Middle Man، Incomplete Library Class

جدول اصلی: نام‌های ۱۹۹۹/refactoring.guru در برابر فهرست ۲۰۱۸ Fowler. فهرست ۲۰۱۸ همان ۲۴ عنوان بخش‌های فصل ۳ ویرایش دوم است (گزیدهٔ InformIT).

نام refactoring.guru / ۱۹۹۹نام Fowler در ۲۰۱۸خانوادهجزو ۱۴ تا؟
(ندارد)Mysterious Nameتازه در ۲۰۱۸نه
Duplicate CodeDuplicated CodeDispensablesبله (10)
Long MethodLong FunctionBloatersبله (1)
Long Parameter ListLong Parameter ListBloatersبله (4)
(ندارد)Global Dataتازه در ۲۰۱۸نه
(ندارد)Mutable Dataتازه در ۲۰۱۸نه
Divergent ChangeDivergent ChangeChange Preventersبله (8)
Shotgun SurgeryShotgun SurgeryChange Preventersبله (9)
Feature EnvyFeature EnvyCouplersبله (14)
Data ClumpsData ClumpsBloatersبله (5)
Primitive ObsessionPrimitive ObsessionBloatersبله (3)
Switch StatementsRepeated SwitchesOO Abusersبله (6)
(ندارد)Loopsتازه در ۲۰۱۸نه
Lazy ClassLazy ElementDispensablesنه
Speculative GeneralitySpeculative GeneralityDispensablesبله (13)
Temporary FieldTemporary FieldOO Abusersنه
Message ChainsMessage ChainsCouplersنه
Middle ManMiddle ManCouplersنه
Inappropriate IntimacyInsider TradingCouplersنه
Large ClassLarge ClassBloatersبله (2)
Alternative Classes with Different InterfacesهمانOO Abusersنه
Data ClassData ClassDispensablesبله (12)
Refused BequestRefused BequestOO Abusersبله (7)
CommentsCommentsDispensablesبله (11)
Parallel Inheritance Hierarchiesدر فهرست ۲۰۱۸ نیستChange Preventersنه
Incomplete Library Classدر فهرست ۲۰۱۸ نیستCouplersنه
Dead Code (فقط refactoring.guru)بو نیست؛ Remove Dead Code یک refactoring استDispensablesنه

۱۴ بو، یکی‌یکی ​

هر بلوک: به زبان ساده، باور غلط رایج، تعریف (هر جا نقل می‌کنیم، عبارت خود Fowler)، یک مثال Go و یک مثال PHP، حرکت‌ها، و اینکه کی بو نیست. کد قبل آزمایشگاه بیشترشان را در یک فایل دارد.

۱. Long Method (Long Function) حیاتی ​

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

بدفهمی رایج: «بلند یعنی بیش از N خط.» Fowler: "The key here is not function length but the semantic distance between what the method does and how it does it." تابعی ۳۰ خطی که HTTP و SQL و قاعدهٔ مالیات را قاطی کرده بلند است؛ جدولی ۶۰ خطی از حالت‌ها شاید نباشد.

تعریف: تابعی که بدنه‌اش برای فهمیده شدن به comment یا «پاراگراف»‌های جداشده با خط خالی نیاز دارد. درمان در فصل ۳: "Ninety-nine percent of the time, all you have to do to shorten a function is Extract Function". در Go با funlen (پیش‌فرض ۶۰ خط / ۴۰ دستور)، gocognit، gocyclo، nestif پیدایش کنید؛ در PHP با قاعده‌های پیچیدگی به سبک PHPMD یا همان code review.

go
// Before: HandleOrder in the lab is ~110 lines: decode, validate, price, ship, reserve, save, respond.
// After: each paragraph became a named function; the handler reads like the comment it replaced.
placed, err := h.Svc.Place(cmd)
php
// Before: 90 lines inside store(). After:
['order' => $order, 'quote' => $quote, 'method' => $method] = $placeOrder->handle($request->toData());

حرکت‌ها: Extract Function؛ Replace Temp with Query (متغیرهای موقت جلوی extract را می‌گیرند)؛ Introduce Parameter Object؛ Decompose Conditional؛ Split Loop؛ و وقتی هیچ‌کدام جواب نداد Replace Function with Command.

کی بو نیست: اسکریپت خطی (migration، mainی که وابستگی‌ها را سیم‌کشی می‌کند)، parser تولیدشده، یا تست table-driven که حالت‌ها را فهرست می‌کند.

۲. Large Class حیاتی ​

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

بدفهمی رایج: «بر اساس اندازه بشکنش.» بر اساس اینکه چه کسی از چه چیزی استفاده می‌کند بشکنید: "The clients of such a class are often the best clue for splitting up the class."

تعریف: "When a class has too many fields, duplicated code cannot be far behind." model User در Laravel با ۶۰ متد و struct Server در Go با ۴۰ متد مظنون‌های همیشگی‌اند. شکل افراطی‌اش ضدالگوی God Object / Blob است.

go
// Smell: one struct for HTTP, pricing, stock and storage.
type Shop struct { prices map[string]float64; stock map[string]int; db *sql.DB; mailer Mailer; tpl *template.Template }
// Cure: Catalog, Pricer, Orders, Handler; each field moved to the type that uses it.
php
// Smell: User has auth, billing, newsletter and GDPR export.
// Cure: BillingProfile and NewsletterPreference models, an ExportUserData action, User keeps relations.

حرکت‌ها: Extract Class (بر اساس پیشوند فیلدها: deposit_amount، deposit_currency ← Deposit)، Extract Superclass، Replace Type Code with Subclasses. شکستن بر اساس actor را در SRP ببینید.

کی بو نیست: aggregateی منسجم که یک تیم به یک دلیل تغییرش می‌دهد، یا facadeی که کارش دقیقاً تنها درِ ورود بودن است.

۳. Primitive Obsession حیاتی ​

به زبان ساده: مفهوم‌های دامنه (پول، ایمیل، SKU، وضعیت) در int، float64 و string زندگی می‌کنند، پس قاعده‌هایشان هر جا استفاده شوند کپی می‌شود.

بدفهمی رایج: «typeهای کوچک سربار دارند.» در Go یک type نام‌دار روی int64 در زمان اجرا هزینه‌ای ندارد؛ یک class readonly در PHP یک allocation است. باگ‌هایی که جلویشان را می‌گیرد (پولِ float، IDهای جابه‌جا، غلط تایپی در string وضعیت) خیلی گران‌ترند.

تعریف: به گفتهٔ Fowler و Beck برنامه‌نویس‌ها "curiously reluctant to create their own fundamental types which are useful for their domain—such as money, coordinates, or ranges" هستند و stringهایی که این‌طور به کار می‌روند متغیرهای "stringly typed" نام دارند.

go
// Before: subtotal += p * float64(it.Qty)   // float money, rounding by %.2f at the edge
type Money int64 // cents
func (m Money) Percent(p int64) Money { return m * Money(p) / 100 }
php
final readonly class Money { private function __construct(public int $cents) {} /* plus, minus, percent ... */ }
enum ShippingMethod: string { case Standard = 'standard'; case Express = 'express'; case Pickup = 'pickup'; }

حرکت‌ها: Replace Primitive with Object؛ Replace Type Code with Subclasses و بعد Replace Conditional with Polymorphism؛ Extract Class برای گروه primitiveها (همان Data Clumps). در Laravel، cast سفارشی Eloquent ستون را به value object نگاشت می‌کند.

کی بو نیست: در لبه‌ها (JSON، ردیف SQL، flagهای CLI) که primitive خودِ قالب سیم است؛ در مرز تبدیل کنید.

۴. Long Parameter List مهم ​

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

بدفهمی رایج: «به جایش یک map یا array $options بده.» این فهرست را پنهان می‌کند نه کوتاه، و type را هم از دست می‌دهید.

تعریف: فصل ۳ درمان‌ها را در یک پاراگراف می‌آورد: Replace Parameter with Query، Preserve Whole Object، Introduce Parameter Object، و برای پرچم‌ها Remove Flag Argument؛ و Combine Functions into Class وقتی چند تابع پارامترهای یکسان دارند.

go
// Before
func price(lines []Line, typ, coupon, shipping, street, city, zip, country string, dryRun bool) (float64, error)
// After: the address is one value, dryRun became two functions (Quote vs Place)
func (p Pricer) Price(lines []Line, t CustomerType, coupon string, ship ShippingMethod, to Address) (Quote, error)
php
// Before: place($email, $type, $items, $street, $city, $zip, $country, $shipping, $coupon, $sendMail = true)
// After: handle(PlaceOrderData $data) with Address and the mail moved to a listener

حرکت‌ها: Introduce Parameter Object، Preserve Whole Object، Remove Flag Argument، Replace Parameter with Query، Combine Functions into Class.

کی بو نیست: constructorهایی که container تزریق وابستگی صدا می‌زند و هر پارامتر یک همکار است؛ فهرست، خودِ مستند وابستگی‌هاست.

۵. Data Clumps مهم ​

به زبان ساده: همان سه چهار مقدار مدام با هم ظاهر می‌شوند: به‌صورت فیلد، پارامتر، کلید آرایه.

بدفهمی رایج: «یک struct با فیلدهای public کافی است.» شروع خوبی است؛ سود واقعی وقتی می‌آید که رفتاری که از این دسته استفاده می‌کند به داخلش برود (Fowler و Beck عمداً "a class here, not a simple record structure" را انتخاب کردند تا بعد بشود feature envy را درمان کرد).

تعریف: آزمون فصل ۳: "consider deleting one of the data values. If you did this, would the others make any sense? If they don’t, it’s a sure sign that you have an object that’s dying to be born."

go
type Address struct{ Street, City, Zip, Country string }
func (a Address) Domestic() bool { return a.Country == HomeCountry } // behaviour followed the data
php
final readonly class Address { public function isDomestic(): bool { return $this->country === self::HOME_COUNTRY; } }

حرکت‌ها: Extract Class روی فیلدها، بعد Introduce Parameter Object یا Preserve Whole Object روی امضاها، بعد Move Function برای کد حسود.

کی بو نیست: مختصاتی که به‌صورت (x, y) به یک تابع ریاضی داده می‌شود و این جفت امضای طبیعی تابع است.

۶. Switch Statements (Repeated Switches) حیاتی ​

به زبان ساده: همان switch (یا زنجیرهٔ if/else) روی همان کد نوع در چند جا تکرار شده، پس اضافه کردن یک حالت یعنی گشتن دنبال همه‌شان.

بدفهمی رایج: «هر switch باید polymorphism شود.» Fowler در ۲۰۱۸ دقیقاً برای جلوگیری از این خوانش نام بو را عوض کرد: "we now focus on the repeated switch, where the same conditional switching logic ... pops up in different places." یک switch در یک factory اشکالی ندارد.

تعریف: کد نوعی ("standard"، "express"، "pickup") که در دو شرط یا بیشتر رفتار را تعیین می‌کند.

text
     Day   Request                               Before (2 switches)                         After (interface)
1    D1    add "same-day courier" shipping        edit switch in HandleOrder                 add type courier + one map entry
2    D1                                           forget the switch for the ETA: eta = ""   compiler: courier must implement ETA()
3    D2    support ticket: "ETA is blank"         find the second switch, patch              (cannot happen)
4    D9    quote endpoint shows wrong price       third switch, in HandleQuote, never edited  (one Pricer, one copy)
go
type ShippingMethod interface { Cost(net Money, to Address) Money; ETA() string }
var shippingMethods = map[string]ShippingMethod{"standard": standard{}, "express": express{}, "pickup": pickup{}}
php
enum ShippingMethod: string { /* cases */ public function cost(Money $net, Address $to): Money { return match ($this) { /* ... */ }; } }

حرکت‌ها: Replace Conditional with Polymorphism (در Go: interface و یک type برای هر حالت؛ در PHP: classها، یا enum پشتیبان‌دار با متدهایی که matchشان جامع است)، و اگر کد نوع هنوز primitive است اول Replace Type Code with Subclasses. سمت طراحی ماجرا در OCP است.

کی بو نیست: یک switch در مرز که ورودی را به type نگاشت می‌کند (factory)، یا match داخل یک enum در PHP که همهٔ حالت‌ها را در یک فایل نگه می‌دارد.

۷. Refused Bequest تکمیلی ​

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

بدفهمی رایج: «هر متد ارثی استفاده‌نشده نقض است.» Fowler در این مورد آسان‌گیر است: "Nine times out of ten this smell is too faint to be worth cleaning." شکل جدی‌اش رد کردن interface است: "We don’t mind refusing implementations—but refusing interface gets us on our high horses." این شکل جدی همان نقض LSP است.

تعریف: زیرکلاسی که از ارثش کم استفاده می‌کند، یا برای عملیات والد BadMethodCallException پرتاب می‌کند/خطا برمی‌گرداند.

go
// Go has no inheritance; the smell shows up with struct embedding:
type ReadOnlyStore struct{ *Store } // embeds Save, Delete ...
func (ReadOnlyStore) Delete(id int) error { return errors.New("not supported") } // refusing the interface
// Cure: do not embed; hold a field and expose only Get (Replace Superclass with Delegate).
type ReadOnlyStore struct{ s *Store }
func (r ReadOnlyStore) Get(id int) (Order, error) { return r.s.Get(id) }
php
class ArchivedOrder extends Order { public function cancel(): void { throw new \LogicException('archived'); } }
// Cure: final class ArchivedOrder { public function __construct(private Order $order) {} /* only reads */ }

حرکت‌ها: Push Down Method / Push Down Field به یک هم‌نیا (درمان «سنتی»)، یا Replace Subclass with Delegate / Replace Superclass with Delegate (با alias معروف Replace Inheritance with Delegation).

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

۸. Divergent Change حیاتی ​

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

بدفهمی رایج: «همان shotgun surgery است.» تصویر آینه‌ای آن است: divergent change یعنی یک ماژول، دلیل‌های زیاد؛ shotgun surgery یعنی یک دلیل، ماژول‌های زیاد.

تعریف: "Divergent change occurs when one module is often changed in different ways for different reasons." این همان نقض SRP است که از دریچهٔ تاریخچهٔ تغییرها دیده شده.

text
     Week   Ticket                         File edited in the lab's before code
1    W1     new carrier rate (logistics)   before/handler.go
2    W2     VIP 12% (marketing)            before/handler.go
3    W3     move orders to PostgreSQL      before/handler.go
4    W4     new JSON field (mobile team)   before/handler.go   -> four teams, one file, four merge conflicts
go
// Cure: Split Phase (decode -> PlaceOrder command -> Service.Place -> Placed -> encode) and one type per reason:
// shipping.go (logistics), customer.go (marketing), catalog.go/order.go (storage), http.go (API).
php
// Cure: PlaceOrderRequest (API), CustomerType (marketing), ShippingMethod (logistics), PlaceOrder (use case).

حرکت‌ها: Split Phase وقتی دلیل‌ها یک توالی می‌سازند؛ Extract Function و بعد Move Function؛ Extract Class.

کی بو نیست: اوایل پروژه، وقتی مرزها هنوز معلوم نیستند؛ Fowler می‌گوید اغلب "discover this only after you’ve added a few databases or financial instruments".

۹. Shotgun Surgery حیاتی ​

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

بدفهمی رایج: «classهای بیشتر و کوچک‌تر همیشه بهترند.» شکستن بیش از حد باعث shotgun surgery می‌شود. Fowler حتی توصیه می‌کند موقتاً برعکس بروید: تکه‌های پراکنده را در یک جا inline کنید، "we aren’t afraid of creating something large as an intermediate step to reorganization"، و بعد تکه‌های معقول را extract کنید.

تعریف: "every time you make a change, you have to make a lot of little edits to a lot of different classes."

text
     Step   "Free shipping from 50 becomes 60"     Files to edit before         After
1           handler (HandleOrder)                  before/handler.go:114        shipping.go: freeShippingFrom
2           handler (HandleQuote)                  before/handler.go:190        (same constant)
3           checkout banner text                   resources/views/cart.blade.php  reads the constant via a view composer
4           email template                         one more copy, missed        (gone)
go
const freeShippingFrom = Money(5000) // one place
php
private const FREE_FROM_CENTS = 5000; // inside ShippingMethod, the only owner

حرکت‌ها: Move Function و Move Field به یک ماژول؛ Combine Functions into Class / into Transform؛ اگر منطق پراکنده است، اول Inline Function / Inline Class.

کی بو نیست: تغییری فراگیر که قرار است همه‌جا را لمس کند (rename یک فیلد در کل API)، با ابزار و در یک commit.

۱۰. Duplicate Code (Duplicated Code) حیاتی ​

به زبان ساده: همان منطق در دو جا؛ هر اصلاح باید دو بار انجام شود و همیشه یک نسخه جا می‌ماند.

بدفهمی رایج: «هر چیزی که شبیه است تکراری است.» کدی که شبیه است ولی مالک‌های متفاوت دارد و به دلایل متفاوت تغییر می‌کند تکرار تصادفی است؛ SRP و قاعدهٔ سه را ببینید.

تعریف: "If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them." درمان‌های فصل ۳: Extract Function؛ اول Slide Statements برای هم‌ردیف کردن تکرارهای تقریبی؛ Pull Up Method وقتی نسخه‌ها در زیرکلاس‌های هم‌نیا هستند.

text
     Day   Event in the lab's before code
1    D1    HandleQuote created by copying the pricing half of HandleOrder
2    D20   HandleOrder gains qty and stock validation; HandleQuote does not
3    D35   unknown shipping: HandleOrder returns 422, HandleQuote silently charges 0
4    D36   the characterization test pins both behaviours; unifying them is a product decision, not a refactoring
go
// After: both endpoints call the same Pricer.Price; the quote keeps its old quirk explicitly (see the lab).
q, err := s.Pricer.Price(cmd.Lines, cmd.Type, cmd.Coupon, ship, cmd.Address)
php
// After: PriceQuote::calculate() is the only copy of the pricing rules.

حرکت‌ها: Extract Function، Slide Statements، Pull Up Method، Form Template Method (نام ویرایش اول)، Substitute Algorithm. در Go با dupl (golangci-lint، آستانهٔ پیش‌فرض ۱۵۰ token) و در PhpStorm با تشخیص کد تکراری پیدایش کنید.

کی بو نیست: دو نسخه که مال actorهای متفاوت‌اند (نگهشان دارید)، یا fixtureهای تست که تکرار باعث می‌شود هر تست به‌تنهایی خوانا باشد.

۱۱. Comments مهم ​

به زبان ساده: commentی که توضیح می‌دهد یک بلوک چه می‌کند، نام تابعی است که منتظر نوشته شدن است.

بدفهمی رایج: «Fowler می‌گوید comment بد است.» برعکس می‌گوید: "comments aren’t a bad smell; indeed they are a sweet smell." بو این است که "comments are often used as a deodorant."

تعریف: "When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous." commentهایی که چرا را توضیح می‌دهند یا عدم‌قطعیت را علامت می‌زنند می‌مانند: "A comment can also explain why you did something."

go
// Before:  // discount: vip 10%, staff 30%, coupon 5 off except for staff
// After: the comment became the code.
func (t CustomerType) Discount(subtotal Money, coupon string) Money
php
// Before: // the same switch again
// After: ShippingMethod::eta(); the remaining comment explains WHY unknown shipping costs 0 in quotes.

حرکت‌ها: Extract Function (با نامی از روی comment)، Change Function Declaration (rename)، Introduce Assertion برای commentهای «اینجا این باید درست باشد».

کی بو نیست: مستندات package و API صادرشده (doc commentهای Go از نوعی که ST1020 چک می‌کند)، سرآیند حقوقی، commentهای «چرا»، لینک به تیکت یا RFC.

۱۲. Data Class مهم ​

به زبان ساده: typeی با فیلد و getter/setter در حالی که همهٔ منطقِ مربوط به آن در classهای دیگر است.

بدفهمی رایج: «هر struct باید رفتار داشته باشد.» استثنای Fowler: "one of the best exceptions is a record that’s being used as a result record from a distinct function invocation"، مثل نتیجهٔ Split Phase؛ و رکوردهای immutable نیازی به کپسوله‌سازی ندارند. DTOها در لبه و API Resourceهای Laravel مشکلی ندارند. نسخهٔ سطح domain این بو مدل دامنهٔ کم‌خون (Anemic domain model) است.

تعریف: "classes that have fields, getting and setting methods for the fields, and nothing else ... often being manipulated in far too much detail by other classes."

go
// Fine: Quote is a result record of Pricer.Price, immutable in practice.
type Quote struct{ Subtotal, Discount, Shipping, Total Money }
// Smell: an Order struct whose total, status rules and refunds are computed in five handlers.
php
// Smell: an Eloquent model with only $fillable while controllers compute status transitions.
// Cure: $order->cancel(), $order->refund(Money $amount) on the model or a domain object.

حرکت‌ها: Encapsulate Record، Remove Setting Method، Move Function به داخل data class، و اگر فقط بخشی جابه‌جا می‌شود اول Extract Function.

کی بو نیست: DTOها، شکل‌های request/response در API، payload رویدادها، read modelها و رکوردهای نتیجهٔ Split Phase.

۱۳. Speculative Generality مهم ​

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

بدفهمی رایج: «interface برای همه‌چیز کد را تست‌پذیر می‌کند.» در Go، interface مال مصرف‌کننده است و وقتی معرفی می‌شود که پیاده‌سازی دوم یا یک تست به آن نیاز داشته باشد؛ interface به نام Repository با یک پیاده‌سازی و بدون fake، حدس است.

تعریف: نامی که Brian Foote پیشنهاد کرد؛ نشانه‌اش در فصل ۳: "Speculative generality can be spotted when the only users of a function or class are test cases."

go
// Smell: type PricerFactory interface{ New(opts ...PricerOption) Pricer } with one implementation and no option ever passed.
// Cure: delete the factory; call the constructor. Detect unused params with unparam, unused code with unused.
php
// Smell: AbstractShippingCalculatorFactoryInterface with one implementation and a $strategy = null nobody passes.
// Cure: Rector's deadCode set removes unused private methods and params; Collapse Hierarchy for the rest.

حرکت‌ها: Collapse Hierarchy، Inline Function، Inline Class، Change Function Declaration (حذف پارامترهای استفاده‌نشده)، Remove Dead Code.

کی بو نیست: API یک کتابخانه یا plugin منتشرشده که نقطه‌های توسعه خودِ محصول‌اند؛ درزی (Seam) که همین حالا برای یک تست لازم دارید.

۱۴. Feature Envy حیاتی ​

به زبان ساده: تابعی که بیشتر از دادهٔ type دیگری می‌خواند تا دادهٔ خودش؛ دلش می‌خواهد آنجا زندگی کند.

بدفهمی رایج: «هر تابع را ببر کنار داده‌ای که لمس می‌کند.» Strategy و Visitor عمداً رفتار را از داده جدا نگه می‌دارند؛ Fowler آن‌ها را استثناهای مشروع می‌نامد. قاعدهٔ زیرین این است: "put things together that change together."

تعریف: "a function in one module spends more time communicating with functions or data inside another module than it does within its own module." سرانگشت برای تابعی که از چند ماژول استفاده می‌کند: آن را به ماژولی ببرید که بیشترِ داده را دارد.

go
// Before (in the handler): if req.Country == "NL" { shipping = 4.95 } ...
// After: the address answers the question itself.
func (a Address) Domestic() bool { return a.Country == HomeCountry }
php
// Before: $data['country'] == 'NL' ? 4.95 : 9.95 in the controller. After: $to->isDomestic() on Address.

حرکت‌ها: Move Function؛ Extract Function روی بخش حسود، بعد Move Function.

کی بو نیست: Strategy، Visitor و الگوهای دیگری که عمداً رفتار را از داده جدا می‌کنند؛ projectionهای فقط‌خواندنی (سازندهٔ گزارشی که از چند model می‌خواند).

بوهای دیگر ​

بقیهٔ کاتالوگ، هر کدام در یک سطر: تعریف، نمونه‌ای در Go، نمونه‌ای در PHP، حرکت‌ها و اینکه کی اشکالی ندارد.

بوتعریفنمونهٔ Goنمونهٔ PHPحرکت‌هاکی بو نیست
Temporary Field (فیلد موقت)فیلدی که فقط در بعضی شرایط مقدار می‌گیردretryAt time.Time که فقط یک مسیر کد استفاده می‌کند?Carbon $retryAt که بیشتر وقت‌ها null استExtract Class، Move Function، Introduce Special Casecache تنبلی که مستند شده
Alternative Classes with Different Interfacesدو type یک کار را با نام‌های متد متفاوت انجام می‌دهندSMTPMailer.Send در برابر SESMailer.DeliverStripeGateway::charge در برابر MollieGateway::payChange Function Declaration، Move Function، Extract Superclass / interfacetypeهای شخص ثالث که به‌هرحال با adapter می‌پوشانید
Parallel Inheritance Hierarchiesهر زیرکلاس تازه در یک سلسله‌مراتب، یکی هم در دیگری می‌خواهدXMLExporter و XMLValidator برای هر قالب (از راه interface)جفت‌های PdfInvoice و PdfInvoiceRendererMove Function، Move Field تا یکی از سلسله‌مراتب‌ها محو شودجفت‌ها عمداً در لایه‌های متفاوت‌اند (domain در برابر adapter)
Lazy Class (Lazy Element)class یا تابعی که دیگر ارزش نگه داشتن ندارد؛ "such program elements need to die with dignity"packageی با یک تابع سه‌خطیclass به نام Helper با یک متد staticInline Function، Inline Class، Collapse Hierarchyدرزی نام‌دار که قرار است همین حالا بزرگ شود
Dead Code (کد مرده)کدی که هرگز اجرا نمی‌شود (refactoring.guru؛ Fowler آن را refactoringِ Remove Dead Code می‌داند)تابع unexportedی که کسی صدا نمی‌زند (unused)متد private استفاده‌نشده (شاخه‌های مردهٔ PHPStan سطح ۴، مجموعهٔ deadCode در Rector)Remove Dead Code؛ به version control اعتماد کنیدکدِ پشت feature flag با مالک و تاریخ حذف
Inappropriate Intimacy (Insider Trading)ماژول‌هایی که جزئیات داخلی هم را می‌دانند؛ "Modules that whisper to each other by the coffee machine"package billing که فیلدهای unexported orders را از راه یک helper مشترک در internal می‌خواندmodelی که با DB::table('other_module_x') به جدول ماژول دیگر سرک می‌کشدMove Function، Move Field، Hide Delegate، Replace Subclass/Superclass with Delegateدو type داخل یک package منسجم
Message Chains (زنجیرهٔ پیام)a.B().C().D()؛ "the client is coupled to the structure of the navigation"order.Customer().Account().Plan().Limit()$order->customer->account->plan->limitHide Delegate، Extract Function و Move Function به پایین زنجیرهbuilderهای روان و query builderها (User::query()->where()->get())
Middle Man (واسطه)"half the methods are delegating to this other class"Serviceی که متدهایش فقط repository را صدا می‌زنندservice class در Laravel که یک‌به‌یک به Eloquent پاس می‌دهدRemove Middle Man، Inline Function، Replace Superclass/Subclass with DelegateProxy، Decorator، Facade، لایه‌های ضدفساد (Anti-corruption layer)
Incomplete Library Classکتابخانه متدی را که لازم دارید ندارد و نمی‌توانید عوضش کنیدhelper جاافتاده روی یک client شخص ثالثمتد جاافتاده روی یک class در vendorIntroduce Foreign Method / Local Extension (ویرایش اول)؛ در Go یک type پوشاننده، در PHP پوشاننده یا macro (Collection::macro)هر جا بشود، به upstream کمک کنید
Mysterious Name (۲۰۱۸)نام‌هایی که منظور را پنهان می‌کنند؛ "When you can’t think of a good name for something, it’s often a sign of a deeper design malaise."func proc(d map[string]any)function handle2($x)Change Function Declaration، Rename Variable، Rename Fieldنام‌های کوتاه در دامنهٔ کوچک (i، err، r)
Global Data (۲۰۱۸)داده‌ای که "modified from anywhere in the code base"var Prices = map[string]float64{...} در آزمایشگاهconfig() که در زمان اجرا نوشته می‌شود، propertyهای staticEncapsulate Variable، بعد تنگ کردن دامنهثابت‌ها و config فقط‌خواندنیِ زمان شروع
Mutable Data (۲۰۱۸)به‌روزرسانی در یک جا کدی دیگر را غافلگیر می‌کندبرگرداندن slice داخلی که فراخوان می‌تواند به آن append کندتغییر دادن آرایهٔ مشترک از راه referenceEncapsulate Variable، Split Variable، Separate Query from Modifier، Remove Setting Method، Change Reference to Valueمتغیرهای محلی در دامنهٔ کوتاه
Loops (۲۰۱۸)حلقه‌ای که منظورش پشت بازی با index پنهان شدهحلقه‌های دستی filter و جمع (Go pipeline ندارد؛ helper نام‌دار یا تابع‌های slices)foreachی که آرایه می‌سازد ← collect()->filter()->sum()Replace Loop with Pipelineمسیرهای داغ در Go؛ حلقهٔ ساده در Go idiomatic است

کاتالوگ حرکت‌ها ​

کاتالوگ کامل refactoring.com حدود ۶۰ کارت دارد؛ این‌ها همان‌هایی‌اند که هر تیمی هر هفته به کار می‌برد. هر کارت در سایت نام ویرایش دوم، aliasها و معکوس را نشان می‌دهد.

حرکتalias / معکوسسازوکار در یک خطGoLaravel / PHPIDE
Extract Functionalias Extract Method؛ معکوس Inline Functionتکه را نام‌گذاری کن، آنچه می‌خواند را بده، آنچه می‌نویسد را برگردانتابع یا متد unexported تازهمتد private، یا یک Action قابل‌فراخوانیgopls refactor.extract.function / .method؛ PhpStorm Extract Method
Inline Functionalias Inline Methodفراخوانی‌ها را با بدنه عوض کن، تابع را حذف کنgopls refactor.inline.callPhpStorm Inlineهر دو
Extract Variablealias Introduce Explaining Variable؛ معکوس Inline Variableیک زیرعبارت را نام‌گذاری کنisStaff := t == Staff$isStaff = ...gopls refactor.extract.variable؛ PhpStorm Extract Variable
Change Function Declaration / RenameRename Function، Add/Remove Parameter، Change Signatureنام یا شکل را عوض کن، همهٔ فراخوان‌ها را به‌روز کن (اگر منتشرشده است، مرحله‌به‌مرحله)gopls rename؛ removeUnusedParam در goplsPhpStorm Rename، Change Signatureهر دو
Move Function / Move Fieldalias Move Methodبه مقصد کپی کن، از جای قدیم delegate کن، بعد delegate را inline کنبه packageی که مالک داده استاز controller به model/value objectPhpStorm Move
Replace Temp with Queryمتغیر موقت را تابع کن تا extract پارامتر کمتری بخواهدfunc (q Quote) net() Moneyprivate function net(): Moneyدستی
Introduce Parameter Objectپارامترها را در یک type جمع کن و همان را بدهstruct به نام PlaceOrderclass فقط‌خواندنی PlaceOrderDataدستی (Extract Class در PhpStorm کمک می‌کند)
Replace Conditional with Polymorphismیک type برای هر حالت؛ switch تبدیل به یک فراخوانی می‌شودinterface و typeهاclassها، یا متدهای enumدستی
Replace Type Code with Subclassesaliasها Extract Subclass، Replace Type Code with State/Strategyاول کد را type کنtype نام‌دار و interfaceenum پشتیبان‌دار، و اگر رفتار بزرگ شد classدستی
Decompose Conditionalشرط و هر شاخه را به تابع‌های نام‌دار extract کنacceptsCoupon()acceptsCoupon()Extract Method
Extract Classمعکوس Inline Classtype تازه، اول فیلدها، بعد متدها، یکی‌یکیtype یا package تازهvalue object، model، ActionPhpStorm Extract Delegate
Pull Up Method / Push Down Methodمعکوس هممتد را به والد / به زیرکلاس‌هایی که استفاده‌اش می‌کنند ببردر Go معنا ندارد (ارث‌بری نیست)؛ به یک helper جاسازی‌شده ببر یا از آن بیرون بیاورPhpStorm Pull Members Up / Push Members DownPhpStorm
Replace Superclass with Delegatealias Replace Inheritance with Delegationوالد قبلی را به‌صورت فیلد نگه دار و فقط آنچه لازم است را forward کنفیلد به جای embeddingprivate Order $order به جای extends Orderدستی
Introduce Special Casealias Introduce Null Objectیک شیء برای مقدار خاص با رفتار پیش‌فرضpickup{} برای quoteهای ناشناختهGuestCustomer با name() => 'occupant'دستی
Separate Query from Modifierیک تابع جواب می‌دهد، دیگری state را عوض می‌کندPricer.Price در برابر Catalog.ReservePriceQuote::calculate در برابر PlaceOrder::handleدستی
Encapsulate Collectionکپی یا نمای فقط‌خواندنی برگردان؛ افزودن و حذف از راه متدAll() کپی برمی‌گرداندکپی Collection برگردان، هرگز آرایهٔ داخلی با referenceدستی
Split Phaseبین دو مرحله یک ساختار داده بگذارdecode ← PlaceOrder ← PlaceForm Request ← DTO ← Action ← Resourceدستی
Hide Delegate / Remove Middle Manمعکوس هممتد forward اضافه کن / وقتی زیاد شدند حذفشان کنorder.CustomerPlan()$order->customerPlan()دستی
Replace Magic Literalalias Replace Magic Number with Symbolic Constantمقدار ثابت را نام‌گذاری کنconst freeShippingFrom = Money(5000)private const FREE_FROM_CENTS = 5000PhpStorm Extract Constant؛ gopls refactor.extract.constant
Remove Dead Codeحذفش کن؛ version control یادش می‌ماندunused پیدایش می‌کندPHPStan / مجموعهٔ deadCode در Rectorهر دو

سازوکار چهار حرکت بزرگ، در Go و PHP ​

Replace Conditional with Polymorphism. (۱) مطمئن شوید کد نوع یک type است (ShippingMethod)، نه string. (۲) برای هر حالت یک پیاده‌سازی بسازید با همان متد که مقدار آن حالت را برمی‌گرداند. (۳) هر بار یک case را با فراخوانی عوض کنید؛ بعد از هر کدام تست. (۴) وقتی switch فقط dispatch می‌کند، آن را با فراخوانی عوض کنید؛ یک map/tryFrom در مرز به‌عنوان factory بماند. shipping.go و ShippingMethod.php در آزمایشگاه نتیجهٔ همین است.

Replace Inheritance with Delegation (Replace Superclass with Delegate). (۱) فیلدی اضافه کنید که نمونه‌ای از والد قبلی را نگه می‌دارد. (۲) برای هر متد والد که فرزند واقعاً لازم دارد یک متد forward بنویسید. (۳) extends (در PHP) یا embedding (در Go) را بردارید. (۴) forwardهایی را که کسی صدا نمی‌زند حذف کنید.

go
// Before: embedding exports every Store method, including ones a read-only view must refuse.
type Report struct{ *Store }
// After: delegate only what the report needs.
type Report struct{ store *Store }
func (r Report) Orders() []Order { return r.store.All() }

Introduce Special Case (Null Object). (۱) چک‌های تکراری برای یک مقدار خاص را پیدا کنید (if customer == nil، $customer === null). (۲) typeی برای آن با رفتار پیش‌فرض بسازید. (۳) آن را به جای nil/null از lookup برگردانید. (۴) چک‌ها را یکی‌یکی حذف کنید.

php
final class GuestCustomer implements Customer
{
    public function name(): string { return 'occupant'; }
    public function discountPercent(): int { return 0; }
}
// $customer = $repo->find($id) ?? new GuestCustomer();   // the null checks disappear

Separate Query from Modifier. تابعی که هم مقدار برمی‌گرداند و state را عوض می‌کند را نمی‌شود «فقط برای نگاه کردن» صدا زد. جدایش کنید: query را می‌شود دو بار صدا زد، در endpoint قیمت، در تست یا در retry؛ modifier فقط یک کار می‌کند. کارت Fowler: getTotalOutstandingAndSendBill() به totalOutstanding() و sendBill() تبدیل می‌شود. در آزمایشگاه Pricer.Price همان query است و Catalog.Reserve همان modifier، و همین است که یک نسخهٔ واحد از قیمت‌گذاری را ممکن کرد.

ضدالگوها ​

به زبان ساده: ضدالگو (Anti-pattern) راه‌حلی است که معقول به نظر می‌رسد، تکرار می‌شود و بیشتر از آنچه حل می‌کند مشکل می‌سازد. بو نشانه‌ای در کد است؛ ضدالگو یک تصمیم طراحی تکراری است که بوهای زیادی می‌سازد.

بدفهمی رایج: «ضدالگو یعنی همان کد بد.» Brown و همکاران دو جزء می‌خواهند: راه‌حل بد تکراری و یک راه‌حل refactorشده. سایت نویسندگان توصیفی را که راه خروج ندارد "a pseudo-AntiPattern, closer to a complaint than a diagnosis" می‌نامد.

ضدالگومنبع و عبارتبوهایی که می‌سازدراه‌حل refactorشدهنمونهٔ Go / Laravel
God Object / The Blob حیاتیAntiPatterns (۱۹۹۸): "One class or object monopolizes behavior. Alias: God Class."Large Class، Divergent Change، Feature Envy در جاهای دیگرپخش کردن مسئولیت: Extract Class بر اساس actorServer با ۴۰ متد؛ model User با ۳۰۰۰ خط
Spaghetti Code (کد اسپاگتی)AntiPatterns: "Control flow with no discernible structure."Long Function، شرط‌های تودرتوExtract Function، guard clause، ماژول‌هایی با نام معنادارمتغیرهای پرچم شبیه goto؛ if هشت‌لایه در controller
Cut-and-Paste ProgrammingAntiPatterns: "Reuse by duplication."Duplicated Code، Shotgun Surgeryیک انتزاع، بعد از قاعدهٔ سهhandlerهای کپی‌شده در آزمایشگاه
Golden Hammer (چکش طلایی)AntiPatterns: "A familiar tool applied to every problem."Speculative Generality، انتزاع‌های غلطابزار را بعد از مسئله انتخاب کنیدKafka برای صف کاری با ۱۰ پیام در دقیقه؛ Redis به‌عنوان دیتابیس اصلی برای دادهٔ رابطه‌ای
Lava Flow (جریان گدازه)AntiPatterns: "The Lava Flow of obsolete technologies and forgotten extensions leaves hardened globules of dead code in its wake."Dead Code، Speculative Generalityکشف سیستم: پیدا کنید چه استفاده می‌شود، بقیه را با تست حذف کنیدpackage به نام legacy_v2/ که کسی جرئت حذفش را ندارد
Poltergeists (روح‌های مزاحم)AntiPatterns: "Short-lived objects that exist only to pass messages."Middle Man، Lazy Classروح را جمع کنید: Inline ClassOrderManagerStarter که فقط OrderManager را صدا می‌زند
Boat Anchor (لنگر قایق)AntiPatterns: "A costly component kept because it was costly."Dead Code، Speculative Generalityحذفش کنیدrules engine استفاده‌نشده‌ای که هنوز در container سیم‌کشی شده
Magic Numbers (عددهای جادویی)مقالهٔ Anti-pattern در Wikipedia (ثانویه): "A literal value with an important yet unexplained meaning"Primitive Obsession، Shotgun SurgeryReplace Magic Literal4.95، 0.30، 50 در کد قبل آزمایشگاه؛ linter به نام mnd
Cargo Cult Programming (برنامه‌نویسی آیینی)Wikipedia (ثانویه): گنجاندن آیینی کد یا ساختاری که هیچ هدف واقعی نداردSpeculative Generality، Middle Manبپرسید هر لایه چه می‌کند؛ آنچه کاری نمی‌کند را حذف کنیدinterface و service و DTO برای یک endpoint یک‌خطی CRUD «چون Clean Architecture»
Functional DecompositionAntiPatterns: "Procedural design wearing object clothing."Data Class، Feature Envyشیءهایی که داده و رفتار را با هم دارندmodelهای Eloquent به‌عنوان کیسهٔ ستون، منطق در classهای *Service

سناریوهای واقعی: Helper.php پرداخت که هر قابلیتی import می‌کند (Blob)؛ یک میکروسرویس برای هر ابزار محبوب تیم (Golden Hammer)؛ پوشهٔ v1/ که «احتمالاً استفاده نمی‌شود» (Lava Flow)؛ اپ Laravelی که هر classش یک interface با دقیقاً یک پیاده‌سازی دارد (Cargo Cult).

بوهای معماری ​

به زبان ساده: همان ایده یک سطح بالاتر: نشانه‌هایی در گراف وابستگی بین packageها، ماژول‌ها یا سرویس‌ها که می‌گویند تغییر گران خواهد بود.

بدفهمی رایج: «بوهای معماری ابزار خاص می‌خواهند.» سه تای اول در go list -deps، گراف autoload در composer یا یک نمودار import دیده می‌شوند؛ دو تای آخر در grantهای دیتابیس و لاگ deployها.

تعریف: Sas، Avgeriou و Uyumaz (۲۰۲۲)، با گزارش تعریف‌های Arcelli Fontana و همکاران (۲۰۱۷) آن‌طور که در ابزار Arcan پیاده شده‌اند:

بوتعریف (بازنویسی، مگر نقل‌قول)GoLaravel / PHPدرمان
Cyclic Dependency (وابستگی چرخه‌ای) حیاتی"a cycle among a number of components"کامپایلر import چرخه‌ای بین packageها را ممنوع می‌کند ("import cycle not allowed")PHP اجازه می‌دهد؛ ماژول‌های A و B classهای هم را صدا می‌زنندمفهوم مشترک را به ماژول سوم ببرید؛ یک یال را با interface برعکس کنید (DIP)
Hub-Like Dependency (وابستگی هاب‌مانند)مؤلفه‌ای که وابستگی‌های ورودی و خروجی‌اش هر دو بالای میانهٔ سیستم و تقریباً متعادل‌اندpackageی به نام common یا models که همه importش می‌کنند و او هم همه راApp\Services\Helperهاب را بر اساس هدف بشکنید؛ Move Function به فراخوان‌ها
Unstable Dependency (وابستگی ناپایدار)"a component that depends upon a significant number of components that are less stable than itself" (Arcan آستانهٔ ۳۰٪ و معیار instability مارتین را به کار می‌برد)package پایدار domain که package پرتغییر httpapi را import می‌کندdomain modelی که helper یک controller را import می‌کنددر جهت پایداری وابسته شوید؛ تکهٔ پرنوسان را پشت interface ببرید
God Component (مؤلفهٔ خدا)مؤلفه‌ای بیش از حد بزرگ (Blob در سطح package)internal/app با ۲۰۰ فایلپوشهٔ app/Models که هر تیمی ویرایشش می‌کندشکستن به ماژول‌ها بر اساس قابلیت کسب‌وکار
Shared Database (دیتابیس مشترک بین سرویس‌ها)microservices.io عیب‌ها را می‌شمارد: "Development time coupling" و "Runtime coupling"دو سرویس Go که در orders می‌نویسنددو اپ Laravel روی یک schema در MySQLهر جدول یک مالک؛ رویداد یا API منتشر کنید؛ Data Ownership را ببینید
Distributed Monolith (مونولیت توزیع‌شده)اصطلاح اهل فن (اینجا تعریف اولیه‌ای نقل نمی‌کنیم): سرویس‌هایی که باید با هم تغییر کنند و با هم deploy شوندچهار سرویس، یک قطار انتشارpackage مشترک Composer به نام models بین سرویس‌هامرزها را بر اساس قابلیت کسب‌وکار دوباره بکشید؛ Service Boundaries را ببینید

SQL زیر نشان می‌دهد بوی دیتابیس مشترک در grantها چه شکلی است، و نسخهٔ refactorشده‌ای که در آن هر سرویس مالک schema خودش است:

sql
-- Smell: both services connect as the same role and write the same tables.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app;   -- orders-svc and billing-svc both use "app"
-- Refactored: one schema and one writer per service; others read through an API or events.
CREATE SCHEMA orders;  CREATE SCHEMA billing;
CREATE ROLE orders_svc LOGIN;  CREATE ROLE billing_svc LOGIN;
GRANT USAGE, CREATE ON SCHEMA orders  TO orders_svc;
GRANT USAGE, CREATE ON SCHEMA billing TO billing_svc;
REVOKE ALL ON SCHEMA orders FROM billing_svc;   -- billing learns about orders from OrderPlaced events

سازوکار (Mechanics) ​

حلقهٔ refactoring حیاتی ​

Redfailing testGreensimplest codeRefactortests stay greenTDD (Beck): Red, Green, RefactorSmell spottedPick ONE named moveExtract Function, Move ...Small stepseconds to minutesRun the testsunit + characterizationGreen: commit"refactor: ..." onlyRed: revertgit restore, smaller stepBehaviour never changes inside this loop; feature work is the other hat.

سمت چپ تصویر چرخهٔ TDD است: Red (تست شکست‌خورده)، Green (ساده‌ترین کدی که تست را پاس کند)، Refactor (تمیزکاری با تست‌های سبز). Fowler آن را "Red - Green - Refactor" خلاصه می‌کند و هشدار می‌دهد: "The most common way that I hear to screw up TDD is neglecting the third step." سمت راست تصویر درونِ گام refactor را باز می‌کند: بو را می‌بینید، یک حرکت نام‌دار انتخاب می‌کنید، گامی برمی‌دارید که در چند دقیقه تمام شود، تست‌ها را اجرا می‌کنید، روی سبز commit و روی قرمز revert می‌کنید. داخل این حلقهٔ سمت راست رفتار هرگز عوض نمی‌شود؛ کار روی قابلیت، کلاه دیگر است.

تور ایمنی: تست‌هایی که می‌شود به آن‌ها اعتماد کرد حیاتی ​

تورچیستکیGoLaravel
Unit testتست سریع یک تابع یا typeکد از قبل داردgo test ./...تست‌های unit در Pest / PHPUnit
Characterization test (Golden master)آنچه کد الان می‌کند را با همهٔ عجیب‌وغریبی‌هایش ثبت می‌کندکد legacy بی‌تستreplay با httptest و بدنه‌های دقیق (labtest در آزمایشگاه)feature test با assertExactJson
Approval / snapshot testخروجی را در فایل نگه می‌دارد و diff می‌گیردخروجی‌های بزرگ (گزارش، PDF، JSON)فایل‌های golden زیر testdata/ با پرچم -updatepackage assertion از نوع snapshot یا fixture ذخیره‌شده
Type checker و تحلیل ایستاارجاع‌های شکسته را هنگام جابه‌جایی می‌گیردهر گامکامپایلر، go vet، staticcheckPHPStan در بالاترین سطحی که نگه می‌دارید
Mutation testingکد را عوض می‌کند و چک می‌کند که تستی شکست بخوردبه قدرت تست‌ها شک داریدابزارهای mutation شخص ثالثInfection

تست توصیفی روی کد قدیمی نوشته می‌شود، باید روی آن پاس شود و باید در هر گام پاس بماند. اگر شکست خورد، یا گامتان رفتار را عوض کرده (revert کنید) یا رفتاری پیدا کرده‌اید که می‌خواهید عوضش کنید (بایستید، refactoring را تمام کنید، بعد در commit جداگانه با تست تازه عوضش کنید).

text
     Step   Action                                          labtest result
1           write labtest against before/                    PASS (14 cases)
2           point labtest at after/ (first version)          FAIL: body has trailing "\n" (json.Encoder)
3           switch to json.Marshal + w.Write                 PASS
4           add a negative-qty quote case                    FAIL on after/: Money prints "-7.-55"
5           fix Money.String for negative amounts             PASS

انضباط commit و review مهم ​

قاعدهچرا
هر commit یک حرکت refactoring (یا چند حرکت پیش‌پاافتاده)bisect و revert معنادار می‌مانند
پیشوند: commitهای refactor: هرگز انتظارهای تست را عوض نمی‌کنندبازبین‌ها سریع رد می‌شوند؛ تست‌ها ایمنی را ثابت می‌کنند
تغییر رفتار در commitهای خودش، بعد از refactoringدو کلاه در تاریخچهٔ git
rename در یک commit، با ابزار، بدون هیچ چیز دیگرdiffهای بزرگ ولی بدیهی‌درست
refactoringها را زود و به‌صورت PR جدا push کنیدبازبین diff کوچک می‌بیند؛ قابلیت‌ها روی کد تمیز می‌نشینند

تغییرهای بزرگ: Parallel Change و Branch by Abstraction مهم ​

Parallel Change (گسترش و جمع کردن، Expand and contract). Danilo Sato در bliki Fowler: "Parallel change, also known as expand and contract, is a pattern to implement backward-incompatible changes to an interface in a safe manner, by breaking the change into three distinct phases: expand, migrate, and contract." وقتی فراخوان‌ها دست شما نیستند (API منتشرشده، تیم‌های دیگر، schema دیتابیس) از آن استفاده کنید.

text
     Release   Expand / migrate / contract: rename orders.total (float) to orders.total_cents (bigint)
1    R1        expand: add total_cents; write both columns; read total
2    R2        backfill total_cents for old rows; read total_cents, fall back to total
3    R3        migrate readers (reports, other services) to total_cents
4    R4        contract: stop writing total; drop it in a later release

Branch by Abstraction (شاخه با انتزاع). bliki Fowler آن را تکنیکی می‌داند "for making a large-scale change to a software system in gradual way that allows you to release the system regularly while the change is still in-progress." جلوی چیزی که قرار است جایگزین شود یک interface بگذارید، فراخوان‌ها را به آن ببرید، پیاده‌سازی تازه را پشتش بسازید، سوئیچ کنید و قدیمی را حذف کنید. این‌طور یک کتابخانهٔ پرداخت یا یک ORM را بدون branch عمرطولانی عوض می‌کنند.

ابزارها ​

ابزارها بو پیدا می‌کنند و حرکت‌های مکانیکی را انجام می‌دهند؛ هرگز تصمیم نمی‌گیرند کدام حرکت درست است.

Go حیاتی ​

ابزاربرای refactoring چه می‌کندمثال
gofmt -rقاعده‌های بازنویسی نحوی به شکل "pattern -> replacement" (حرف کوچک تکی wildcard است)gofmt -r 'a.Total() -> a.Sum()' -w .
code actionهای goplsrefactor.extract.function، .method، .variable، .constant، .toNewFile؛ refactor.inline.call، .variable؛ refactor.rewrite.removeUnusedParam، moveParamLeft/Rightدر هر ویرایشگر LSP؛ مستندات gopls می‌گوید Extract و Inline "are prone to losing comments"
gopls renamerename آگاه از type در کل module، از جمله rename یک packagegopls rename -w before/handler.go:#1450 placeOrder
go vetساختارهای مشکوکدر هر گام آزمایشگاه اجرا می‌شود
staticcheckساده‌سازی (S1xxx)، سبک (ST1xxx، مثلاً ST1003 شناسهٔ بدنام، ST1013 کدهای HTTP جادویی)، کد مرده مثل SA4006 مقداری که هرگز خوانده نمی‌شودstaticcheck ./...
golangci-lintlinterهای زیادی را اجرا می‌کند؛ بوگیرها در جدول بعدgolangci-lint run
linter در golangci-lintبویی که علامت می‌زند
funlen (پیش‌فرض ۶۰ خط، ۴۰ دستور)Long Function
gocognit، gocyclo، cyclop، nestif، maintidxLong Function، شرط‌های پیچیده
dupl (پیش‌فرض ۱۵۰ token)Duplicated Code
goconst، mndعددهای جادویی و stringهای تکراری
unused، unparamDead Code، Speculative Generality
gochecknoglobalsGlobal Data
interfacebloatLarge Class در سطح interface
depguardقاعده‌های معماری: منع import بین لایه‌ها
yaml
# .golangci.yml (golangci-lint v2 format)
version: "2"
linters:
  enable: [funlen, gocognit, dupl, goconst, mnd, unparam, gochecknoglobals, nestif]
  settings:
    funlen:
      lines: 60
      statements: 40
    gocognit:
      min-complexity: 15
    dupl:
      threshold: 100

PHP و Laravel حیاتی ​

ابزارنقشجزئیات
PHPStanتحلیل ایستا، تور ایمنی جابه‌جایی‌ها در PHP"you can currently choose from 11 levels (0 is the loosest and 10 is the strictest)"؛ "Levels are cumulative"؛ فایل baseline اجازه می‌دهد سطح را بالا ببرید بی‌آنکه اول خطاهای قدیمی را درست کنید؛ Larastan دانش Laravel را اضافه می‌کند
Rectorقاعده‌های refactoring خودکار، در CI یا محلی با --dry-runwithPreparedSets(deadCode: true, codeQuality: true, codingStyle: true, typeDeclarations: true, ...)؛ سطح‌ها یکی‌یکی بالا می‌روند (withDeadCodeLevel، withCodeQualityLevel، withTypeCoverageLevel)
Laravel Pintفقط سبک کد؛ "an opinionated PHP code style fixer for minimalists"، ساخته‌شده روی PHP CS Fixerابزار refactoring نیست: هرگز ساختار را عوض نمی‌کند؛ اجرایش کنید تا diff refactoring به فاصله‌گذاری آلوده نشود
PhpStormrefactoringهای تعاملی با preview و پنجرهٔ تعارضRename، Change Signature، Extract Method / Variable / Constant / Class / Interface / Superclass، Extract Delegate، Encapsulate Fields، Inline، Move، Pull Members Up / Push Members Down
سطح PHPStanچه اضافه می‌کند (انباشتی)
0classها، تابع‌ها و متدهای ناشناخته روی $this، تعداد آرگومان غلط، متغیرهایی که همیشه تعریف‌نشده‌اند
1–3متغیرهای احتمالاً تعریف‌نشده، عضوهای magic، اعتبارسنجی PHPDoc، typeهای بازگشتی، type propertyها
4کد مردهٔ پایه: instanceof همیشه false، شاخه‌های else مرده، کد بعد از return
5–6type آرگومان‌ها؛ typehintهای جاافتاده
7–8union typeهای تا حدی غلط؛ دسترسی روی nullable
9–10mixed سخت‌گیرانه؛ سطح 10 (PHPStan 2.0) mixed ضمنی را هم می‌گیرد
php
<?php // rector.php: start small, one level per pull request
use Rector\Config\RectorConfig;

return RectorConfig::configure()
    ->withPaths([__DIR__.'/app', __DIR__.'/tests'])
    ->withPreparedSets(deadCode: true, codeQuality: true)
    ->withTypeCoverageLevel(0);

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

مسئلهراه‌حلچطورمزیتهزینه / محدودیت
controller / handler چاقSplit Phase به جایگاه‌های Laravel یا GoForm Request / decode ← DTO ← Action / Service ← Resource / encodeهر مرحله جدا تست می‌شودفایل بیشتر
پول به‌صورت floatReplace Primitive with ObjectMoney بر حسب سنت، تبدیل در لبهحساب دقیق، یک قالب‌بندیمراقبت از قالب سیم و علامت منفی (quote منفی آزمایشگاه)
همان switch در شش فایلReplace Conditional with Polymorphisminterface یا enum با متد؛ یک factoryحالت تازه = یک type تازهبرای switch دوحالته ارزش ندارد
endpoint کپی‌شدهExtract Function بعد از قاعدهٔ سه؛ Separate Query from Modifierیک تابع قیمت‌گذاری که هر دو استفاده می‌کنندیک اصلاح، هر دو را درست می‌کندواگرایی‌ها رو می‌شوند و تصمیم محصول لازم دارند
map سراسری / singletonEncapsulate Variable، بعد تزریقtype مالک داده است؛ تزریق از constructorتست‌ها state تازه می‌سازندکد سیم‌کشی در main / providerها
model خداExtract Class بر اساس actorvalue object، model مرتبط، Action، Policymerge conflict کمترmigration برای ستون‌های جابه‌جاشده
کد legacy بی‌تستاول characterization testدرخواست‌های واقعی را replay کنید، خروجی‌ها را میخ کنیدrefactoring امنعجیب‌وغریبی‌های میخ‌شده را بعداً، آگاهانه، درست کنید
interface منتشرشده شکل تازه می‌خواهدParallel Changeگسترش، مهاجرت فراخوان‌ها، جمع کردنبی‌انتشار انفجاریمدتی دو مسیر کد

controller چاق و handler چاق ​

آزمایشگاه همین مسئله از اول تا آخر است. اندازه‌گیری روی snippetها: فایل handler در Go از یک فایل ۲۰۷ خطی با ۲ تابع handler به ۹ فایل کوچک رسید که در آن http.go فقط decode، یک فراخوانی و encode را دارد؛ store() در controller Laravel از حدود ۹۰ خط با ۶ خط use به ۸ خط رسید.

همان switch در شش فایل ​

bash
# find every switch on the same type code before replacing it (Go and PHP)
grep -rn --include='*.go' 'case "express"' . ; grep -rn --include='*.php' "'express'" app/

بعد Replace Conditional with Polymorphism را اجرا کنید، هر case در یک commit.

انتخاب: refactor، بازنویسی یا رها کردن ​

وضعیتتوصیهتکنیک تکمیلیدلیل
اضافه کردن قابلیت سخت استاول preparatory refactoring، بعد قابلیتcommitهای جدااول تغییر را آسان کنید
کدی که می‌خوانید گیج‌کننده استcomprehension refactoring (rename، extract)اگر فقط فهمیدن لازم بود، دور بریزیدفهمیدن خودش محصول است
ریخت‌وپاش کوچک سر راهlitter-pickupچند دقیقه سقف زمانیقانون اردوگاه
همان منطق برای بار سوم آمدهextractآنچه فرق می‌کند را پارامتر کنیدقاعدهٔ سه
ماژول legacy، بی‌تست، باید عوض شودcharacterization test، بعد refactorgolden masterبدون تور، refactoring نیست
مشکل ساختاری بزرگ (کتابخانهٔ غلط، God Component)planned / long-term refactoringBranch by Abstraction، Parallel Changeدر تمام مدت انتشار ادامه دارد
ماژول کوچک است و رفتارش به‌هرحال غلط استپشت همان interface بازنویسی کنیدcontract testحفظ رفتار غلط هدر دادن است
کد پایدار است و کسی لازم ندارد عوضش کندرهایش کنیدبو را یادداشت کنیدrefactoring فقط هنگام تغییر سود می‌دهد
شکستن یک monolithاول داخل monolith به ماژول refactor کنید، بعد بیرون بکشیدStrangler Figحرکت‌های ارزان قبل از مرز شبکه

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

refactoring با رفتار مشاهده‌پذیرِ حفظ‌شده تعریف می‌شود. داخل یک پروسه چک کردنش آسان است و به محض اینکه فراخوان‌ها آن سوی شبکه بنشینند سخت‌تر می‌شود.

Monolith (مونولیت): یک پروسه، یک دیتابیس ​

چطور ظاهر می‌شود: همهٔ بوهای کلاسیک، همهٔ حرکت‌ها در دسترس، کامپایلر (Go) یا PHPStan (PHP) و مجموعه‌تست هر گام را چک می‌کنند، و یک rename یک commit است.

ساده‌ترین استفادهٔ درست: پیوسته refactor کنید، commitهای refactor: را جدا نگه دارید، روی هر کدام کل تست‌ها را اجرا کنید.

مثال (ساده): PostController@store در یک وبلاگ parse برچسب‌ها را هم گرفته؛ یک TagParser extract کنید، یک unit test اضافه کنید، در یک PR تمام.

مثال (پیچیده): آزمایشگاه: handler سفارشی با همهٔ بوها به نُه فایل منسجم تبدیل می‌شود، با پشتیبانی یک characterization test.

Modular monolith و چند دیتابیس ​

چطور ظاهر می‌شود: بوها یک سطح بالا می‌روند: وابستگی چرخه‌ای بین ماژول‌ها، ماژول هاب‌مانند Shared، ماژولی که جدول‌های ماژول دیگر را می‌خواند. حرکت‌های refactoring به Move Function از روی مرز ماژول تبدیل می‌شوند، که API عمومی ماژول را هم عوض می‌کند.

قاعده‌ها: هر ماژول یک facade دارد؛ حرکت‌های داخل ماژول آزادند؛ حرکت‌های بین ماژول‌ها از facade رد می‌شوند و ممکن است Parallel Change بخواهند. در Go با internal/ و چک import چرخه‌ای کامپایلر و با depguard اعمالشان کنید؛ در PHP با تست‌های معماری (arch() در Pest یا قاعده‌های deptrac).

مثال: Billing مستقیم orders.total را می‌خواند (Insider Trading). refactor: Orders\Api::totalFor(int $orderId): Money را اضافه کنید، Billing را به آن ببرید، grant مربوط به جدول orders را از Billing بگیرید.

Microservices (میکروسرویس): refactoring از روی شبکه ​

چه می‌ماند: داخل یک سرویس، همهٔ آنچه گفتیم. چه می‌شکند: تغییر API یا schema رویداد یک سرویس به معنای Fowler refactoring نیست، چون رفتار مشاهده‌پذیر همان قراردادی است که تیم‌های دیگر استفاده می‌کنند. تغییر قرارداد است و با نسخه‌گذاری یا expand/contract انجام می‌شود.

بیرون کشیدن یک سرویس از monolith جایی است که refactoring و معماری به هم می‌رسند. اول حرکت‌های ارزان را انجام دهید، داخل همان پروسه، جایی که برگشت‌پذیرند:

text
     Step   Where             Move                                                       Behaviour
1    monolith          characterization tests around the shipping logic                  same
2    monolith          Extract Class -> ShippingMethod; Move Function out of controllers  same
3    monolith          Introduce an interface (Branch by Abstraction) at the seam        same
4    monolith          remove shared tables: shipping owns its rates table (Parallel Change)  same
5    network           new shipping-svc implements the interface over HTTP/gRPC           same, slower
6    router / gateway  Strangler Fig: route a percentage of calls to shipping-svc, compare   same
7    monolith          delete the in-process implementation                               same

گام‌های ۱ تا ۴ refactoring‌اند؛ از گام ۵ به بعد مهاجرت است که در Strangler Fig آمده. مقالهٔ Strangler Fig از Fowler: "the term “Strangler Fig” is now often used to describe a gradual approach to legacy modernization."

داده‌های توزیع‌شده: replica، cache و schema مشترک ​

کجا refactoring می‌شکند: داده از کد بیشتر عمر می‌کند. rename یک ستون، شکستن یک جدول یا عوض کردن شکل مقداری در cache برای همهٔ خواننده‌ها دیده می‌شود، از جمله replicaها، jobهای تحلیلی، سرویس‌های دیگر و ورودی‌های cache که نسخهٔ قدیمی نوشته. هر کدام expand/contract می‌خواهد: هر دو شکل را بنویسید، خواننده‌ها را مهاجرت دهید، بعد قدیمی را حذف کنید. قالب مقدار یک کلید cache هم یک schema است: به جای عوض کردن مقدار در جا، کلید را نسخه‌دار کنید (order:v2:42).

بوهای این سطح: دیتابیس مشترک بین سرویس‌ها، replica گزارش‌گیری که هر تیمی query می‌زند (هاب‌مانند)، رویدادهایی که payloadشان ردیف داخلی جدول است (Insider Trading از روی شبکه).

مسیر مقیاس‌پذیری: 1×، 10×، 100× ​

مقیاسساختارروش refactoring
1× (یک تیم، یک اپ)Monolithrefactoring فرصت‌طلبانه، linter در CI، characterization test برای بخش‌های legacy
10× (چند تیم، یک repo)Modular monolithfacade ماژول‌ها، قاعدهٔ import (depguard، deptrac)، بازبینی گراف وابستگی هر فصل برای چرخه‌ها و هاب‌ها
100× (تیم‌ها و سرویس‌های زیاد)سرویس بر اساس قابلیت کسب‌وکارداخل سرویس آزادانه refactor کنید؛ قرارداد را با نسخه‌گذاری و expand/contract عوض کنید؛ برای بیرون کشیدن، Strangler Fig

آزمایشگاه: refactor یک handler بدبو در Go و یک controller بدبو در Laravel ​

از کدی شروع می‌کنید که کار می‌کند و همهٔ بوهای این صفحه را دارد، یک characterization test برایش می‌نویسید و در گام‌های کوچک refactor می‌کنید تا به شکل کد «بعد» برسد، با تستی که بعد از هر گام سبز است.

BeforeAfterHandleOrder~110 lines, 6 jobsHandleQuotecopy of half of itcopyglobal Prices, Stock, Ordersfloat64 money, 2 copies of every switchevery change: edit both handlers,re-read 200 lines, hope tests catch itHandler (HTTP)ServiceCatalogPricerOrdersShippingMethodstandard, express, pickupMoney, Address, TypeArrows point at what a box depends on; leaves change least.

سمت چپ تصویر نقطهٔ شروع است: دو handler (HandleOrder و HandleQuote) که mapهای سراسری را شریک‌اند و یکی کپی دیگری است، با پولِ float64 و دو نسخه از هر switch. سمت راست وضعیت پایانی است: یک adapter نازک HTTP، یک Service، یک Catalog که مالک موجودی است، یک Pricer که تنها نسخهٔ قاعده‌های قیمت‌گذاری است، و پیاده‌سازی‌های ShippingMethod (standard، express، pickup) به جای دو switch. پیکان‌ها به وابستگی اشاره می‌کنند؛ برگ‌ها (Money، Address، CustomerType) کمتر از همه تغییر می‌کنند.

بخش الف: Go ​

آماده‌سازی.

bash
cd docs/snippets/design/code-smells-refactoring/go
go vet ./... && go test ./...
# ok  academy/code-smells-refactoring/after
# ok  academy/code-smells-refactoring/before

نقطهٔ شروع. پیش از دیدن جواب بخوانیدش و بوها را فهرست کنید: دست‌کم باید long function، primitive obsession (پولِ float64، کدهای نوع string)، data clumps (نشانی)، repeated switches، duplicated code (HandleQuote)، global data، عددهای جادویی، commentهای خوشبوکننده و feature envy را پیدا کنید.

go
// Package before is the smelly starting point of the lab: two HTTP handlers
// that validate, price, ship, reserve stock and save, all inline.
// It works. Every smell on the page is in here somewhere.
package before

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"sync"
	"time"
)

// Global mutable data: anyone can change prices, stock or orders.
var (
	Prices = map[string]float64{"BOOK": 12.50, "MUG": 8.00, "LAMP": 40.00}
	Stock  = map[string]int{"BOOK": 10, "MUG": 3, "LAMP": 1}
	Orders = []map[string]any{}
	mu     sync.Mutex
)

// Reset puts the global state back; only tests call it.
func Reset() {
	mu.Lock()
	defer mu.Unlock()
	Stock = map[string]int{"BOOK": 10, "MUG": 3, "LAMP": 1}
	Orders = []map[string]any{}
}

type item struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

// Data clump: street, city, zip and country always travel together.
type orderRequest struct {
	Email    string `json:"email"`
	Type     string `json:"customer_type"` // "regular", "vip", "staff"
	Items    []item `json:"items"`
	Street   string `json:"street"`
	City     string `json:"city"`
	Zip      string `json:"zip"`
	Country  string `json:"country"`
	Shipping string `json:"shipping"` // "standard", "express", "pickup"
	Coupon   string `json:"coupon"`
}

func writeErr(w http.ResponseWriter, code int, msg string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	fmt.Fprintf(w, `{"error":%q}`, msg)
}

// HandleOrder is the long method: about 100 lines, six jobs.
func HandleOrder(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(405)
		return
	}
	var req orderRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeErr(w, 400, "bad json")
		return
	}
	// validate the customer
	if req.Email == "" || !strings.Contains(req.Email, "@") {
		writeErr(w, 422, "invalid email")
		return
	}
	if len(req.Items) == 0 {
		writeErr(w, 422, "no items")
		return
	}
	// validate the address
	if req.Street == "" || req.City == "" || req.Zip == "" || req.Country == "" {
		writeErr(w, 422, "address required")
		return
	}
	mu.Lock()
	defer mu.Unlock()
	// compute the subtotal and check the stock
	subtotal := 0.0
	for _, it := range req.Items {
		p, ok := Prices[it.SKU]
		if !ok {
			writeErr(w, 422, "unknown sku: "+it.SKU)
			return
		}
		if it.Qty <= 0 {
			writeErr(w, 422, "invalid qty: "+it.SKU)
			return
		}
		if Stock[it.SKU] < it.Qty {
			writeErr(w, 409, "out of stock: "+it.SKU)
			return
		}
		subtotal += p * float64(it.Qty)
	}
	// discount: vip 10%, staff 30%, coupon 5 off except for staff
	discount := 0.0
	if req.Type == "vip" {
		discount = subtotal * 0.10
	} else if req.Type == "staff" {
		discount = subtotal * 0.30
	}
	if req.Coupon == "WELCOME5" && req.Type != "staff" {
		discount = discount + 5
	}
	// shipping
	shipping := 0.0
	switch req.Shipping {
	case "standard":
		if subtotal-discount >= 50 {
			shipping = 0
		} else if req.Country == "NL" {
			shipping = 4.95
		} else {
			shipping = 9.95
		}
	case "express":
		if req.Country == "NL" {
			shipping = 9.95
		} else {
			shipping = 19.95
		}
	case "pickup":
		shipping = 0
	default:
		writeErr(w, 422, "unknown shipping: "+req.Shipping)
		return
	}
	total := subtotal - discount + shipping
	// reserve the stock and save the order
	for _, it := range req.Items {
		Stock[it.SKU] -= it.Qty
	}
	id := len(Orders) + 1
	Orders = append(Orders, map[string]any{
		"id": id, "email": req.Email, "total": total,
		"street": req.Street, "city": req.City, "zip": req.Zip, "country": req.Country,
		"created": time.Now(),
	})
	// the same switch again, for the delivery estimate
	eta := ""
	switch req.Shipping {
	case "standard":
		eta = "3-5 days"
	case "express":
		eta = "1 day"
	case "pickup":
		eta = "same day"
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(201)
	fmt.Fprintf(w, `{"id":%d,"subtotal":%.2f,"discount":%.2f,"shipping":%.2f,"total":%.2f,"eta":%q}`,
		id, subtotal, discount, shipping, total, eta)
}

// HandleQuote was copied from HandleOrder and trimmed: duplicate code.
func HandleQuote(w http.ResponseWriter, r *http.Request) {
	var req orderRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeErr(w, 400, "bad json")
		return
	}
	mu.Lock()
	defer mu.Unlock()
	subtotal := 0.0
	for _, it := range req.Items {
		p, ok := Prices[it.SKU]
		if !ok {
			writeErr(w, 422, "unknown sku: "+it.SKU)
			return
		}
		subtotal += p * float64(it.Qty)
	}
	discount := 0.0
	if req.Type == "vip" {
		discount = subtotal * 0.10
	} else if req.Type == "staff" {
		discount = subtotal * 0.30
	}
	if req.Coupon == "WELCOME5" && req.Type != "staff" {
		discount = discount + 5
	}
	shipping := 0.0
	switch req.Shipping {
	case "standard":
		if subtotal-discount >= 50 {
			shipping = 0
		} else if req.Country == "NL" {
			shipping = 4.95
		} else {
			shipping = 9.95
		}
	case "express":
		if req.Country == "NL" {
			shipping = 9.95
		} else {
			shipping = 19.95
		}
	}
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, `{"subtotal":%.2f,"discount":%.2f,"shipping":%.2f,"total":%.2f}`,
		subtotal, discount, shipping, subtotal-discount+shipping)
}

گام ۱: تور ایمنی. characterization test چهارده درخواست را به ترتیب و روی یک state واحد replay می‌کند و کد وضعیت و بدنه را بایت‌به‌بایت مقایسه می‌کند. امروز روی before/ پاس می‌شود.

go
// Package labtest is the characterization (golden master) test shared by
// every version of the lab. It pins what the code does today, byte for byte,
// so each refactoring step can prove it changed structure and nothing else.
package labtest

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// Handlers is what a version of the lab must expose.
type Handlers struct {
	Order http.Handler
	Quote http.Handler
	Reset func()
}

type step struct {
	name     string
	handler  string // "order" or "quote"
	method   string
	body     string
	wantCode int
	wantBody string
}

const addrNL = `"street":"Main 1","city":"Utrecht","zip":"3511","country":"NL"`
const addrDE = `"street":"Hauptstr 2","city":"Berlin","zip":"10115","country":"DE"`

// The steps run in order against one state: stock taken by one step is gone
// for the next, exactly as in production.
var steps = []step{
	{"regular, standard NL", "order", "POST",
		`{"email":"a@x.io","customer_type":"regular","items":[{"sku":"BOOK","qty":2},{"sku":"MUG","qty":1}],` + addrNL + `,"shipping":"standard"}`,
		201, `{"id":1,"subtotal":33.00,"discount":0.00,"shipping":4.95,"total":37.95,"eta":"3-5 days"}`},
	{"vip gets 10% and free standard over 50", "order", "POST",
		`{"email":"b@x.io","customer_type":"vip","items":[{"sku":"LAMP","qty":1},{"sku":"BOOK","qty":2}],` + addrDE + `,"shipping":"standard"}`,
		201, `{"id":2,"subtotal":65.00,"discount":6.50,"shipping":0.00,"total":58.50,"eta":"3-5 days"}`},
	{"staff 30%, coupon ignored, express DE", "order", "POST",
		`{"email":"c@x.io","customer_type":"staff","coupon":"WELCOME5","items":[{"sku":"MUG","qty":2}],` + addrDE + `,"shipping":"express"}`,
		201, `{"id":3,"subtotal":16.00,"discount":4.80,"shipping":19.95,"total":31.15,"eta":"1 day"}`},
	{"coupon for regular, pickup", "order", "POST",
		`{"email":"d@x.io","customer_type":"regular","coupon":"WELCOME5","items":[{"sku":"BOOK","qty":1}],` + addrNL + `,"shipping":"pickup"}`,
		201, `{"id":4,"subtotal":12.50,"discount":5.00,"shipping":0.00,"total":7.50,"eta":"same day"}`},
	{"lamp already sold", "order", "POST",
		`{"email":"e@x.io","customer_type":"regular","items":[{"sku":"LAMP","qty":1}],` + addrNL + `,"shipping":"standard"}`,
		409, `{"error":"out of stock: LAMP"}`},
	{"wrong method", "order", "GET", ``, 405, ``},
	{"bad json", "order", "POST", `{`, 400, `{"error":"bad json"}`},
	{"invalid email", "order", "POST",
		`{"email":"nope","items":[{"sku":"BOOK","qty":1}],` + addrNL + `,"shipping":"standard"}`,
		422, `{"error":"invalid email"}`},
	{"missing address", "order", "POST",
		`{"email":"a@x.io","items":[{"sku":"BOOK","qty":1}],"shipping":"standard"}`,
		422, `{"error":"address required"}`},
	{"unknown sku", "order", "POST",
		`{"email":"a@x.io","items":[{"sku":"PEN","qty":1}],` + addrNL + `,"shipping":"standard"}`,
		422, `{"error":"unknown sku: PEN"}`},
	{"unknown shipping", "order", "POST",
		`{"email":"a@x.io","items":[{"sku":"BOOK","qty":1}],` + addrNL + `,"shipping":"drone"}`,
		422, `{"error":"unknown shipping: drone"}`},
	{"quote does not reserve stock", "quote", "POST",
		`{"customer_type":"regular","items":[{"sku":"BOOK","qty":2},{"sku":"MUG","qty":1}],"country":"NL","shipping":"standard"}`,
		200, `{"subtotal":33.00,"discount":0.00,"shipping":4.95,"total":37.95}`},
	{"quote keeps the old copy's quirk: unknown shipping costs 0", "quote", "POST",
		`{"customer_type":"vip","items":[{"sku":"BOOK","qty":1}],"country":"NL","shipping":"drone"}`,
		200, `{"subtotal":12.50,"discount":1.25,"shipping":0.00,"total":11.25}`},
	{"quote never validated qty: negative amounts must print like %.2f", "quote", "POST",
		`{"customer_type":"regular","items":[{"sku":"BOOK","qty":-1}],"country":"NL","shipping":"standard"}`,
		200, `{"subtotal":-12.50,"discount":0.00,"shipping":4.95,"total":-7.55}`},
}

// Run replays every step against h and fails on the first difference.
func Run(t *testing.T, h Handlers) {
	t.Helper()
	h.Reset()
	for _, s := range steps {
		target := h.Order
		if s.handler == "quote" {
			target = h.Quote
		}
		req := httptest.NewRequest(s.method, "/"+s.handler, strings.NewReader(s.body))
		rec := httptest.NewRecorder()
		target.ServeHTTP(rec, req)
		if rec.Code != s.wantCode || rec.Body.String() != s.wantBody {
			t.Fatalf("%s:\n got  %d %s\n want %d %s", s.name, rec.Code, rec.Body.String(), s.wantCode, s.wantBody)
		}
	}
}
go
package before

import (
	"net/http"
	"testing"

	"academy/code-smells-refactoring/labtest"
)

func TestCharacterization(t *testing.T) {
	labtest.Run(t, labtest.Handlers{
		Order: http.HandlerFunc(HandleOrder),
		Quote: http.HandlerFunc(HandleQuote),
		Reset: Reset,
	})
}

گام ۲: کپسوله کردن دادهٔ سراسری. Prices، Stock و Orders را به یک Catalog و یک type به نام Orders با متد منتقل کنید (Encapsulate Variable، Encapsulate Collection). go test ./...: سبز.

گام ۳: معرفی Money. float64 را با Money بر حسب سنت عوض کنید (Replace Primitive with Object) و به آن MarshalJSON بدهید که دو رقم اعشار چاپ کند. سبز، چون همهٔ مبلغ‌های تست بر حسب سنت دقیق‌اند؛ اگر کاتالوگ قیمتی مثل 0.333 داشت، این گام گرد کردن را عوض می‌کرد و تست به شما می‌گفت.

گام ۴: extract کردن Address. چهار string یک type می‌شوند (Extract Class) و country == "NL" به Address.Domestic() می‌رود (Move Function، درمان feature envy). سبز.

گام ۵: نام‌گذاری عددها و تجزیهٔ تخفیف. 0.10، 0.30، 5 و "WELCOME5" ثابت می‌شوند؛ if/else تبدیل به CustomerType.Discount با acceptsCoupon می‌شود (Replace Magic Literal، Decompose Conditional). سبز.

گام ۶: جایگزینی هر دو switch ارسال با polymorphism. یک interface به نام ShippingMethod، سه type، یک map. switch مربوط به ETA ناپدید می‌شود چون ETA() کنار Cost() نشسته. سبز.

گام ۷: یک نسخه از قاعده‌های قیمت‌گذاری. Pricer.Price را (یک query خالص) extract کنید و از هر دو handler صدایش بزنید. تست واگرایی‌ای را می‌گیرد که کپی کردن ایجاد کرده بود: HandleQuote برای روش ارسال ناشناخته به جای خطا، صفر حساب می‌کند. refactoring آن را نگه می‌دارد؛ Service.Quote با یک comment به pickup{} برمی‌گردد (Introduce Special Case) و درست کردنش تیکت خودش را می‌گیرد.

گام ۸: Split Phase در handler. decode به یک فرمان PlaceOrder، صدا زدن Service.Place، encode. تلاش اول از json.NewEncoder استفاده کرد که یک newline انتهایی اضافه می‌کند؛ تست بایت‌دقیق شکست خورد؛ json.Marshal همراه با w.Write درستش کرد. سبز.

وضعیت پایانی، فایل‌به‌فایل:

go
// Package after is the lab's end state: the same behaviour as package before,
// reached through small named refactorings, each run against labtest.
package after

import "fmt"

// Money replaces float64 (Replace Primitive with Object): integer cents, no
// float drift, one place that knows how money prints.
type Money int64

// Cents builds Money from a cent amount.
func Cents(c int64) Money { return Money(c) }

// Percent returns p percent of m, truncated to the cent.
func (m Money) Percent(p int64) Money { return m * Money(p) / 100 }

func (m Money) String() string {
	sign := ""
	if m < 0 {
		sign, m = "-", -m
	}
	return fmt.Sprintf("%s%d.%02d", sign, m/100, m%100)
}

// MarshalJSON keeps the wire format of the old handler: a bare number with two decimals.
func (m Money) MarshalJSON() ([]byte, error) { return []byte(m.String()), nil }
go
package after

// HomeCountry is where standard and express shipping are cheaper.
const HomeCountry = "NL"

// Address was a data clump of four strings (Extract Class, Introduce Parameter Object).
type Address struct {
	Street  string `json:"street"`
	City    string `json:"city"`
	Zip     string `json:"zip"`
	Country string `json:"country"`
}

// Complete reports whether every field is present.
func (a Address) Complete() bool {
	return a.Street != "" && a.City != "" && a.Zip != "" && a.Country != ""
}

// Domestic moved here from the handler (Move Function: it was feature envy).
func (a Address) Domestic() bool { return a.Country == HomeCountry }
go
package after

// CustomerType was a bare string compared in two copies of the same if/else.
type CustomerType string

const (
	Regular CustomerType = "regular"
	VIP     CustomerType = "vip"
	Staff   CustomerType = "staff"
)

// Named constants replace the magic numbers 0.10, 0.30 and 5.
const (
	vipDiscountPercent   = 10
	staffDiscountPercent = 30
	welcomeCoupon        = "WELCOME5"
)

var welcomeCouponValue = Cents(500)

// discountPercent is a lookup table: adding a customer type is one line.
var discountPercent = map[CustomerType]int64{VIP: vipDiscountPercent, Staff: staffDiscountPercent}

// Discount is Decompose Conditional applied to the old if/else plus coupon rule.
func (t CustomerType) Discount(subtotal Money, coupon string) Money {
	d := subtotal.Percent(discountPercent[t])
	if t.acceptsCoupon(coupon) {
		d += welcomeCouponValue
	}
	return d
}

func (t CustomerType) acceptsCoupon(coupon string) bool {
	return coupon == welcomeCoupon && t != Staff
}
go
package after

// ShippingMethod replaces the two switches on the shipping string
// (Replace Conditional with Polymorphism). A new method is a new type
// plus one map entry; no switch to hunt down.
type ShippingMethod interface {
	Cost(net Money, to Address) Money
	ETA() string
}

const freeShippingFrom = Money(5000)

type standard struct{}

func (standard) Cost(net Money, to Address) Money {
	switch {
	case net >= freeShippingFrom:
		return 0
	case to.Domestic():
		return Cents(495)
	default:
		return Cents(995)
	}
}
func (standard) ETA() string { return "3-5 days" }

type express struct{}

func (express) Cost(_ Money, to Address) Money {
	if to.Domestic() {
		return Cents(995)
	}
	return Cents(1995)
}
func (express) ETA() string { return "1 day" }

// pickup is also the Special Case used by the quote endpoint for unknown names.
type pickup struct{}

func (pickup) Cost(Money, Address) Money { return 0 }
func (pickup) ETA() string               { return "same day" }

var shippingMethods = map[string]ShippingMethod{
	"standard": standard{},
	"express":  express{},
	"pickup":   pickup{},
}

// ShippingMethodFor returns the method or a validation error.
func ShippingMethodFor(name string) (ShippingMethod, error) {
	m, ok := shippingMethods[name]
	if !ok {
		return nil, invalid("unknown shipping: " + name)
	}
	return m, nil
}
go
package after

import "sync"

// Line is one SKU and a quantity.
type Line struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

// Catalog encapsulates the former global maps (Encapsulate Variable,
// Encapsulate Collection): nobody outside can write prices or stock.
type Catalog struct {
	mu     sync.Mutex
	prices map[string]Money
	stock  map[string]int
}

// NewCatalog returns the demo catalogue used by the lab.
func NewCatalog() *Catalog {
	return &Catalog{
		prices: map[string]Money{"BOOK": Cents(1250), "MUG": Cents(800), "LAMP": Cents(4000)},
		stock:  map[string]int{"BOOK": 10, "MUG": 3, "LAMP": 1},
	}
}

// Price is a query: it never changes state.
func (c *Catalog) Price(sku string) (Money, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	p, ok := c.prices[sku]
	return p, ok
}

// Check validates lines in the same order the old handler did:
// per line, unknown SKU, then quantity, then stock.
func (c *Catalog) Check(lines []Line) error {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.check(lines)
}

func (c *Catalog) check(lines []Line) error {
	for _, l := range lines {
		if _, ok := c.prices[l.SKU]; !ok {
			return invalid("unknown sku: " + l.SKU)
		}
		if l.Qty <= 0 {
			return invalid("invalid qty: " + l.SKU)
		}
		if c.stock[l.SKU] < l.Qty {
			return conflict("out of stock: " + l.SKU)
		}
	}
	return nil
}

// Reserve is the modifier: check and decrement under one lock.
func (c *Catalog) Reserve(lines []Line) error {
	c.mu.Lock()
	defer c.mu.Unlock()
	if err := c.check(lines); err != nil {
		return err
	}
	for _, l := range lines {
		c.stock[l.SKU] -= l.Qty
	}
	return nil
}
go
package after

// Quote is the result record of pricing (immutable in practice, so a data
// class is fine here: Fowler's exception for Split Phase results).
type Quote struct {
	Subtotal Money `json:"subtotal"`
	Discount Money `json:"discount"`
	Shipping Money `json:"shipping"`
	Total    Money `json:"total"`
}

// Pricer is the single copy of the pricing rules that both endpoints use
// (the duplicate code is gone; Separate Query from Modifier: no side effects).
type Pricer struct{ Catalog *Catalog }

// Price computes a quote. Callers validate lines first.
func (p Pricer) Price(lines []Line, t CustomerType, coupon string, ship ShippingMethod, to Address) (Quote, error) {
	var q Quote
	for _, l := range lines {
		price, ok := p.Catalog.Price(l.SKU)
		if !ok {
			return Quote{}, invalid("unknown sku: " + l.SKU)
		}
		q.Subtotal += price * Money(l.Qty)
	}
	q.Discount = t.Discount(q.Subtotal, coupon)
	q.Shipping = ship.Cost(q.Subtotal-q.Discount, to)
	q.Total = q.Subtotal - q.Discount + q.Shipping
	return q, nil
}
go
package after

import (
	"strings"
	"sync"
	"time"
)

// PlaceOrder is the command (Introduce Parameter Object for nine loose fields).
type PlaceOrder struct {
	Email    string       `json:"email"`
	Type     CustomerType `json:"customer_type"`
	Lines    []Line       `json:"items"`
	Address               // embedded: the JSON keeps its flat shape
	Shipping string       `json:"shipping"`
	Coupon   string       `json:"coupon"`
}

// Order is what we store.
type Order struct {
	ID      int
	Email   string
	Total   Money
	Address Address
	Created time.Time
}

// Placed is returned to the HTTP layer.
type Placed struct {
	ID int `json:"id"`
	Quote
	ETA string `json:"eta"`
}

// Orders replaces the global slice (Encapsulate Collection).
type Orders struct {
	mu   sync.Mutex
	list []Order
}

func (o *Orders) add(ord Order) int {
	o.mu.Lock()
	defer o.mu.Unlock()
	ord.ID = len(o.list) + 1
	o.list = append(o.list, ord)
	return ord.ID
}

// All returns a copy; callers cannot append behind our back.
func (o *Orders) All() []Order {
	o.mu.Lock()
	defer o.mu.Unlock()
	return append([]Order(nil), o.list...)
}

// Service is the use case. Each step is one named function call.
type Service struct {
	Catalog *Catalog
	Orders  *Orders
	Pricer  Pricer
	Now     func() time.Time
}

// NewService wires the lab's in-memory pieces.
func NewService() *Service {
	c := NewCatalog()
	return &Service{Catalog: c, Orders: &Orders{}, Pricer: Pricer{Catalog: c}, Now: time.Now}
}

// Place validates, prices, reserves and saves, in the old order of checks.
func (s *Service) Place(cmd PlaceOrder) (Placed, error) {
	if err := validateCustomer(cmd); err != nil {
		return Placed{}, err
	}
	if err := s.Catalog.Check(cmd.Lines); err != nil {
		return Placed{}, err
	}
	ship, err := ShippingMethodFor(cmd.Shipping)
	if err != nil {
		return Placed{}, err
	}
	q, err := s.Pricer.Price(cmd.Lines, cmd.Type, cmd.Coupon, ship, cmd.Address)
	if err != nil {
		return Placed{}, err
	}
	if err := s.Catalog.Reserve(cmd.Lines); err != nil {
		return Placed{}, err
	}
	id := s.Orders.add(Order{Email: cmd.Email, Total: q.Total, Address: cmd.Address, Created: s.Now()})
	return Placed{ID: id, Quote: q, ETA: ship.ETA()}, nil
}

func validateCustomer(cmd PlaceOrder) error {
	switch {
	case cmd.Email == "" || !strings.Contains(cmd.Email, "@"):
		return invalid("invalid email")
	case len(cmd.Lines) == 0:
		return invalid("no items")
	case !cmd.Address.Complete():
		return invalid("address required")
	}
	return nil
}

// Quote prices without side effects. Unknown shipping costs nothing: the old
// HandleQuote copy did that, the characterization test pins it, and changing
// it is a behaviour change for its own commit, not part of this refactoring.
func (s *Service) Quote(cmd PlaceOrder) (Quote, error) {
	ship, err := ShippingMethodFor(cmd.Shipping)
	if err != nil {
		ship = pickup{}
	}
	return s.Pricer.Price(cmd.Lines, cmd.Type, cmd.Coupon, ship, cmd.Address)
}
go
package after

// Kind says which HTTP status an error maps to, without the domain importing net/http.
type Kind int

const (
	Invalid Kind = iota + 1
	Conflict
)

// Error is a domain error with a kind and a message for the client.
type Error struct {
	Kind Kind
	Msg  string
}

func (e *Error) Error() string { return e.Msg }

func invalid(msg string) error  { return &Error{Invalid, msg} }
func conflict(msg string) error { return &Error{Conflict, msg} }
go
package after

import (
	"encoding/json"
	"errors"
	"net/http"
)

// Handler is now a thin adapter: decode, call one use case, encode.
type Handler struct{ Svc *Service }

// Order handles POST /orders.
func (h Handler) Order(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	var cmd PlaceOrder
	if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
		writeJSON(w, http.StatusBadRequest, errorBody{"bad json"})
		return
	}
	placed, err := h.Svc.Place(cmd)
	if err != nil {
		writeError(w, err)
		return
	}
	writeJSON(w, http.StatusCreated, placed)
}

// Quote handles POST /quote.
func (h Handler) Quote(w http.ResponseWriter, r *http.Request) {
	var cmd PlaceOrder
	if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
		writeJSON(w, http.StatusBadRequest, errorBody{"bad json"})
		return
	}
	q, err := h.Svc.Quote(cmd)
	if err != nil {
		writeError(w, err)
		return
	}
	writeJSON(w, http.StatusOK, q)
}

type errorBody struct {
	Error string `json:"error"`
}

var statusOf = map[Kind]int{Invalid: http.StatusUnprocessableEntity, Conflict: http.StatusConflict}

func writeError(w http.ResponseWriter, err error) {
	var e *Error
	if !errors.As(err, &e) {
		writeJSON(w, http.StatusInternalServerError, errorBody{"internal error"})
		return
	}
	writeJSON(w, statusOf[e.Kind], errorBody{e.Msg})
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	body, err := json.Marshal(v) // Marshal, not Encoder: no trailing newline, same bytes as before
	if err != nil {
		code, body = http.StatusInternalServerError, []byte(`{"error":"internal error"}`)
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	_, _ = w.Write(body)
}
go
package after

import (
	"net/http"
	"testing"

	"academy/code-smells-refactoring/labtest"
)

func TestCharacterization(t *testing.T) {
	h := &Handler{Svc: NewService()}
	labtest.Run(t, labtest.Handlers{
		Order: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.Order(w, r) }),
		Quote: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.Quote(w, r) }),
		Reset: func() { h.Svc = NewService() },
	})
}

func TestMoneyIsExact(t *testing.T) {
	if got := Cents(1600).Percent(30).String(); got != "4.80" {
		t.Fatalf("got %s", got)
	}
}

گام ۹: اندازه‌گیری.

معیارقبلبعد
بلندترین تابعHandleOrder، حدود ۱۱۰ خطService.Place، حدود ۲۵ خط
نسخه‌های قاعدهٔ قیمت‌گذاری21 (Pricer.Price)
switch روی string ارسال3 (دو تا در HandleOrder، یکی در HandleQuote)0 (یک lookup در map)
متغیرهای تغییرپذیر سطح package40 (shippingMethods و discountPercent جدول‌های فقط‌خواندنی‌اند)
فایل‌هایی که «ارسال رایگان از ۶۰» لمس می‌کند1 فایل، 2 جا1 ثابت
فایل‌هایی که «افزودن ارسال پیک» لمس می‌کند3 switch1 type تازه + 1 ورودی map
Characterization testPASSPASS (همان ۱۴ حالت، بایت‌دقیق)

گام ۱۰ (اختیاری): linterها را روی هر دو اجرا کنید. golangci-lint run --enable funlen,gocognit,dupl,mnd,gochecknoglobals ./... باید در before/ تابع بلند، بلوک تکراری، عددهای جادویی و متغیرهای سراسری را گزارش کند؛ در after/ فقط جدول‌های lookup فقط‌خواندنی عمدی (shippingMethods، discountPercent، statusOf) و مبلغ‌های سنتی نام‌دار داخل shipping.go می‌مانند که می‌توانید بپذیرید یا ثابت کنید. (برای این صفحه اجرا نشده.)

بخش ب: Laravel ​

همان دامنه در یک اپ Laravel 13 (PHP 8.4). اینجا php اجرا نمی‌شود؛ فایل‌ها بازبینی شده‌اند، نه اجرا. route ما Route::post('/orders', [OrderController::class, 'store']) در routes/api.php است، با modelهای Product (sku، price از نوع decimal:2، stock) و Order؛ Order برای Order::create() در کد بعد به $fillable نیاز دارد.

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

// The smelly starting point of the Laravel lab: one controller method that
// validates, prices, ships, reserves stock, saves and emails.
class OrderController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        // validate
        $data = $request->validate([
            'email' => 'required|email',
            'customer_type' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.sku' => 'required|string',
            'items.*.qty' => 'required|integer|min:1',
            'street' => 'required', 'city' => 'required', 'zip' => 'required', 'country' => 'required',
            'shipping' => 'required|string',
            'coupon' => 'nullable|string',
        ]);

        return DB::transaction(function () use ($data) {
            // subtotal and stock, floats for money
            $subtotal = 0.0;
            foreach ($data['items'] as $item) {
                $product = Product::where('sku', $item['sku'])->lockForUpdate()->first();
                if (! $product) {
                    return response()->json(['error' => 'unknown sku: '.$item['sku']], 422);
                }
                if ($product->stock < $item['qty']) {
                    return response()->json(['error' => 'out of stock: '.$item['sku']], 409);
                }
                $subtotal += $product->price * $item['qty'];
            }

            // discount
            $discount = 0.0;
            if (($data['customer_type'] ?? 'regular') == 'vip') {
                $discount = $subtotal * 0.10;
            } elseif (($data['customer_type'] ?? 'regular') == 'staff') {
                $discount = $subtotal * 0.30;
            }
            if (($data['coupon'] ?? null) == 'WELCOME5' && ($data['customer_type'] ?? 'regular') != 'staff') {
                $discount += 5;
            }

            // shipping
            switch ($data['shipping']) {
                case 'standard':
                    $shipping = $subtotal - $discount >= 50 ? 0 : ($data['country'] == 'NL' ? 4.95 : 9.95);
                    break;
                case 'express':
                    $shipping = $data['country'] == 'NL' ? 9.95 : 19.95;
                    break;
                case 'pickup':
                    $shipping = 0;
                    break;
                default:
                    return response()->json(['error' => 'unknown shipping: '.$data['shipping']], 422);
            }
            $total = $subtotal - $discount + $shipping;

            // reserve stock
            foreach ($data['items'] as $item) {
                Product::where('sku', $item['sku'])->decrement('stock', $item['qty']);
            }

            // save
            $order = new Order;
            $order->email = $data['email'];
            $order->street = $data['street'];
            $order->city = $data['city'];
            $order->zip = $data['zip'];
            $order->country = $data['country'];
            $order->total = $total;
            $order->save();

            // email, inside the transaction, on the request path
            Mail::raw('Thanks for order #'.$order->id, fn ($m) => $m->to($data['email'])->subject('Your order'));

            // the same switch again
            $eta = match ($data['shipping']) {
                'standard' => '3-5 days',
                'express' => '1 day',
                'pickup' => 'same day',
            };

            return response()->json([
                'id' => $order->id,
                'subtotal' => round($subtotal, 2),
                'discount' => round($discount, 2),
                'shipping' => round($shipping, 2),
                'total' => round($total, 2),
                'eta' => $eta,
            ], 201);
        });
    }
}

گام ۱: characterization test روی controller قدیمی. به floatهای دقیق دقت کنید: کد قدیمی 33.0 برمی‌گرداند، نه 33.

php
<?php

namespace Tests\Feature;

use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

// Characterization tests: written against the OLD controller first, kept green
// after every refactoring step. They pin today's behaviour, quirks included.
final class OrderCharacterizationTest extends TestCase
{
    use RefreshDatabase;

    private const ADDRESS_NL = ['street' => 'Main 1', 'city' => 'Utrecht', 'zip' => '3511', 'country' => 'NL'];

    private const ADDRESS_DE = ['street' => 'Hauptstr 2', 'city' => 'Berlin', 'zip' => '10115', 'country' => 'DE'];

    protected function setUp(): void
    {
        parent::setUp();
        Mail::fake();
        Queue::fake();
        Product::insert([
            ['sku' => 'BOOK', 'price' => '12.50', 'stock' => 10],
            ['sku' => 'MUG', 'price' => '8.00', 'stock' => 3],
            ['sku' => 'LAMP', 'price' => '40.00', 'stock' => 1],
        ]);
    }

    public function test_regular_customer_standard_shipping_in_nl(): void
    {
        $this->postJson('/api/orders', [
            'email' => 'a@x.io', 'customer_type' => 'regular', 'shipping' => 'standard',
            'items' => [['sku' => 'BOOK', 'qty' => 2], ['sku' => 'MUG', 'qty' => 1]],
            ...self::ADDRESS_NL,
        ])->assertCreated()->assertExactJson([
            'id' => 1, 'subtotal' => 33.0, 'discount' => 0.0, 'shipping' => 4.95, 'total' => 37.95, 'eta' => '3-5 days',
        ]);

        $this->assertSame(8, Product::firstWhere('sku', 'BOOK')->stock);
    }

    public function test_vip_gets_ten_percent_and_free_standard_shipping_over_fifty(): void
    {
        $this->postJson('/api/orders', [
            'email' => 'b@x.io', 'customer_type' => 'vip', 'shipping' => 'standard',
            'items' => [['sku' => 'LAMP', 'qty' => 1], ['sku' => 'BOOK', 'qty' => 2]],
            ...self::ADDRESS_DE,
        ])->assertCreated()->assertJson(['discount' => 6.5, 'shipping' => 0, 'total' => 58.5]);
    }

    public function test_staff_discount_ignores_the_coupon(): void
    {
        $this->postJson('/api/orders', [
            'email' => 'c@x.io', 'customer_type' => 'staff', 'coupon' => 'WELCOME5', 'shipping' => 'express',
            'items' => [['sku' => 'MUG', 'qty' => 2]],
            ...self::ADDRESS_DE,
        ])->assertCreated()->assertJson(['discount' => 4.8, 'shipping' => 19.95, 'total' => 31.15, 'eta' => '1 day']);
    }

    public function test_unknown_customer_type_is_treated_as_regular(): void
    {
        $this->postJson('/api/orders', [
            'email' => 'd@x.io', 'customer_type' => 'gold', 'shipping' => 'pickup',
            'items' => [['sku' => 'BOOK', 'qty' => 1]],
            ...self::ADDRESS_NL,
        ])->assertCreated()->assertJson(['discount' => 0, 'total' => 12.5]);
    }

    public function test_out_of_stock_is_a_conflict_and_changes_nothing(): void
    {
        $this->postJson('/api/orders', [
            'email' => 'e@x.io', 'shipping' => 'standard',
            'items' => [['sku' => 'BOOK', 'qty' => 1], ['sku' => 'LAMP', 'qty' => 2]],
            ...self::ADDRESS_NL,
        ])->assertConflict()->assertExactJson(['error' => 'out of stock: LAMP']);

        $this->assertSame(10, Product::firstWhere('sku', 'BOOK')->stock);
        $this->assertDatabaseCount('orders', 0);
    }

    public function test_unknown_sku_and_unknown_shipping_are_unprocessable(): void
    {
        $this->postJson('/api/orders', [
            'email' => 'f@x.io', 'shipping' => 'standard', 'items' => [['sku' => 'PEN', 'qty' => 1]], ...self::ADDRESS_NL,
        ])->assertUnprocessable()->assertExactJson(['error' => 'unknown sku: PEN']);

        $this->postJson('/api/orders', [
            'email' => 'f@x.io', 'shipping' => 'drone', 'items' => [['sku' => 'BOOK', 'qty' => 1]], ...self::ADDRESS_NL,
        ])->assertUnprocessable()->assertExactJson(['error' => 'unknown shipping: drone']);
    }
}

گام ۲: value objectهای Money و Address. مراقب قالب سیم باشید: کد قدیمی 33.0 می‌فرستد؛ jsonSerialize(): float و تقسیم بر 100.0 آن را float نگه می‌دارد. (PHP برای این صفحه اجرا نشده؛ تست‌ها بازبینی شده‌اند، نه اجرا.)

php
<?php

namespace App\Domain\Orders;

use JsonSerializable;

// Replace Primitive with Object: integer cents instead of float.
final readonly class Money implements JsonSerializable
{
    private function __construct(public int $cents) {}

    public static function cents(int $cents): self
    {
        return new self($cents);
    }

    // Products store price as a decimal:2 column, which Eloquent casts to a string like "12.50".
    public static function fromDecimal(string $amount): self
    {
        return new self((int) round(((float) $amount) * 100));
    }

    public static function zero(): self
    {
        return new self(0);
    }

    public function plus(self $other): self
    {
        return new self($this->cents + $other->cents);
    }

    public function minus(self $other): self
    {
        return new self($this->cents - $other->cents);
    }

    public function times(int $qty): self
    {
        return new self($this->cents * $qty);
    }

    public function percent(int $p): self
    {
        return new self(intdiv($this->cents * $p, 100));
    }

    public function atLeast(self $other): bool
    {
        return $this->cents >= $other->cents;
    }

    // Keeps the old wire format: a float such as 33.0, as round() produced before.
    public function jsonSerialize(): float
    {
        return $this->cents / 100.0;
    }
}
php
<?php

namespace App\Domain\Orders;

// The data clump street/city/zip/country becomes one value object.
final readonly class Address
{
    public const HOME_COUNTRY = 'NL';

    public function __construct(
        public string $street,
        public string $city,
        public string $zip,
        public string $country,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self($data['street'], $data['city'], $data['zip'], $data['country']);
    }

    public function isDomestic(): bool
    {
        return $this->country === self::HOME_COUNTRY;
    }
}

گام ۳: enumهای رفتاردار جای کدهای نوع string و هر دو switch را می‌گیرند.

php
<?php

namespace App\Domain\Orders;

// A backed enum replaces the 'vip' / 'staff' strings compared in if/elseif chains.
enum CustomerType: string
{
    case Regular = 'regular';
    case Vip = 'vip';
    case Staff = 'staff';

    private const WELCOME_COUPON = 'WELCOME5';

    private const WELCOME_COUPON_CENTS = 500;

    public function discount(Money $subtotal, ?string $coupon): Money
    {
        $discount = $subtotal->percent($this->discountPercent());

        return $this->acceptsCoupon($coupon)
            ? $discount->plus(Money::cents(self::WELCOME_COUPON_CENTS))
            : $discount;
    }

    private function discountPercent(): int
    {
        return match ($this) {
            self::Regular => 0,
            self::Vip => 10,
            self::Staff => 30,
        };
    }

    private function acceptsCoupon(?string $coupon): bool
    {
        return $coupon === self::WELCOME_COUPON && $this !== self::Staff;
    }
}
php
<?php

namespace App\Domain\Orders;

// Replace Conditional with Polymorphism, PHP 8.1+ style: each case owns its rules.
// The single match per method is exhaustive; adding a case without a rule is a
// fatal UnhandledMatchError in tests, not a silent zero.
enum ShippingMethod: string
{
    case Standard = 'standard';
    case Express = 'express';
    case Pickup = 'pickup';

    private const FREE_FROM_CENTS = 5000;

    public function cost(Money $net, Address $to): Money
    {
        return match ($this) {
            self::Standard => match (true) {
                $net->atLeast(Money::cents(self::FREE_FROM_CENTS)) => Money::zero(),
                $to->isDomestic() => Money::cents(495),
                default => Money::cents(995),
            },
            self::Express => Money::cents($to->isDomestic() ? 995 : 1995),
            self::Pickup => Money::zero(),
        };
    }

    public function eta(): string
    {
        return match ($this) {
            self::Standard => '3-5 days',
            self::Express => '1 day',
            self::Pickup => 'same day',
        };
    }
}

گام ۴: یک تابع قیمت‌گذاری خالص و یک parameter object.

php
<?php

namespace App\Domain\Orders;

// Result record of pricing; immutable, so being "just data" is fine here.
final readonly class PriceQuote
{
    public function __construct(
        public Money $subtotal,
        public Money $discount,
        public Money $shipping,
        public Money $total,
    ) {}

    /**
     * Pure calculation (Separate Query from Modifier): no database, no side effects.
     *
     * @param  list<array{price: Money, qty: int}>  $lines
     */
    public static function calculate(array $lines, CustomerType $type, ?string $coupon, ShippingMethod $method, Address $to): self
    {
        $subtotal = array_reduce($lines, fn (Money $sum, array $l) => $sum->plus($l['price']->times($l['qty'])), Money::zero());
        $discount = $type->discount($subtotal, $coupon);
        $shipping = $method->cost($subtotal->minus($discount), $to);

        return new self($subtotal, $discount, $shipping, $subtotal->minus($discount)->plus($shipping));
    }

    public function toArray(): array
    {
        return [
            'subtotal' => $this->subtotal,
            'discount' => $this->discount,
            'shipping' => $this->shipping,
            'total' => $this->total,
        ];
    }
}
php
<?php

namespace App\Domain\Orders;

// Introduce Parameter Object: one typed command instead of an untyped array.
// shippingName stays a string on purpose: the old controller rejected an unknown
// method only after the stock checks, and the characterization test pins that order.
final readonly class PlaceOrderData
{
    /** @param list<array{sku: string, qty: int}> $items */
    public function __construct(
        public string $email,
        public CustomerType $type,
        public array $items,
        public Address $address,
        public string $shippingName,
        public ?string $coupon,
    ) {}
}

گام ۵: Form Request، Action و یک exception قابل‌render. نوع مشتری ناشناخته هنوز regular حساب می‌شود و ارسال ناشناخته هنوز بعد از چک موجودی رد می‌شود، چون تست‌ها همین را می‌گویند؛ سخت‌گیرتر کردنش با Rule::enum یک commit بعدی و تغییردهندهٔ رفتار است.

php
<?php

namespace App\Http\Requests;

use App\Domain\Orders\Address;
use App\Domain\Orders\CustomerType;
use App\Domain\Orders\PlaceOrderData;
use Illuminate\Foundation\Http\FormRequest;

// Validation leaves the controller (Extract Class into Laravel's slot for it).
final class PlaceOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'email' => ['required', 'email'],
            'customer_type' => ['nullable', 'string'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.sku' => ['required', 'string'],
            'items.*.qty' => ['required', 'integer', 'min:1'],
            'street' => ['required'], 'city' => ['required'], 'zip' => ['required'], 'country' => ['required'],
            'shipping' => ['required', 'string'],
            'coupon' => ['nullable', 'string'],
        ];
    }

    public function toData(): PlaceOrderData
    {
        return new PlaceOrderData(
            email: $this->validated('email'),
            // unknown types were treated as regular before; keep it (tighten later, in its own commit)
            type: CustomerType::tryFrom($this->validated('customer_type') ?? '') ?? CustomerType::Regular,
            items: $this->validated('items'),
            address: Address::fromArray($this->safe()->only(['street', 'city', 'zip', 'country'])),
            shippingName: $this->validated('shipping'),
            coupon: $this->validated('coupon'),
        );
    }
}
php
<?php

namespace App\Domain\Orders;

use Illuminate\Http\JsonResponse;
use RuntimeException;

// A renderable exception: Laravel calls render() automatically, and throwing
// inside DB::transaction rolls the transaction back.
final class OrderRejected extends RuntimeException
{
    private function __construct(string $message, private readonly int $status)
    {
        parent::__construct($message);
    }

    public static function unknownSku(string $sku): self
    {
        return new self('unknown sku: '.$sku, 422);
    }

    public static function outOfStock(string $sku): self
    {
        return new self('out of stock: '.$sku, 409);
    }

    public static function unknownShipping(string $name): self
    {
        return new self('unknown shipping: '.$name, 422);
    }

    public function render(): JsonResponse
    {
        return response()->json(['error' => $this->getMessage()], $this->status);
    }
}
php
<?php

namespace App\Actions;

use App\Domain\Orders\Money;
use App\Domain\Orders\OrderRejected;
use App\Domain\Orders\PlaceOrderData;
use App\Domain\Orders\PriceQuote;
use App\Domain\Orders\ShippingMethod;
use App\Events\OrderPlaced;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\DB;

// The use case. Each line is one named step; the controller no longer knows them.
final class PlaceOrder
{
    /** @return array{order: Order, quote: PriceQuote, method: ShippingMethod} */
    public function handle(PlaceOrderData $data): array
    {
        return DB::transaction(function () use ($data) {
            $products = $this->lockProducts($data->items);
            $lines = array_map(fn (array $i) => [
                'price' => Money::fromDecimal($products[$i['sku']]->price),
                'qty' => $i['qty'],
            ], $data->items);

            $method = ShippingMethod::tryFrom($data->shippingName)
                ?? throw OrderRejected::unknownShipping($data->shippingName);

            $quote = PriceQuote::calculate($lines, $data->type, $data->coupon, $method, $data->address);

            foreach ($data->items as $item) {
                $products[$item['sku']]->decrement('stock', $item['qty']);
            }

            $order = Order::create([
                'email' => $data->email,
                'street' => $data->address->street,
                'city' => $data->address->city,
                'zip' => $data->address->zip,
                'country' => $data->address->country,
                'total' => $quote->total->cents / 100.0,
            ]);

            OrderPlaced::dispatch($order);

            return ['order' => $order, 'quote' => $quote, 'method' => $method];
        });
    }

    /** @return array<string, Product> keyed by SKU, rows locked FOR UPDATE */
    private function lockProducts(array $items): array
    {
        $products = Product::whereIn('sku', array_column($items, 'sku'))
            ->lockForUpdate()
            ->get()
            ->keyBy('sku')
            ->all();

        foreach ($items as $item) {
            $product = $products[$item['sku']] ?? throw OrderRejected::unknownSku($item['sku']);
            if ($product->stock < $item['qty']) {
                throw OrderRejected::outOfStock($item['sku']);
            }
        }

        return $products;
    }
}

گام ۶: controller نازک.

php
<?php

namespace App\Http\Controllers;

use App\Actions\PlaceOrder;
use App\Http\Requests\PlaceOrderRequest;
use Illuminate\Http\JsonResponse;

// The controller translates HTTP into one call and back. Nothing else.
final class OrderController extends Controller
{
    public function store(PlaceOrderRequest $request, PlaceOrder $placeOrder): JsonResponse
    {
        ['order' => $order, 'quote' => $quote, 'method' => $method] = $placeOrder->handle($request->toData());

        return response()->json([
            'id' => $order->id,
            ...$quote->toArray(),
            'eta' => $method->eta(),
        ], 201);
    }
}

گام ۷: تغییر رفتار، آگاهانه و در آخر. فرستادن ایمیل به‌صورت همگام داخل تراکنش مشکل واقعی است (timeout سرور ایمیل قفل ردیف‌ها را نگه می‌دارد)، اما جابه‌جا کردنش زمان‌بندی را عوض می‌کند، پس commit و تست خودش را دارد (Queue::fake() / Event::fake())، بعد از اینکه همهٔ commitهای refactoring merge شدند.

php
<?php

namespace App\Events;

use App\Models\Order;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

final class OrderPlaced
{
    use Dispatchable, SerializesModels;

    public function __construct(public Order $order) {}
}
php
<?php

namespace App\Listeners;

use App\Events\OrderPlaced;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Support\Facades\Mail;

// The email left the transaction and the request path. This is a behaviour
// change (timing), so it ships in its own commit with its own test, after the
// refactoring commits.
final class SendOrderConfirmation implements ShouldQueueAfterCommit
{
    public function handle(OrderPlaced $event): void
    {
        Mail::raw('Thanks for order #'.$event->order->id, fn ($m) => $m->to($event->order->email)->subject('Your order'));
    }
}

گام ۸: بگذارید ابزارها خط را نگه دارند. PHPStan را اضافه کنید (از سطحی که کد پاس می‌شود شروع کنید، baseline بسازید، در هر PR یک سطح بالا بروید)، Rector را با مجموعه‌های deadCode و codeQuality به‌صورت --dry-run در CI، و Pint را برای سبک تا diffهای refactoring نویز فاصله‌گذاری نداشته باشند.

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

باورواقعیت
refactoring یعنی هر تمیزکاری یا بازنویسیدنباله‌ای از حرکت‌های کوچک حافظ رفتار است؛ build شکسته برای چند روز یعنی restructuring
بو ثابت می‌کند کد بد است"smells don't always indicate a problem"؛ دلیلی برای نگاه کردن است
comment بو استcommentی که "as a deodorant" به کار رفته بو است؛ commentهای «چرا» "a sweet smell" هستند
هر switch باید polymorphism شودFowler در ۲۰۱۸ نام بو را Repeated Switches گذاشت؛ یک switch اشکالی ندارد
همهٔ تکرارها را باید یک‌جا حذف کردقاعدهٔ سه؛ تکرار تصادفی بین مالک‌های متفاوت می‌ماند
classهای کوچک‌تر همیشه بهترندشکستن بیش از حد Shotgun Surgery می‌سازد؛ Inline Class هم یک refactoring است
یک sprint برای refactoring لازم استبیشتر refactoringها preparatory، comprehension یا litter-pickup و چنددقیقه‌ای‌اند
اگر دقیق باشید بدون تست هم می‌شود refactor کردبدون تور نمی‌دانید رفتار حفظ شده؛ اول characterization test بنویسید
Pint کد را refactor می‌کندPint فقط سبک را درست می‌کند؛ Rector و IDEها refactor می‌کنند
عوض کردن API بین سرویس‌ها refactoring استتغییر قرارداد است؛ نسخه‌گذاری یا expand/contract
data class همیشه غلط استرکوردهای نتیجه، DTOها و مقدارهای immutable استثنای صریح Fowler‌اند
Go ارث‌بری ندارد، پس بوهای ارث‌بری در آن نیستembedding همان Refused Bequest و Middle Man را می‌سازد؛ درمان، فیلد به جای embedding است

چکیده ​

موضوعبه خاطر بسپارید
تعریفساختار را عوض کن نه رفتار مشاهده‌پذیر را، در گام‌های کوچک، تست‌ها بعد از هر گام سبز
بو"a surface indication that usually corresponds to a deeper problem"؛ نگاه کن، بعد تصمیم بگیر
خانواده‌هاBloaters، OO Abusers، Change Preventers، Dispensables، Couplers (refactoring.guru)
تغییرهای ۲۰۱۸تازه: Mysterious Name، Global Data، Mutable Data، Loops؛ تغییر نام: Long Function، Repeated Switches، Lazy Element، Insider Trading
حرکت‌های اصلیExtract Function، Rename، Move Function، Extract Class، Introduce Parameter Object، Replace Conditional with Polymorphism
زمان‌بندیpreparatory، comprehension، litter-pickup، گام refactor در TDD؛ قاعدهٔ سه برای تکرار
دو کلاههرگز در یک گام یا commit هم refactor نکنید هم رفتار را عوض کنید
کد legacyاول characterization test (golden master)
تغییرهای بزرگParallel Change (expand، migrate، contract)، Branch by Abstraction
ضدالگوهاBlob، Lava Flow، Golden Hammer، Poltergeists، Boat Anchor، Cut-and-Paste، Spaghetti، Magic Numbers، Cargo Cult
بوهای معماریCyclic، Hub-Like، Unstable Dependency، God Component، Shared Database، Distributed Monolith
ابزارهای Gogofmt -r، code actionهای gopls، vet، staticcheck، golangci-lint (funlen، gocognit، dupl، mnd، unused، unparam)
ابزارهای PHPسطح‌های 0 تا 10 در PHPStan + baseline، مجموعه‌ها و سطح‌های Rector، Pint برای سبک، refactoringهای PhpStorm
میکروسرویسداخل سرویس refactor، بین سرویس‌ها قرارداد نسخه‌دار؛ بیرون کشیدن با Strangler Fig بعد از حرکت‌های درون‌پروسه‌ای

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

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

۱ — چه دو شرطی یک تغییر کد را refactoring می‌کند؟ حیاتی ​

پاسخ

پاسخ: رفتار مشاهده‌پذیر عوض نمی‌شود، و تغییر به‌صورت دنباله‌ای از گام‌های کوچک حافظ رفتار انجام می‌شود که بعد از هر کدام سیستم کار می‌کند. تعریف را ببینید.

۲ — divergent change و shotgun surgery: کدام کدام است؟ حیاتی ​

پاسخ

پاسخ: Divergent change: یک ماژول، دلیل‌های زیاد برای تغییر. Shotgun surgery: یک دلیل تغییر، ماژول‌های زیاد برای ویرایش. Divergent Change و Shotgun Surgery را ببینید.

۳ — چرا Fowler در ۲۰۱۸ نام «Switch Statements» را به «Repeated Switches» عوض کرد؟ تکمیلی ​

پاسخ

پاسخ: polymorphism دیگر کم‌استفاده نیست و switchهای امروزی غنی‌ترند؛ مشکل واقعی همان منطق انتخاب در چند جاست، که افزودن یک حالت یعنی پیدا کردن همه‌شان. Switch Statements را ببینید.

۴ — همان ۶ خط را در دو جا پیدا می‌کنید. extractشان می‌کنید؟ حیاتی ​

پاسخ

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

۵ — controller قدیمی تست ندارد و باید عوضش کنید. گام اول؟ حیاتی ​

پاسخ

پاسخ: characterization testهایی بنویسید که رفتار فعلی را میخ کنند (پاسخ‌های دقیق، اثرهای جانبی)، روی کد قدیمی پاسشان کنید، بعد refactor کنید. تور ایمنی را ببینید.

۶ — وسط refactoring، characterization test نشان می‌دهد endpoint قیمت برای ارسال ناشناخته صفر حساب می‌کند. چه می‌کنید؟ مهم ​

پاسخ

پاسخ: رفتار را نگه دارید (refactoring نباید عوضش کند)، مستندش کنید، و بعداً در commit جداگانه پس از تصمیم محصول عوضش کنید. آزمایشگاه، گام ۷ را ببینید.

۷ — برای پیدا کردن تابع بلند، تکرار، عدد جادویی و متغیر سراسری کدام linterهای golangci-lint را روشن می‌کنید؟ مهم ​

پاسخ

پاسخ: funlen / gocognit، dupl، mnd (و goconst)، gochecknoglobals. ابزارهای Go را ببینید.

۸ — آیا Laravel Pint ابزار refactoring است؟ حیاتی ​

پاسخ

پاسخ: نه. اصلاح‌کنندهٔ سبک کد است که روی PHP CS Fixer ساخته شده و هرگز ساختار را عوض نمی‌کند. Rector و PhpStorm refactor می‌کنند؛ PHPStan تور ایمنی است. ابزارهای PHP را ببینید.

۹ — Refused Bequest در Go که ارث‌بری ندارد چطور ظاهر می‌شود و چطور درستش می‌کنید؟ تکمیلی ​

پاسخ

پاسخ: از راه struct embedding: type بیرونی همهٔ متدهای type جاسازی‌شده را صادر می‌کند و مجبور است بعضی را رد کند. embedding را با یک فیلد عوض کنید و فقط متدهای لازم را forward کنید (Replace Superclass with Delegate). Refused Bequest را ببینید.

۱۰ — فرق بو و ضدالگو چیست؟ حیاتی ​

پاسخ

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

۱۱ — چرا rename یک فیلد در رویدادی منتشرشده refactoring نیست؟ حیاتی ​

پاسخ

پاسخ: سرویس‌های دیگر رویداد را می‌بینند؛ شکلش جزو رفتار است. از نسخه‌گذاری یا Parallel Change (expand، migrate، contract) استفاده کنید. میکروسرویس را ببینید.

۱۲ — سه بوی معماری را که Arcan از گراف وابستگی پیدا می‌کند نام ببرید و برای هر کدام یک درمان. تکمیلی ​

پاسخ

پاسخ: Cyclic Dependency (مفهوم مشترک را extract کنید یا یک یال را با interface برعکس کنید)، Hub-Like Dependency (هاب را بر اساس هدف بشکنید)، Unstable Dependency (به سمت پایداری وابسته شوید و تکهٔ پرنوسان را پشت interface ببرید). بوهای معماری را ببینید.

واژه‌نامه ​

اصطلاحمعنا
بازآرایی، اسم (Refactoring)تغییری در ساختار داخلی که رفتار را حفظ می‌کند و کد را فهمیدنی‌تر و تغییرش را ارزان‌تر می‌کند
بازآرایی، فعل (Refactoring)بازسازی نرم‌افزار با اعمال دنباله‌ای از refactoringها بدون تغییر رفتار مشاهده‌پذیر
بازسازی (Restructuring)هر جابه‌جایی در کد؛ refactoring نوع منضبط و گام‌کوچک آن است
بوی کد (Code smell)نشانه‌ای سطحی و زود دیدنی که معمولاً به مشکلی عمیق‌تر در طراحی اشاره می‌کند
ضدالگو (Anti-pattern)راه‌حلی تکراری که درست به نظر می‌رسد ولی عیبش از سودش بیشتر است، همراه با راه‌حل refactorشده
بوی معماری (Architectural smell)بویی در ساختار وابستگی بین مؤلفه‌ها (چرخه، هاب، وابستگی ناپایدار)
Bloaters / OO Abusers / Change Preventers / Dispensables / Couplersپنج خانوادهٔ بو در refactoring.guru
Long Method / Long Functionتابعی بلندتر از آنکه با یک نگاه فهمیده شود؛ درمان با Extract Function
Large Classtypeی با فیلدها و مسئولیت‌های بیش از حد
Primitive Obsession (وسواس primitive)مفهوم‌های دامنه در primitiveها ("stringly typed")
Long Parameter Listپارامترهای بیش از حد، اغلب پرچم
Data Clumps (دسته‌های داده)مقدارهایی که همیشه با هم می‌آیند و می‌خواهند type شوند
Switch Statements / Repeated Switchesهمان شرط روی یک کد نوع در چند جا
Temporary Fieldفیلدی که فقط در بعضی شرایط مقدار می‌گیرد
Refused Bequest (میراث ردشده)زیرنوعی که ارثش را نمی‌خواهد
Alternative Classes with Different Interfacestypeهایی که یک کار را با نام‌های متد متفاوت می‌کنند
Divergent Change (تغییر واگرا)یک ماژول که به دلایل بی‌ربط زیاد تغییر می‌کند
Shotgun Surgery (جراحی ساچمه‌ای)یک تغییر که ویرایش‌های کوچک زیادی در ماژول‌ها می‌خواهد
Parallel Inheritance Hierarchiesافزودن زیرکلاس در یک سلسله‌مراتب، یکی در دیگری را هم لازم می‌کند
Comments (بو)commentی که خوشبوکنندهٔ کد نامفهوم است
Duplicate Code / Duplicated Codeهمان منطق در بیش از یک جا
Lazy Class / Lazy Elementclass یا تابعی که دیگر ارزش نگه داشتن ندارد
Data Classفقط فیلد و accessor؛ رفتار جای دیگر
Dead Code (کد مرده)کدی که هرگز اجرا نمی‌شود
Speculative Generality (عمومیت حدسی)انتزاع برای نیازهایی که هرگز نیامدند
Feature Envy (حسادت قابلیت)تابعی که به دادهٔ ماژول دیگر بیشتر از دادهٔ خودش علاقه دارد
Inappropriate Intimacy / Insider Tradingماژول‌هایی که از جزئیات داخلی هم زیادی خبر دارند
Message Chainsپیمودن زنجیره‌ای از شیءها که client را به ساختار وابسته می‌کند
Middle Mantypeی که بیشتر فقط delegate می‌کند
Incomplete Library Classtype کتابخانه‌ای که متد لازم را ندارد
Mysterious Name / Global Data / Mutable Data / Loopsچهار بویی که در ویرایش ۲۰۱۸ Fowler اضافه شدند
Extract Function / Inline Functionنام‌گذاری یک تکه به‌صورت تابع / برگرداندن بدنهٔ تابع به جای فراخوانی‌ها
Extract Variableنام‌گذاری یک زیرعبارت
Change Function Declarationrename یک تابع یا تغییر پارامترهایش
Move Function / Move Fieldبردن رفتار یا داده به ماژولی که مالک آن است
Replace Temp with Queryتبدیل متغیر موقت به تابع
Introduce Parameter Objectجمع کردن پارامترها در یک type
Preserve Whole Objectدادن خود شیء به جای مقدارهایی که از آن بیرون کشیده شده
Remove Flag Argumentجایگزینی پارامتر boolean با تابع‌های صریح
Replace Primitive with Objectپیچیدن یک primitive در type دامنه
Replace Conditional with Polymorphismجایگزینی switch روی نوع با یک پیاده‌سازی برای هر حالت
Replace Type Code with Subclassesتبدیل کد نوع به type (aliasها: Extract Subclass، Replace Type Code with State/Strategy)
Decompose Conditionalextract کردن شرط و شاخه‌ها به تابع‌های نام‌دار
Extract Class / Inline Classشکستن یک type به دو / ادغام دوباره
Pull Up Method / Push Down Methodبردن متد به والد / به زیرکلاس‌ها
Replace Superclass with Delegateجایگزینی ارث‌بری با فیلد و forward (alias Replace Inheritance with Delegation)
Introduce Special Casetypeی برای مقدار خاص با رفتار پیش‌فرض (alias Introduce Null Object)
Separate Query from Modifierجدا کردن تابعی که هم جواب می‌دهد هم state را عوض می‌کند
Encapsulate Collectionهرگز collection داخلی را بیرون ندهید؛ کپی برگردانید
Encapsulate Variableپیچیدن دسترسی به داده در تابع برای کنترل و ردگیری
Split Phaseجدا کردن دو مرحله با یک ساختار دادهٔ میانی
Combine Functions into Classگروه کردن تابع‌هایی که داده‌ای مشترک دارند در یک type
Hide Delegate / Remove Middle Manافزودن / حذف متدهای forward
Replace Magic Literalنام‌گذاری یک مقدار ثابت
دو کلاه (Two hats)افزودن رفتار و refactoring دو فعالیت جدا هستند
قاعدهٔ سه (Rule of three)refactor تکرار در بار سوم
Preparatory / comprehension / litter-pickup / planned / long-term refactoringجریان‌های refactoring از Fowler
Opportunistic refactoring (فرصت‌طلبانه)refactor هر جا و هر وقت لازم شد، به دست هر کسی که دید؛ قانون اردوگاه
Red-Green-Refactorچرخهٔ TDD: تست شکست‌خورده، کد پاس‌کننده، تمیزکاری
Characterization test / Golden Masterتستی که رفتار فعلی کد legacy را میخ می‌کند
Parallel Change (expand and contract)تغییر یک interface در سه مرحله: گسترش، مهاجرت، جمع کردن
Branch by Abstractionجایگزینی یک مؤلفه پشت یک interface در حالی که انتشار منظم ادامه دارد
Strangler Figجایگزینی تدریجی یک سیستم legacy با هدایت قابلیت‌ها به کد تازه
God Object / Blobیک class که رفتار را در انحصار دارد
Spaghetti Code / Cut-and-Paste Programming / Golden Hammer / Lava Flow / Poltergeists / Boat Anchorضدالگوهای توسعه در AntiPatterns (۱۹۹۸)
Magic Numberمقدار ثابت بی‌توضیح
Cargo Cult Programmingساختار آیینی بدون هدف واقعی
Cyclic / Hub-Like / Unstable Dependency، God Componentبوهای معماری که Arcan پیدا می‌کند
Shared Databaseچند سرویس که از جدول‌های یکسان می‌خوانند و در آن‌ها می‌نویسند
Distributed Monolithسرویس‌هایی که باید با هم تغییر کنند و deploy شوند
بدهی فنی (Technical debt)هزینهٔ اضافهٔ تغییر که ساختار امروز می‌سازد
gofmt / gopls / go vet / staticcheck / golangci-lintقالب‌بند Go با قاعدهٔ بازنویسی، language server با code actionهای refactoring، و تحلیل‌گرهای ایستا
PHPStan / baseline / Rector / Laravel Pint / PhpStormتحلیل‌گر ایستای PHP با سطح و فایل baseline، قاعده‌های refactoring خودکار، اصلاح‌کنندهٔ سبک، IDE با refactoring

منابع ​

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