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 در ۲۰۱۸ | خانواده | به زبان ساده | اولین حرکت |
|---|---|---|---|---|---|
| 1 | Long Method | Long Function | Bloaters | یک تابع چند کار میکند | Extract Function |
| 2 | Large Class | Large Class | Bloaters | یک type بیش از حد میداند | Extract Class |
| 3 | Primitive Obsession | Primitive Obsession | Bloaters | پول در float64، وضعیت در string | Replace Primitive with Object |
| 4 | Long Parameter List | Long Parameter List | Bloaters | نُه آرگومان، نصفشان پرچم | Introduce Parameter Object |
| 5 | Data Clumps | Data Clumps | Bloaters | همان ۳ تا ۴ مقدار همیشه با هم میآیند | Extract Class |
| 6 | Switch Statements | Repeated Switches | OO Abusers | همان switch در چند جا | Replace Conditional with Polymorphism |
| 7 | Refused Bequest | Refused Bequest | OO Abusers | زیرنوعی که ارثش را نمیخواهد | Replace Superclass with Delegate |
| 8 | Divergent Change | Divergent Change | Change Preventers | یک ماژول به دلایل زیاد تغییر میکند | Split Phase، Extract Class |
| 9 | Shotgun Surgery | Shotgun Surgery | Change Preventers | یک تغییر به ماژولهای زیاد دست میزند | Move Function، Move Field |
| 10 | Duplicate Code | Duplicated Code | Dispensables | همان منطق دو بار | Extract Function، Pull Up Method |
| 11 | Comments | Comments | Dispensables | توضیحی برای کدی که باید خودش توضیح بدهد | Extract Function، Rename |
| 12 | Data Class | Data Class | Dispensables | فیلد و getter؛ رفتار جای دیگر | Move Function به داخلش |
| 13 | Speculative Generality | Speculative Generality | Dispensables | قلاب برای آیندهای که نیامد | Collapse Hierarchy، Inline، Remove Dead Code |
| 14 | Feature Envy | Feature Envy | Couplers | تابعی که به دادهٔ type دیگر علاقهٔ بیشتری دارد | Move Function |
حرکتهایی که ۹۰ درصد وقت به کار میبرید. نامها از کاتالوگ ویرایش دوم Fowler است؛ نامهای قدیمی روی همان کارت کاتالوگ بهعنوان alias آمدهاند.
| حرکت | نام قدیمی / alias | چه چیزی را درمان میکند | معکوس |
|---|---|---|---|
| Extract Function | Extract Method | تابع بلند، comment، کد تکراری | Inline Function |
| Extract Variable | Introduce Explaining Variable | عبارتهای ناخوانا | Inline Variable |
| Change Function Declaration | Rename Function، Add/Remove Parameter، Change Signature | نامهای مرموز، پارامترهای حدسی | خودش |
| Move Function / Move Field | Move Method | feature envy، shotgun surgery | خودش |
| Extract Class | large class، data clumps، divergent change | Inline Class | |
| Introduce Parameter Object | long parameter list، data clumps | ||
| Replace Primitive with Object | Replace Data Value with Object، Replace Type Code with Class | primitive obsession | |
| Replace Conditional with Polymorphism | repeated switches | ||
| Introduce Special Case | Introduce 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 پاک کردنش است؛ ضدالگو عادتی است که مدام چسبناکش میکند (روغن را لب پیشخوان گذاشتن). بازنویسی یعنی تعطیل کردن رستوران برای ساختن آشپزخانهٔ نو: گاهی لازم است، ولی هرگز جواب اول نیست.
سه بدفهمی رایج، از همین اول
- «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.
- «بو یعنی کد غلط است.» "smells don't always indicate a problem" (Fowler، CodeSmell). بو دلیلی برای نگاه کردن است. تابعی ۶۰ خطی که یک frame پروتکل را از بالا تا پایین parse میکند شاید روشنترین کدی باشد که میشود نوشت.
- «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".
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".
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 Change | rename آن تغییر قرارداد است، نه refactoring |
کاتالوگ بوها
این تصویر پنج جعبه دارد که دستهبندی 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 Code | Duplicated Code | Dispensables | بله (10) |
| Long Method | Long Function | Bloaters | بله (1) |
| Long Parameter List | Long Parameter List | Bloaters | بله (4) |
| (ندارد) | Global Data | تازه در ۲۰۱۸ | نه |
| (ندارد) | Mutable Data | تازه در ۲۰۱۸ | نه |
| Divergent Change | Divergent Change | Change Preventers | بله (8) |
| Shotgun Surgery | Shotgun Surgery | Change Preventers | بله (9) |
| Feature Envy | Feature Envy | Couplers | بله (14) |
| Data Clumps | Data Clumps | Bloaters | بله (5) |
| Primitive Obsession | Primitive Obsession | Bloaters | بله (3) |
| Switch Statements | Repeated Switches | OO Abusers | بله (6) |
| (ندارد) | Loops | تازه در ۲۰۱۸ | نه |
| Lazy Class | Lazy Element | Dispensables | نه |
| Speculative Generality | Speculative Generality | Dispensables | بله (13) |
| Temporary Field | Temporary Field | OO Abusers | نه |
| Message Chains | Message Chains | Couplers | نه |
| Middle Man | Middle Man | Couplers | نه |
| Inappropriate Intimacy | Insider Trading | Couplers | نه |
| Large Class | Large Class | Bloaters | بله (2) |
| Alternative Classes with Different Interfaces | همان | OO Abusers | نه |
| Data Class | Data Class | Dispensables | بله (12) |
| Refused Bequest | Refused Bequest | OO Abusers | بله (7) |
| Comments | Comments | Dispensables | بله (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.
// 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)// 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 است.
// 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.// 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" نام دارند.
// 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 }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 وقتی چند تابع پارامترهای یکسان دارند.
// 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)// 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."
type Address struct{ Street, City, Zip, Country string }
func (a Address) Domestic() bool { return a.Country == HomeCountry } // behaviour followed the datafinal 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") که در دو شرط یا بیشتر رفتار را تعیین میکند.
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)type ShippingMethod interface { Cost(net Money, to Address) Money; ETA() string }
var shippingMethods = map[string]ShippingMethod{"standard": standard{}, "express": express{}, "pickup": pickup{}}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 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) }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 است که از دریچهٔ تاریخچهٔ تغییرها دیده شده.
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// 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).// 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."
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)const freeShippingFrom = Money(5000) // one placeprivate 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 وقتی نسخهها در زیرکلاسهای همنیا هستند.
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// 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)// 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."
// 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// 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."
// 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.// 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."
// 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.// 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." سرانگشت برای تابعی که از چند ماژول استفاده میکند: آن را به ماژولی ببرید که بیشترِ داده را دارد.
// 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 }// 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 Case | cache تنبلی که مستند شده |
| Alternative Classes with Different Interfaces | دو type یک کار را با نامهای متد متفاوت انجام میدهند | SMTPMailer.Send در برابر SESMailer.Deliver | StripeGateway::charge در برابر MollieGateway::pay | Change Function Declaration، Move Function، Extract Superclass / interface | typeهای شخص ثالث که بههرحال با adapter میپوشانید |
| Parallel Inheritance Hierarchies | هر زیرکلاس تازه در یک سلسلهمراتب، یکی هم در دیگری میخواهد | XMLExporter و XMLValidator برای هر قالب (از راه interface) | جفتهای PdfInvoice و PdfInvoiceRenderer | Move Function، Move Field تا یکی از سلسلهمراتبها محو شود | جفتها عمداً در لایههای متفاوتاند (domain در برابر adapter) |
| Lazy Class (Lazy Element) | class یا تابعی که دیگر ارزش نگه داشتن ندارد؛ "such program elements need to die with dignity" | packageی با یک تابع سهخطی | class به نام Helper با یک متد static | Inline 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->limit | Hide 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 Delegate | Proxy، Decorator، Facade، لایههای ضدفساد (Anti-corruption layer) |
| Incomplete Library Class | کتابخانه متدی را که لازم دارید ندارد و نمیتوانید عوضش کنید | helper جاافتاده روی یک client شخص ثالث | متد جاافتاده روی یک class در vendor | Introduce 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های static | Encapsulate Variable، بعد تنگ کردن دامنه | ثابتها و config فقطخواندنیِ زمان شروع |
| Mutable Data (۲۰۱۸) | بهروزرسانی در یک جا کدی دیگر را غافلگیر میکند | برگرداندن slice داخلی که فراخوان میتواند به آن append کند | تغییر دادن آرایهٔ مشترک از راه reference | Encapsulate 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 / معکوس | سازوکار در یک خط | Go | Laravel / PHP | IDE |
|---|---|---|---|---|---|
| Extract Function | alias Extract Method؛ معکوس Inline Function | تکه را نامگذاری کن، آنچه میخواند را بده، آنچه مینویسد را برگردان | تابع یا متد unexported تازه | متد private، یا یک Action قابلفراخوانی | gopls refactor.extract.function / .method؛ PhpStorm Extract Method |
| Inline Function | alias Inline Method | فراخوانیها را با بدنه عوض کن، تابع را حذف کن | gopls refactor.inline.call | PhpStorm Inline | هر دو |
| Extract Variable | alias Introduce Explaining Variable؛ معکوس Inline Variable | یک زیرعبارت را نامگذاری کن | isStaff := t == Staff | $isStaff = ... | gopls refactor.extract.variable؛ PhpStorm Extract Variable |
| Change Function Declaration / Rename | Rename Function، Add/Remove Parameter، Change Signature | نام یا شکل را عوض کن، همهٔ فراخوانها را بهروز کن (اگر منتشرشده است، مرحلهبهمرحله) | gopls rename؛ removeUnusedParam در gopls | PhpStorm Rename، Change Signature | هر دو |
| Move Function / Move Field | alias Move Method | به مقصد کپی کن، از جای قدیم delegate کن، بعد delegate را inline کن | به packageی که مالک داده است | از controller به model/value object | PhpStorm Move |
| Replace Temp with Query | متغیر موقت را تابع کن تا extract پارامتر کمتری بخواهد | func (q Quote) net() Money | private function net(): Money | دستی | |
| Introduce Parameter Object | پارامترها را در یک type جمع کن و همان را بده | struct به نام PlaceOrder | class فقطخواندنی PlaceOrderData | دستی (Extract Class در PhpStorm کمک میکند) | |
| Replace Conditional with Polymorphism | یک type برای هر حالت؛ switch تبدیل به یک فراخوانی میشود | interface و typeها | classها، یا متدهای enum | دستی | |
| Replace Type Code with Subclasses | aliasها Extract Subclass، Replace Type Code with State/Strategy | اول کد را type کن | type نامدار و interface | enum پشتیباندار، و اگر رفتار بزرگ شد class | دستی |
| Decompose Conditional | شرط و هر شاخه را به تابعهای نامدار extract کن | acceptsCoupon() | acceptsCoupon() | Extract Method | |
| Extract Class | معکوس Inline Class | type تازه، اول فیلدها، بعد متدها، یکییکی | type یا package تازه | value object، model، Action | PhpStorm Extract Delegate |
| Pull Up Method / Push Down Method | معکوس هم | متد را به والد / به زیرکلاسهایی که استفادهاش میکنند ببر | در Go معنا ندارد (ارثبری نیست)؛ به یک helper جاسازیشده ببر یا از آن بیرون بیاور | PhpStorm Pull Members Up / Push Members Down | PhpStorm |
| Replace Superclass with Delegate | alias Replace Inheritance with Delegation | والد قبلی را بهصورت فیلد نگه دار و فقط آنچه لازم است را forward کن | فیلد به جای embedding | private Order $order به جای extends Order | دستی |
| Introduce Special Case | alias Introduce Null Object | یک شیء برای مقدار خاص با رفتار پیشفرض | pickup{} برای quoteهای ناشناخته | GuestCustomer با name() => 'occupant' | دستی |
| Separate Query from Modifier | یک تابع جواب میدهد، دیگری state را عوض میکند | Pricer.Price در برابر Catalog.Reserve | PriceQuote::calculate در برابر PlaceOrder::handle | دستی | |
| Encapsulate Collection | کپی یا نمای فقطخواندنی برگردان؛ افزودن و حذف از راه متد | All() کپی برمیگرداند | کپی Collection برگردان، هرگز آرایهٔ داخلی با reference | دستی | |
| Split Phase | بین دو مرحله یک ساختار داده بگذار | decode ← PlaceOrder ← Place | Form Request ← DTO ← Action ← Resource | دستی | |
| Hide Delegate / Remove Middle Man | معکوس هم | متد forward اضافه کن / وقتی زیاد شدند حذفشان کن | order.CustomerPlan() | $order->customerPlan() | دستی |
| Replace Magic Literal | alias Replace Magic Number with Symbolic Constant | مقدار ثابت را نامگذاری کن | const freeShippingFrom = Money(5000) | private const FREE_FROM_CENTS = 5000 | PhpStorm 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هایی را که کسی صدا نمیزند حذف کنید.
// 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 برگردانید. (۴) چکها را یکییکی حذف کنید.
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 disappearSeparate 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 بر اساس actor | Server با ۴۰ متد؛ model User با ۳۰۰۰ خط |
| Spaghetti Code (کد اسپاگتی) | AntiPatterns: "Control flow with no discernible structure." | Long Function، شرطهای تودرتو | Extract Function، guard clause، ماژولهایی با نام معنادار | متغیرهای پرچم شبیه goto؛ if هشتلایه در controller |
| Cut-and-Paste Programming | AntiPatterns: "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 Class | OrderManagerStarter که فقط 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 Surgery | Replace Magic Literal | 4.95، 0.30، 50 در کد قبل آزمایشگاه؛ linter به نام mnd |
| Cargo Cult Programming (برنامهنویسی آیینی) | Wikipedia (ثانویه): گنجاندن آیینی کد یا ساختاری که هیچ هدف واقعی ندارد | Speculative Generality، Middle Man | بپرسید هر لایه چه میکند؛ آنچه کاری نمیکند را حذف کنید | interface و service و DTO برای یک endpoint یکخطی CRUD «چون Clean Architecture» |
| Functional Decomposition | AntiPatterns: "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 پیاده شدهاند:
| بو | تعریف (بازنویسی، مگر نقلقول) | Go | Laravel / 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 خودش است:
-- 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 حیاتی
سمت چپ تصویر چرخهٔ 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 میکنید. داخل این حلقهٔ سمت راست رفتار هرگز عوض نمیشود؛ کار روی قابلیت، کلاه دیگر است.
تور ایمنی: تستهایی که میشود به آنها اعتماد کرد حیاتی
| تور | چیست | کی | Go | Laravel |
|---|---|---|---|---|
| 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/ با پرچم -update | package assertion از نوع snapshot یا fixture ذخیرهشده |
| Type checker و تحلیل ایستا | ارجاعهای شکسته را هنگام جابهجایی میگیرد | هر گام | کامپایلر، go vet، staticcheck | PHPStan در بالاترین سطحی که نگه میدارید |
| Mutation testing | کد را عوض میکند و چک میکند که تستی شکست بخورد | به قدرت تستها شک دارید | ابزارهای mutation شخص ثالث | Infection |
تست توصیفی روی کد قدیمی نوشته میشود، باید روی آن پاس شود و باید در هر گام پاس بماند. اگر شکست خورد، یا گامتان رفتار را عوض کرده (revert کنید) یا رفتاری پیدا کردهاید که میخواهید عوضش کنید (بایستید، refactoring را تمام کنید، بعد در commit جداگانه با تست تازه عوضش کنید).
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 دیتابیس) از آن استفاده کنید.
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 releaseBranch 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های gopls | refactor.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 rename | rename آگاه از type در کل module، از جمله rename یک package | gopls rename -w before/handler.go:#1450 placeOrder |
go vet | ساختارهای مشکوک | در هر گام آزمایشگاه اجرا میشود |
| staticcheck | سادهسازی (S1xxx)، سبک (ST1xxx، مثلاً ST1003 شناسهٔ بدنام، ST1013 کدهای HTTP جادویی)، کد مرده مثل SA4006 مقداری که هرگز خوانده نمیشود | staticcheck ./... |
| golangci-lint | linterهای زیادی را اجرا میکند؛ بوگیرها در جدول بعد | golangci-lint run |
| linter در golangci-lint | بویی که علامت میزند |
|---|---|
funlen (پیشفرض ۶۰ خط، ۴۰ دستور) | Long Function |
gocognit، gocyclo، cyclop، nestif، maintidx | Long Function، شرطهای پیچیده |
dupl (پیشفرض ۱۵۰ token) | Duplicated Code |
goconst، mnd | عددهای جادویی و stringهای تکراری |
unused، unparam | Dead Code، Speculative Generality |
gochecknoglobals | Global Data |
interfacebloat | Large Class در سطح interface |
depguard | قاعدههای معماری: منع import بین لایهها |
# .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: 100PHP و 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-run | withPreparedSets(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 به فاصلهگذاری آلوده نشود |
| PhpStorm | refactoringهای تعاملی با preview و پنجرهٔ تعارض | Rename، Change Signature، Extract Method / Variable / Constant / Class / Interface / Superclass، Extract Delegate، Encapsulate Fields، Inline، Move، Pull Members Up / Push Members Down |
| سطح PHPStan | چه اضافه میکند (انباشتی) |
|---|---|
| 0 | classها، تابعها و متدهای ناشناخته روی $this، تعداد آرگومان غلط، متغیرهایی که همیشه تعریفنشدهاند |
| 1–3 | متغیرهای احتمالاً تعریفنشده، عضوهای magic، اعتبارسنجی PHPDoc، typeهای بازگشتی، type propertyها |
| 4 | کد مردهٔ پایه: instanceof همیشه false، شاخههای else مرده، کد بعد از return |
| 5–6 | type آرگومانها؛ typehintهای جاافتاده |
| 7–8 | union typeهای تا حدی غلط؛ دسترسی روی nullable |
| 9–10 | mixed سختگیرانه؛ سطح 10 (PHPStan 2.0) mixed ضمنی را هم میگیرد |
<?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 یا Go | Form Request / decode ← DTO ← Action / Service ← Resource / encode | هر مرحله جدا تست میشود | فایل بیشتر |
| پول بهصورت float | Replace Primitive with Object | Money بر حسب سنت، تبدیل در لبه | حساب دقیق، یک قالببندی | مراقبت از قالب سیم و علامت منفی (quote منفی آزمایشگاه) |
| همان switch در شش فایل | Replace Conditional with Polymorphism | interface یا enum با متد؛ یک factory | حالت تازه = یک type تازه | برای switch دوحالته ارزش ندارد |
| endpoint کپیشده | Extract Function بعد از قاعدهٔ سه؛ Separate Query from Modifier | یک تابع قیمتگذاری که هر دو استفاده میکنند | یک اصلاح، هر دو را درست میکند | واگراییها رو میشوند و تصمیم محصول لازم دارند |
| map سراسری / singleton | Encapsulate Variable، بعد تزریق | type مالک داده است؛ تزریق از constructor | تستها state تازه میسازند | کد سیمکشی در main / providerها |
| model خدا | Extract Class بر اساس actor | value object، model مرتبط، Action، Policy | merge 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 در شش فایل
# 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، بعد refactor | golden master | بدون تور، refactoring نیست |
| مشکل ساختاری بزرگ (کتابخانهٔ غلط، God Component) | planned / long-term refactoring | Branch 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 و معماری به هم میرسند. اول حرکتهای ارزان را انجام دهید، داخل همان پروسه، جایی که برگشتپذیرند:
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× (یک تیم، یک اپ) | Monolith | refactoring فرصتطلبانه، linter در CI، characterization test برای بخشهای legacy |
| 10× (چند تیم، یک repo) | Modular monolith | facade ماژولها، قاعدهٔ import (depguard، deptrac)، بازبینی گراف وابستگی هر فصل برای چرخهها و هابها |
| 100× (تیمها و سرویسهای زیاد) | سرویس بر اساس قابلیت کسبوکار | داخل سرویس آزادانه refactor کنید؛ قرارداد را با نسخهگذاری و expand/contract عوض کنید؛ برای بیرون کشیدن، Strangler Fig |
آزمایشگاه: refactor یک handler بدبو در Go و یک controller بدبو در Laravel
از کدی شروع میکنید که کار میکند و همهٔ بوهای این صفحه را دارد، یک characterization test برایش مینویسید و در گامهای کوچک refactor میکنید تا به شکل کد «بعد» برسد، با تستی که بعد از هر گام سبز است.
سمت چپ تصویر نقطهٔ شروع است: دو handler (HandleOrder و HandleQuote) که mapهای سراسری را شریکاند و یکی کپی دیگری است، با پولِ float64 و دو نسخه از هر switch. سمت راست وضعیت پایانی است: یک adapter نازک HTTP، یک Service، یک Catalog که مالک موجودی است، یک Pricer که تنها نسخهٔ قاعدههای قیمتگذاری است، و پیادهسازیهای ShippingMethod (standard، express، pickup) به جای دو switch. پیکانها به وابستگی اشاره میکنند؛ برگها (Money، Address، CustomerType) کمتر از همه تغییر میکنند.
بخش الف: Go
آمادهسازی.
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 را پیدا کنید.
// 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/ پاس میشود.
// 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)
}
}
}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 درستش کرد. سبز.
وضعیت پایانی، فایلبهفایل:
// 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 }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 }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
}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
}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
}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
}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)
}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} }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)
}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، حدود ۲۵ خط |
| نسخههای قاعدهٔ قیمتگذاری | 2 | 1 (Pricer.Price) |
| switch روی string ارسال | 3 (دو تا در HandleOrder، یکی در HandleQuote) | 0 (یک lookup در map) |
| متغیرهای تغییرپذیر سطح package | 4 | 0 (shippingMethods و discountPercent جدولهای فقطخواندنیاند) |
| فایلهایی که «ارسال رایگان از ۶۰» لمس میکند | 1 فایل، 2 جا | 1 ثابت |
| فایلهایی که «افزودن ارسال پیک» لمس میکند | 3 switch | 1 type تازه + 1 ورودی map |
| Characterization test | PASS | PASS (همان ۱۴ حالت، بایتدقیق) |
گام ۱۰ (اختیاری): 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 |
| ابزارهای Go | gofmt -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 Class | typeی با فیلدها و مسئولیتهای بیش از حد |
| Primitive Obsession (وسواس primitive) | مفهومهای دامنه در primitiveها ("stringly typed") |
| Long Parameter List | پارامترهای بیش از حد، اغلب پرچم |
| Data Clumps (دستههای داده) | مقدارهایی که همیشه با هم میآیند و میخواهند type شوند |
| Switch Statements / Repeated Switches | همان شرط روی یک کد نوع در چند جا |
| Temporary Field | فیلدی که فقط در بعضی شرایط مقدار میگیرد |
| Refused Bequest (میراث ردشده) | زیرنوعی که ارثش را نمیخواهد |
| Alternative Classes with Different Interfaces | typeهایی که یک کار را با نامهای متد متفاوت میکنند |
| Divergent Change (تغییر واگرا) | یک ماژول که به دلایل بیربط زیاد تغییر میکند |
| Shotgun Surgery (جراحی ساچمهای) | یک تغییر که ویرایشهای کوچک زیادی در ماژولها میخواهد |
| Parallel Inheritance Hierarchies | افزودن زیرکلاس در یک سلسلهمراتب، یکی در دیگری را هم لازم میکند |
| Comments (بو) | commentی که خوشبوکنندهٔ کد نامفهوم است |
| Duplicate Code / Duplicated Code | همان منطق در بیش از یک جا |
| Lazy Class / Lazy Element | class یا تابعی که دیگر ارزش نگه داشتن ندارد |
| Data Class | فقط فیلد و accessor؛ رفتار جای دیگر |
| Dead Code (کد مرده) | کدی که هرگز اجرا نمیشود |
| Speculative Generality (عمومیت حدسی) | انتزاع برای نیازهایی که هرگز نیامدند |
| Feature Envy (حسادت قابلیت) | تابعی که به دادهٔ ماژول دیگر بیشتر از دادهٔ خودش علاقه دارد |
| Inappropriate Intimacy / Insider Trading | ماژولهایی که از جزئیات داخلی هم زیادی خبر دارند |
| Message Chains | پیمودن زنجیرهای از شیءها که client را به ساختار وابسته میکند |
| Middle Man | typeی که بیشتر فقط delegate میکند |
| Incomplete Library Class | type کتابخانهای که متد لازم را ندارد |
| Mysterious Name / Global Data / Mutable Data / Loops | چهار بویی که در ویرایش ۲۰۱۸ Fowler اضافه شدند |
| Extract Function / Inline Function | نامگذاری یک تکه بهصورت تابع / برگرداندن بدنهٔ تابع به جای فراخوانیها |
| Extract Variable | نامگذاری یک زیرعبارت |
| Change Function Declaration | rename یک تابع یا تغییر پارامترهایش |
| 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 Conditional | extract کردن شرط و شاخهها به تابعهای نامدار |
| Extract Class / Inline Class | شکستن یک type به دو / ادغام دوباره |
| Pull Up Method / Push Down Method | بردن متد به والد / به زیرکلاسها |
| Replace Superclass with Delegate | جایگزینی ارثبری با فیلد و forward (alias Replace Inheritance with Delegation) |
| Introduce Special Case | typeی برای مقدار خاص با رفتار پیشفرض (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 |
منابع
- Martin Fowler، refactoring.com (تعریف و "Refactoring is a part of day-to-day programming") و کاتالوگ آنلاین refactoringها، از جمله کارتهای Extract Function، Replace Conditional with Polymorphism، Introduce Special Case، Separate Query from Modifier، Replace Superclass with Delegate، Replace Type Code with Subclasses، Encapsulate Collection، Introduce Parameter Object، Move Function، Extract Class، Decompose Conditional، Replace Temp with Query، Pull Up Method
- Martin Fowler و Kent Beck، «Bad Smells in Code»، فصل ۳ کتاب Refactoring، ویرایش دوم (Addison-Wesley، ۲۰۱۸)، گزیدهٔ InformIT
- Martin Fowler، bliki: CodeSmell، DefinitionOfRefactoring، RefactoringMalapropism، OpportunisticRefactoring، TestDrivenDevelopment، ParallelChange (Danilo Sato)، BranchByAbstraction
- Martin Fowler، Workflows of Refactoring (infodeck، ۲۰۱۴)؛ An example of preparatory refactoring؛ Strangler Fig
- refactoring.guru: Code Smells (پنج خانواده و صفحهٔ هر بو، مثلاً Long Method، Feature Envy)، When to refactor (خلاصهٔ ثانویه از Fowler)
- W. Brown، R. Malveau، H. McCormick، T. Mowbray، AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis (Wiley، ۱۹۹۸)، سایت نویسندگان: catalog، development catalog، Lava Flow
- Joshua Kerievsky، Refactoring to Patterns (Addison-Wesley، ۲۰۰۴)، صفحهٔ کتاب در Industrial Logic
- D. Sas، P. Avgeriou، U. Uyumaz، "On the evolution and impact of Architectural Smells: an industrial case study"، ۲۰۲۲، arXiv:2203.08702 (گزارش تعریفهای Arcan از Arcelli Fontana و همکاران)
- Chris Richardson، Shared database pattern، microservices.io
- Wikipedia (ثانویه): Code refactoring (Opdyke، Griswold)، Anti-pattern (Koenig ۱۹۹۵)، Rule of three، Characterization test، Magic number، Cargo cult programming
- Go: gofmt، قابلیتهای تبدیل کد در gopls، checkهای staticcheck، linterهای golangci-lint و تنظیمات linterها
- PHP: سطحهای PHPStan، مستندات Rector و set listها، PhpStorm: code refactoring
- Laravel 13: Pint، HTTP tests، Validation: Form Requests، Errors: renderable exceptions، Events: ShouldQueueAfterCommit، Queries: pessimistic locking