Design Quality: Complexity, Coupling & Cohesion, Information Hiding, Separation of Concerns, Conceptual Integrity
"Every module in the second decomposition is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings." — D. L. Parnas، On the Criteria To Be Used in Decomposing Systems into Modules، Communications of the ACM 15(12)، ۱۹۷۲
خلاصه (Summary): طراحی خوب یعنی پایین نگه داشتن پیچیدگی: وابستگیهای کم و ضعیف بین ماژولها (coupling پایین)، رابطهٔ قوی بین اجزای داخل هر ماژول (cohesion بالا)، پنهان کردن هر تصمیمی که احتمال تغییرش هست پشت یک interface کوچک، جای جدا برای هر دغدغه، و یک مجموعه ایدهٔ یکدست در کل سیستم. تمرکز (Focus): پیچیدگی ذاتی در برابر عارضی، سه نشانهٔ Ousterhout، نردبان کامل coupling و cohesion، پنهانسازی اطلاعات در برابر کپسولهسازی، interface بهعنوان قرارداد، ماژول عمیق و کمعمق، جداسازی دغدغهها و دغدغههای همهجاگیر، یکپارچگی مفهومی، connascence، معیارها و ابزارها، و اینکه همین قواعد بین میکروسرویسها چطور اجرا میشوند. هدف یادگیری (Learning goal): نوع coupling و cohesion هر تکه کد را نام ببرید، اندازهاش بگیرید، و آن را در Go و Laravel یک پله به سمت «data coupling، functional cohesion، ماژول عمیق» ببرید؛ هم داخل یک monolith و هم بین سرویسها.
این صفحه فصل واژگان بخش طراحی است و فصلهای بعدی همه از واژههای آن استفاده میکنند: SRP یعنی «cohesion حول یک actor»، ISP یعنی «interfaceهای باریک»، DIP یعنی «وابستگی را به سمت انتزاعهای پایدار ببر»، قانون Demeter یعنی «از داخل اشیای دیگر عبور نکن»، و بیشتر بوهای Code Smells & Refactoring نشانههای اسمدار coupling بالا یا cohesion پاییناند. اینجا خود معیارها را تعریف میکنیم: از کجا آمدهاند، چطور اندازهشان بگیریم و چطور درستشان کنیم. پلهٔ رفتن از class به سرویس در در معماری کشیده شده و در Service Boundaries و Modular Monolith ادامه پیدا میکند.
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| همهٔ اصلها در یک صفحه | همهچیز در یک دقیقه |
| چرا اینها پول خرج میکنند یا صرفهجویی | چرا کیفیت طراحی مهم است |
| Parnas، Constantine، Brooks، Dijkstra، McCabe، Ousterhout، Page-Jones | از کجا آمده |
| پیچیدگی و نشانههایش | پیچیدگی، ذاتی در برابر عارضی |
| نردبان coupling، temporal coupling، Ca/Ce/instability | Coupling، Temporal coupling، Afferent، efferent، instability |
| نردبان cohesion | Cohesion |
| پنهانسازی اطلاعات، کپسولهسازی، interface، ماژول عمیق | پنهانسازی اطلاعات، Interface بهعنوان قرارداد، عمیق و کمعمق |
| جداسازی دغدغهها و دغدغههای همهجاگیر | جداسازی دغدغهها |
| یکپارچگی مفهومی و اینکه تیمها چطور از دستش میدهند | یکپارچگی مفهومی |
| Connascence: name، type، meaning، position، algorithm، execution، timing، value، identity | Connascence |
| cyclomatic complexity، LCOM، fan-in/out، gocyclo، go-arch-lint، phpmetrics، deptrac | سازوکار |
| کد قبل و بعد | Go، Laravel |
| متغیر سراسری، flag، wrapper کمعمق، جدول مشترک، فراخوانی پرحرف | حل مسئلههای کلاسیک |
| DB مشترک، API پرحرف، temporal coupling بین سرویسها | در معماری |
| اندازهگیری عملی | آزمایشگاه |
همهچیز در یک دقیقه
اصلها. هر سطر در فهرست مفاهیم باز میشود.
| اصل | به زبان ساده | نشانه وقتی نیست | اولین درمان |
|---|---|---|---|
| پیچیدگی پایین (Low complexity) | سیستم راحت فهمیده و عوض میشود | قابلیت یکخطی یک هفته طول میکشد | وابستگی و ابهام را کم کنید |
| وابستگی پایین (Low coupling) | تغییر A به ندرت B را مجبور به تغییر میکند | «فقط X را عوض کردم و Y شکست» | داده بدهید، نه flag یا متغیر سراسری |
| انسجام بالا (High cohesion) | هر چه در ماژول است به هم تعلق دارد | utils، helpers، classهای Manager | کد را کنار تنها مصرفکنندهاش ببرید |
| پنهانسازی اطلاعات (Information hiding) | هر ماژول یک تصمیم تغییرپذیر را پنهان میکند | صدازنندهها نام جدول، قفل و سیاست retry شما را میدانند | interface را کوچک کنید |
| ماژول عمیق (Deep modules) | interface کوچک، کارکرد پنهان زیاد | wrapper عبوری، classitis | تکههای کمعمق را ادغام کنید، پیچیدگی را پایین بکشید |
| جداسازی دغدغهها (Separation of concerns) | هر دغدغه جای خودش را دارد | auth، لاگ و قاعده در یک تابع | middleware، لایه، event |
| یکپارچگی مفهومی (Conceptual integrity) | کل سیستم یک مجموعه ایده را بازتاب میدهد | سه روش صفحهبندی، دو قالب خطا | نقش معمار، ADR، راهنمای سبک |
| Connascence ضعیف | آنچه باید با هم تغییر کند اسم دارد و نزدیک است | عدد جادویی، آرگومان ترتیبی بین ماژولها | type اسمدار، constructor، محلی نگه داشتن |
نردبان coupling (از تنگترین). بلوک کامل: Coupling.
| سطح | چه چیزی مشترک است | مثال کوچک |
|---|---|---|
| Content (pathological) | درونیات: کد یا دادهٔ خصوصی ماژول دیگر | reflection روی فیلد خصوصی؛ SQL روی جدول ماژول دیگر |
| Common | دادهٔ سراسری تغییرپذیر | var DB *sql.DB، خواندن config() در عمق منطق |
| External | قالب، پروتکل یا دستگاهی که از بیرون تحمیل شده | دو ماژول یک قالب CSV را parse میکنند |
| Control | flagی که شاخهٔ اجرای طرف مقابل را انتخاب میکند | Render(o, true, false) |
| Stamp | کل یک ساختار، با استفادهٔ جزئی | پاس دادن model Eloquent برای خواندن id |
| Data | فقط مقادیر پایهای لازم | Total(lines, "EUR") |
نردبان cohesion (از ضعیفترین). بلوک کامل: Cohesion.
| سطح | چرا اجزا کنار هماند | مثال کوچک |
|---|---|---|
| Coincidental | بیدلیل | helpers.php |
| Logical | یک دسته، انتخاب با flag | Exporter::export($type) |
| Temporal | در یک لحظه اجرا میشوند | boot() که پنج کار بیربط میکند |
| Procedural | گامهای یک رویه روی دادهٔ متفاوت | «اول مجوز را چک کن، بعد فایل را باز کن» |
| Communicational | روی یک داده کار میکنند | همهٔ متدها یک Order را میخوانند |
| Sequential | خروجی یکی ورودی بعدی است | parse → validate → normalise |
| Functional | همهٔ اجزا یک کار مشخص را انجام میدهند | CurrencyConverter::convert |
آنچه میشود اندازه گرفت. بلوک کامل: سازوکار.
| معیار | چه میسنجد | ابزار Go | ابزار PHP |
|---|---|---|---|
| Cyclomatic complexity | مسیرهای مستقل در یک تابع | gocyclo، golangci-lint (لینتر gocyclo) | phpmetrics (ccn) |
| LCOM | متدهایی که هیچ فیلد مشترکی ندارند | ابزار داخلی ندارد | phpmetrics (lcom) |
| Fan-in / fan-out | چه کسی از من استفاده میکند / من از چه کسی | go list -deps، گراف import | phpmetrics (afferent/efferent) |
| Ca، Ce، Instability I = Ce / (Ca + Ce) | پایداری package | اسکریپت گراف import | phpmetrics (instability) |
| وابستگی ممنوع | قواعد معماری | go-arch-lint | deptrac، Pest arch() |
| Change coupling | فایلهایی که با هم تغییر میکنند | تحلیل git log | تحلیل git log |
چرا کیفیت طراحی مهم است
هر برنامهای پیش از تغییر باید فهمیده شود. هزینهٔ یک تغییر بیشترش هزینهٔ فهمیدن این است که چه چیز دیگری هم باید عوض شود و اطمینان از اینکه چیز دیگری نمیشکند. کیفیت طراحی همان ویژگیهایی است که این هزینه را با بزرگ شدن سیستم پایین نگه میدارد. Stevens و Myers و Constantine در ۱۹۷۴ این را در یک جمله گفتند: "Simplicity is the primary measurement recommended for evaluating alternative designs relative to reduced debugging and modification time." یادداشتهای درسی Ousterhout همین را با زبان امروز میگوید: پیچیدگی "anything related to the structure of a system that makes it hard to work on the development of that system" است.
| بهینه برای «امروز کار کند» | بهینه برای «راحت عوض شود» |
|---|---|
| اولین commit سریعتر | اولین commit کمی کندتر |
| هر چه دستت میرسد صدا بزن | فقط interfaceهای منتشرشده را صدا بزن |
| متغیر سراسری و flag راحتاند | وابستگیها صریح پاس داده میشوند |
| هر قابلیت سبک خودش را میآورد | یک سبک، مکتوب |
| هزینه با هر تغییر بالا میرود | هزینه آهسته بالا میرود |
| خطر: گلولهٔ بزرگ گِل | خطر: مهندسی بیش از حد، لایههای زیادی |
Design Stamina Hypothesis در bliki فاولر این معامله را اینطور قاب میگیرد: تا یک نقطهای، نادیده گرفتن طراحی سریعتر است؛ بعد از آن، نبودِ طراحی هر قابلیت را کندتر میکند. این نقطه زودتر از انتظار بیشتر تیمها میرسد.
تشبیهی که در این صفحه بارها برمیگردیم: سیمکشی برق یک ساختمان. سیمها داخل دیوارند (پنهانسازی اطلاعات)؛ شما از پریز استاندارد استفاده میکنید، نه از مس (interface بهعنوان قرارداد)؛ یک پریز پشت صورت کوچکش چیزهای زیادی را پنهان کرده (ماژول عمیق)؛ هر اتاق مدار خودش را دارد تا کتری برق اتاق سرور را قطع نکند (coupling پایین، جداسازی دغدغهها)؛ هر مدار وسایل مرتبط را تغذیه میکند (cohesion)؛ نقشهٔ یک برقکار با یک کد رنگ کل ساختمان را پوشش میدهد (یکپارچگی مفهومی). اگر سیمی را از آپارتمان همسایه به داخل آپارتمان خودتان پیوند بزنید، content coupling ساختهاید.
سه بدفهمی رایج، از همین اول
- «coupling پایین یعنی هیچ وابستگی.» فاولر در Reducing Coupling (IEEE Software، ۲۰۰۱): "if you ban coupling between modules, you have to put everything in one big module." هدف وابستگیِ ضعیف، کم و یکطرفه است، نه صفر.
- «class کوچک یعنی طراحی خوب.» Ousterhout حالت افراطیاش را «classitis» مینامد: classهای کمعمق فراوان که هر کدام ذرهای کارکرد را پشت interface خودش اضافه میکند. عمق مهمتر از اندازه است.
- «کپسولهسازی (Encapsulation) و پنهانسازی اطلاعات (Information hiding) یکیاند.»
privateکردن فیلدها سازوکار زبان است. پنهانسازی اطلاعات تصمیم طراحی دربارهٔ این است که چه چیزی پنهان شود. فیلدهای خصوصی با getter و setter عمومی برای تکتکشان هیچ چیز را پنهان نمیکنند.
از کجا آمده
Dijkstra، ۱۹۷۴: جداسازی دغدغهها. Dijkstra در EWD447 با عنوان On the role of scientific thought از مطالعهٔ "an aspect of one's subject matter in isolation for the sake of its own consistency" حرف میزند و اسمش را میگذارد:
"It is what I sometimes have called "the separation of concerns", which, even if not perfectly possible, is yet the only available technique for effective ordering of one's thoughts, that I know of." — E. W. Dijkstra، On the role of scientific thought (EWD447)، ۱۹۷۴
Parnas، ۱۹۷۲: پنهانسازی اطلاعات. Parnas دو روش شکستن یک برنامهٔ واحد (KWIC index) را مقایسه کرد. روش مرسوم از flowchart پیروی میکرد؛ روش او از تصمیمهایی که ممکن بود عوض شوند. نتیجهاش:
"We propose instead that one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then designed to hide such a decision from the others." — D. L. Parnas، ۱۹۷۲
Stevens، Myers و Constantine، ۱۹۷۴: coupling و cohesion. مقالهٔ Structured Design (IBM Systems Journal 13(2)) وابستگی (Coupling) را "the measure of the strength of association established by a connection from one module to another" تعریف کرد و گفت "Coupling is lower with data connections than with control connections, which are in turn lower than hybrid connections (modification of one module's code by another module)." به انسجام (Cohesion) گفت binding و آن را در شش سطح ردهبندی کرد: "1. Coincidental. 2. Logical. 3. Temporal. 4. Communicational. 5. Sequential. 6. Functional." و افزود "The scale is not linear." Larry Constantine این ایدهها را از اواخر دههٔ ۱۹۶۰ پرورانده بود و کتاب Yourdon و Constantine (۱۹۷۵/۱۹۷۹) آنها را استاندارد کرد (منبع ثانویه: Wikipedia، Coupling (computer programming)). فهرست ششسطحی coupling که امروز استفاده میشود (content، common، external، control، stamp، data) صورت درسی بعدی از Myers و Page-Jones است؛ کتاب Practical Guide to Structured Systems Design از Page-Jones (۱۹۸۰/۱۹۸۸) به content coupling میگوید «pathological» (این را در اسلایدهای ACCU ۲۰۱۰ از Tony Barrett-Powell خواندیم که به کتاب ارجاع میدهد، نه در خود کتاب). cohesion نوع procedural در متنهای بعدی آمده و سطحها را هفت تا میکند.
Brooks، ۱۹۷۵: یکپارچگی مفهومی. فصل ۴ کتاب The Mythical Man-Month با عنوان «Aristocracy, Democracy, and System Design»:
"I will contend that conceptual integrity is the most important consideration in system design. It is better to have a system omit certain anomalous features and improvements, but to reflect one set of design ideas, than to have one that contains many good but independent and uncoordinated ideas." — F. P. Brooks، The Mythical Man-Month، فصل ۴
McCabe، ۱۹۷۶: پیچیدگی cyclomatic. مقالهٔ A Complexity Measure (IEEE TSE، دسامبر ۱۹۷۶) عدد cyclomatic گراف جریان کنترل، یعنی v = e - n + 2p، را معیار یک ماژول گرفت و یک قاعدهٔ عملی گزارش کرد: "The particular upper bound that has been used for cyclomatic complexity is 10 which seems like a reasonable, but not magical, upper limit."
Brooks، ۱۹۸۶: ذات و عارضه. مقالهٔ No Silver Bullet دشواریها را "into essence—the difficulties inherent in the nature of the software—and accidents—those difficulties that today attend its production but that are not inherent" تقسیم میکند و استدلال میکند که پیچیدگی نرمافزار ویژگی ذاتی آن است، نه عارضی.
مارتین، ۲۰۰۰: معیارهای package. مقالهٔ Design Principles and Design Patterns وابستگی ورودی Ca، وابستگی خروجی Ce و ناپایداری I = Ce / (Ca + Ce) را تعریف میکند، با این قاعده: "Depend upon packages whose I metric is lower than yours."
Page-Jones، دههٔ ۱۹۹۰: connascence. Meilir Page-Jones مفهوم connascence را بهعنوان واژگانی دقیقتر برای coupling معرفی کرد؛ تعریفهایی که ما استفاده میکنیم از connascence.io است که آن را "a software quality metric & a taxonomy for different types of coupling" مینامد و بر سه محور قدرت، درجه و محلی بودن میسنجد.
فاولر، ۲۰۰۱. Reducing Coupling: "If changing one module in a program requires changing another module, then coupling exists" و "Duplication always implies coupling."
Ousterhout، ۲۰۱۸. کتاب A Philosophy of Software Design و یادداشتهای درس CS 190 در Stanford واژگان کاری امروز را میدهند: پیچیدگی سه نشانه دارد (change amplification، cognitive load، unknown unknowns) و دو علت (وابستگی و ابهام)، و "Classes Should be Deep". یادداشتها پنهانسازی اطلاعات را "the single most important idea in software design" مینامند.
فهرست مفاهیم
هر بلوک: به زبان ساده، باور غلط رایج، تعریف دقیق، timeline تغییر، سناریوهای واقعی، و درمان.
پیچیدگی (Complexity) حیاتی
به زبان ساده: پیچیدگی هر چیزی است که فهمیدن و تغییر کد را برای کسی که همین حالا رویش کار میکند سخت میکند.
بدفهمی رایج: «پیچیدگی یعنی سیستم بزرگ.» یادداشتهای Ousterhout: "Doesn't necessarily correlate with system size or number of features." یک کدبیس کوچک پر از وابستگی پنهان از یک کدبیس بزرگ و خوبشکسته پیچیدهتر است.
تعریف: سه نشانهٔ Ousterhout، عیناً از یادداشتهای CS 190:
| نشانه | عبارت Ousterhout | آنچه میبینید |
|---|---|---|
| تقویت تغییر (Change amplification) | "a simple change requires many code modifications" | عوض کردن قالب ارز ۱۴ فایل را ویرایش میکند |
| بار شناختی (Cognitive load) | "have to load a lot of information in your mind in order to make a change" | برای افزودن یک endpoint باید ترتیب قفلها، قالب کلید cache و سیاست retry را بدانید |
| ناشناختههای ناشناخته (Unknown unknowns) | "there's important information you need to know before making a change, but not obvious where to find it, or even that it is needed" | گزارشی میشکند چون مستقیم جدول شما را میخواند؛ هیچ جای کدتان به آن اشاره نکرده بود |
و دو علت: وابستگی (Dependencies: "If one changes, the other must change also") و ابهام (Obscurity: "not clear how things work or why the code is the way it is"). "Complexity is incremental": هیچ commit تنهایی این کار را نمیکند؛ هزاران وابستگی کوچک میکنند.
Week Change request Files touched Symptom
1 W1 add "GBP" currency 1 none
2 W8 add "GBP" currency (after 30 copies 14 change amplification
of formatMoney() were pasted around)
3 W9 reviewer must know cache keys embed - cognitive load
the currency and the invoice PDF caches by them
4 W10 finance report breaks: it parsed the - unknown unknown
old money string in SQL; nobody knewسناریوی واقعی: قاعدهٔ قیمتگذاری که در API، پنل ادمین و job شبانه تکرار شده؛ سرویس Go که هر handlerش باید یادش باشد tx.Rollback() را به همان ترتیب صدا بزند؛ اپ Laravel که معنای status = 3 را فقط نویسندهٔ اولش میداند.
درمان: وابستگیها را کم کنید (اتصال کمتر و ضعیفتر: بلوک coupling) و ابهام را کم کنید (نام، type و توضیحی که حدس اول را درست کند: بلوک connascence).
پیچیدگی ذاتی در برابر عارضی (Essential vs accidental complexity) مهم
به زبان ساده: پیچیدگی ذاتی (essential complexity) در خود مسئله است (قانون مالیات پیچیده است)؛ پیچیدگی عارضی (accidental complexity) چیزی است که خودمان هنگام حل اضافه کردهایم (سه لایه cache که هیچکس لازمش ندارد).
بدفهمی رایج: «طراحی خوب پیچیدگی را حذف میکند.» طراحی خوب پیچیدگی عارضی را حذف میکند و نوع ذاتی را پشت یک interface کوچک مهار میکند. Brooks: توصیفهایی "that abstract away its complexity often abstract away its essence."
تعریف: Brooks (۱۹۸۶) کار نرمافزار را به "essential tasks, the fashioning of the complex conceptual structures that compose the abstract software entity, and accidental tasks, the representation of these abstract entities in programming languages" تقسیم میکند. کار کیفیت طراحی سهم عارضی را هدف میگیرد و سهم ذاتی را در یک ماژول عمیق مینشاند.
| مثال | ذاتی | عارضی |
|---|---|---|
| VAT در ۲۷ کشور اتحادیهٔ اروپا | نرخها، reverse charge، آستانهها | قاعدهای که در ۴ سرویس کپی شده |
| نرخ ارز | نرخها عوض میشوند؛ ارائهدهندهها از کار میافتند | هر صدازننده خودش cache و retry را مدیریت میکند |
| ماشین حالت سفارش | انتقالهای مجاز | کد وضعیت به شکل عدد جادویی |
| checkout توزیعشده | شکست جزئی واقعی است | زنجیرهٔ همگام ۶ سرویس که همه باید بالا باشند |
درمان: پیچیدگی ذاتی را پایین و در یک ماژول بنشانید («pull complexity down» در عبارت Ousterhout) و پیچیدگی عارضی اطرافش را پاک کنید.
وابستگی (Coupling) حیاتی
به زبان ساده: coupling یعنی تغییر یک ماژول چقدر ماژول دیگر را مجبور به تغییر، تست دوباره یا دانستن چیزی اضافه میکند.
بدفهمی رایج: «اگر بینشان interface باشد، از هم جدا شدهاند.» interfaceی که متدهایش flag mode int میگیرند، کل ردیف دیتابیس را برمیگردانند یا فراخوانی با ترتیب ثابت لازم دارند هنوز بهشدت وابسته است. coupling دربارهٔ چیزی است که از مرز عبور میکند، نه استفاده از یک کلیدواژه.
تعریف: Stevens و همکاران: "the measure of the strength of association established by a connection from one module to another." و به این بستگی دارد: "(1) on how complicated the connection is, (2) on whether the connection refers to the module itself or something inside it, and (3) on what is being sent or received."
تصویر شش سطح کلاسیک را نشان میدهد، تنگترین در چپ (content که Page-Jones آن را pathological مینامد) و شلترین در راست (data)؛ زیرش دو شکلی آمده که در گراف فراخوانی دیده نمیشوند: temporal coupling (وابستگی به ترتیب یا همزمانی) و change coupling (فایلهایی که بدون هیچ import در تاریخچهٔ git با هم عوض میشوند).
| سطح | تعریف | مثال Go | مثال Laravel | درمان |
|---|---|---|---|---|
| Content (pathological) | یک ماژول درونیات دیگری را استفاده یا تغییر میدهد | unsafe/reflect برای مقداردهی فیلد خصوصی؛ کپی کردن internal تیم دیگر | DB::table('billing_payments') از داخل ماژول گزارش | API منتشرشدهٔ مالک را صدا بزنید |
| Common | چند ماژول دادهٔ سراسری مشترک دارند | var DB *sql.DB، Currency در سطح package | config() داخل منطق دامنه؛ جدول مشترک settings | وابستگی را صریح پاس دهید؛ config را در لبه بخوانید |
| External | قالب، پروتکل یا دستگاه تحمیلی مشترک | دو package یک فایل fixed-width را دستی parse میکنند | دو job یک XML شریک تجاری را دستی میسازند | یک adapter مالک قالب باشد |
| Control | صدازننده flagی میدهد که رفتار را انتخاب میکند | Render(o, asCSV, withNotes) | export($order, 'pdf') با یک match داخلش | به تابعهای اسمدار بشکنید (CSV، Text) |
| Stamp (data-structured) | کل ساختار پاس میشود، بخشی استفاده میشود | func Total(o *Order) که فقط Lines را میخواند | پاس دادن model User برای خواندن id | کوچکترین type را بدهید: []Line، int $userId، DTO |
| Data | فقط مقادیر پایه یا value objectهای کوچک | Total(lines []Line, cur string) Money | new OrderSummary($id, $paid, $cur) | هدف همین است |
Stevens و همکاران دربارهٔ control coupling: "an alternative structure that eliminates the complication always exists." روی timeline، یک flag کنترلی اینطور پخش میشود:
Step Change Modules edited
1 v1 Render(o, asCSV) report
2 v2 product asks for notes in CSV only report + 3 callers (new bool)
3 v3 add JSON: asCSV becomes format string report + 3 callers again
4 v4 a caller passes "cvs"; falls into default runtime bug, no compile error
5 fix CSV(s), Text(s), JSON(s): caller picks by name each new format edits 1 moduleسناریوی واقعی: متغیر سراسری utils.DB در Go که در تستها عوض و فراموش میشود و تست بعدی با دیتابیس اشتباه حرف میزند؛ ReportService::generate($type, $options) در Laravel که آرایهٔ $optionsش را فقط با خواندن ۴۰۰ خط میشود فهمید؛ اپ موبایل و backend که شکل JSON مشترکی دارند و هیچکس مالکش نیست (external coupling بدون قرارداد).
درمان: هر بار یک پله به راست نردبان بروید. کد: Go قبل و بعد، Laravel قبل و بعد.
وابستگی زمانی (Temporal coupling) مهم
به زبان ساده: دو چیز وابستگی زمانی دارند وقتی برای درست کار کردن سیستم باید به ترتیب مشخص یا همزمان اتفاق بیفتند.
بدفهمی رایج: «temporal coupling و temporal cohesion یکیاند.» انسجام زمانی (temporal cohesion) دلیلی برای کنار هم گذاشتن کد است (همه هنگام راهاندازی اجرا میشوند). وابستگی زمانی یک وابستگی در زمان بین ماژولهاست: «Init را قبل از Send صدا بزن» یا «سرویس پرداخت باید هنگام اجرای checkout بالا باشد».
تعریف: در کد، همان connascence of execution order است (بخش connascence): ترتیب درست را typeها تحمیل نمیکنند. بین سرویسها، وابستگیای است که فراخوانی همگام میسازد: صدازننده فقط وقتی کار میکند که طرف مقابل بالا و سریع باشد. مقالهٔ coupling در Wikipedia (منبع ثانویه) این نام را برای کارهایی هم به کار میبرد که "because they happen to occur at the same time" کنار هم آمدهاند.
t checkout (sync HTTP) payments service
1 0ms POST /charge ------------------------> up
2 40ms 200 OK <------------------------
3 ... deploy of payments starts
4 0ms POST /charge ------------------------> restarting
5 5s timeout; checkout returns 502 -- checkout availability = its own x payments'
6 fix write order + outbox row, return 202; payments consumes OrderPlaced when back upسناریوی واقعی: struct در Go با Init() که صدازنندهها فراموشش میکنند؛ listener در Laravel که باید بعد از listener دیگری اجرا شود چون ستونی را میخواند که اولی مینویسد؛ زنجیرهای از فراخوانی HTTP که دسترسپذیریها در هم ضرب میشوند (0.99 × 0.99 × 0.99 ≈ 0.97).
درمان: در کد، ترتیب نادرست را غیرقابلنمایش کنید (constructorی که شیء آماده برمیگرداند). بین سرویسها، اگر صدازننده همین حالا جواب لازم ندارد، فراخوانی را با پیام عوض کنید (outbox + broker، یعنی async). Go connascence و میکروسرویسها را ببینید.
وابستگی ورودی، خروجی و ناپایداری (Afferent, efferent, instability) مهم
به زبان ساده: وابستگی ورودی (afferent coupling، Ca) میشمارد چه کسانی به من وابستهاند؛ وابستگی خروجی (efferent coupling، Ce) میشمارد من به چه کسانی وابستهام. ناپایداری (instability) میگوید یک package چقدر راحت از بیرون هل داده میشود.
بدفهمی رایج: «ناپایداری بد است.» مارتین (۲۰۰۰): "we greatly desire that portions of our software be instable." UI و adapterها باید ناپایدار باشند (راحت عوض شوند)؛ سیاستهای هسته باید پایدار باشند. باگ وقتی است که package پایدار به package ناپایدار وابسته شود.
تعریف: مارتین، Design Principles and Design Patterns: "Ca Afferent Coupling. The number of classes outside the package that depend upon classes inside the package"؛ "Ce Efferent Coupling. The number of classes outside the package that classes inside the package depend upon"؛ I = Ce / (Ca + Ce) در بازهٔ 0 (پایدار) تا 1 (ناپایدار). اصل وابستگیهای پایدار: "Depend upon packages whose I metric is lower than yours." phpmetrics دقیقاً همین سه را با نامهای afferentCoupling، efferentCoupling و instability گزارش میکند.
| Package (عددهای آزمایشگاه) | Ca | Ce | I | نتیجه |
|---|---|---|---|---|
orders (interface سمت مصرفکننده) | 1 (cmd) | 0 package پروژه | 0.0 | هستهٔ پایدار، همانطور که میخواهیم |
stripepay | 1 (cmd) | 0 package پروژه | 0.0 | adapter برگ |
cmd | 0 | 2 | 1.0 | composition root: عمداً ناپایدار |
orders (قبل) | 0 | 1 (stripepay) | 1.0 | هسته به adapter فروشنده وابسته است: خلاف روح SDP |
Fan-in و fan-out همین ایده در سطح تابع یا class است (ابزار CK: FAN-IN یعنی "the number of input dependencies a class has").
انسجام (Cohesion) حیاتی
به زبان ساده: cohesion یعنی اجزای یک ماژول چقدر به هم تعلق دارند. cohesion بالا یعنی یک تغییر معمولاً داخل یک ماژول میماند.
بدفهمی رایج: «گذاشتن همهٔ helperهای رشته کنار هم منسجم است؛ همه دربارهٔ رشتهاند.» این logical cohesion است، دومین سطح ضعیف. سؤال این نیست که «اینها از یک جنساند؟» بلکه این است که «به یک کار خدمت میکنند و به یک دلیل عوض میشوند؟»
تعریف: Stevens و همکاران: "Binding is the measure of the cohesiveness of a module. The objective here is to reduce coupling by striving for high binding." cohesion و coupling دو روی یک تصمیماند: "minimizing the relationships among modules and maximizing relationships among elements in the same module."
نردبان تصویر از پایین (coincidental، بیدلیل) به بالا (functional، همه برای یک کار) میرود و برای هر پله دلیل کنار هم بودن و یک مثال آمده؛ پانویس یادآوری میکند که مقیاس ۱۹۷۴ شش سطح داشت و procedural بعداً اضافه شد.
| سطح | اجزا کنار هماند چون | مثال Go | مثال Laravel | حرکت برای درمان |
|---|---|---|---|---|
| 1 Coincidental | بیدلیل | package utils با Slugify، Retry، TaxRate | app/helpers.php | هر تابع را کنار تنها مصرفکنندهاش یا در package هدفمند ببرید |
| 2 Logical | یک دسته، انتخاب با flag | Export(kind string) با switch | ExportService::run($type) | یک type برای هر حالت پشت یک interface |
| 3 Temporal (temporal cohesion) | همزمان اجرا میشوند | func boot() که DB باز میکند، cache گرم میکند، به Slack پینگ میزند | یک AppServiceProvider::boot() که همه کار میکند | هر ماژول راهاندازی خودش را ثبت کند |
| 4 Procedural | گامهای یک رویه، دادهٔ بیربط | checkPermThenOpenFile() | متد controller که مجوز را چک میکند و بعد CSV میسازد | بر اساس داده بشکنید |
| 5 Communicational | روی یک داده کار میکنند | متدهایی روی یک Order | متدهای model روی یک Order | معمولاً خوب است |
| 6 Sequential | خروجی یکی خوراک بعدی است | parse → validate → normalise | مراحل Pipeline (Illuminate\Pipeline) | خوب است؛ interface مراحل را بپایید |
| 7 Functional | همه به یک کار کمک میکنند | cache.Get/Set | CurrencyConverter::convert | هدف همین است |
Request With package utils With purposeful packages
1 change slug rules for SEO edit utils/strings.go edit slug/slug.go
2 -- 40 packages import utils: all rebuild, all retest, review needs 3 teams --
3 change retry backoff for HTTP edit utils/retry.go edit httpclient/retry.go
4 a new hire looks for "tax rate" greps utils, finds 2 copies finds tax/rates.goقبل و بعد (cohesion): utils.Slugify، utils.Retry، utils.TaxRate ← slug.Make، httpclient.Retry، tax.Rate. قاعدهٔ Dave Cheney برای Go اینجا صدق میکند: نام package باید هدفش را بگوید، پس utils، common، helpers، misc علامت هشدارند.
پنهانسازی اطلاعات و کپسولهسازی (Information hiding & Encapsulation) حیاتی
به زبان ساده: پنهانسازی اطلاعات یعنی تصمیم بگیرید کدام تصمیمهای طراحی را ماژولهای دیگر هرگز نباید به آن تکیه کنند، و آنها را داخل یک ماژول نگه دارید. کپسولهسازی ابزار زبان است (فیلد private، نام unexported) که برای تحمیل آن به کار میبرید.
بدفهمی رایج: «فیلدهایم private است، پس پنهانسازی اطلاعات دارم.» اگر class برای هر فیلد getter و setter دارد، یا نام متدهایش محل ذخیره را لو میدهد (getRowsFromMysql)، تصمیم نشت کرده حتی اگر فیلدها خصوصی باشند. Ousterhout: "Using classes does not necessarily guarantee information hiding!"
تعریف: Parnas: هر ماژول "a design decision which it hides from all others" را پنهان میکند، با interfaceی که "chosen to reveal as little as possible about its inner workings." Ousterhout ضدش را نشت اطلاعات (Information leakage) مینامد: "Implementation details exposed, other classes depend on them"، بهاضافهٔ "Back-door leakage: not visible in the interface" (دو ماژول که هر دو یک قالب فایل را میدانند). او یک علت رایج را هم نام میبرد، تجزیهٔ زمانی (Temporal decomposition): "Code structure reflects the order in which operations execute"، که همان تجزیهٔ flowchartی Parnas است.
| پنهانسازی اطلاعات | کپسولهسازی | |
|---|---|---|
| نوع | اصل طراحی | سازوکار زبان |
| سؤال | کدام تصمیمها ممکن است عوض شوند و چه کسی نباید بداند؟ | کدام نامها از بیرون دیده میشوند؟ |
| Go | مرز package، internal/، API صادرشدهٔ کوچک | شناسههای با حرف کوچک unexported هستند |
| PHP | مرز ماژول، interface قرارداد، @internal + قاعدهٔ deptrac | private، protected، readonly |
| شکست وقتی | interface آینهٔ پیادهسازی است | getter/setter برای همه چیز؛ reflection |
Change Leaky module (exports map + mutex) Hiding module (Get/Set)
1 switch eviction from FIFO to LRU 12 callers edited cache.go only
2 add metrics on hit rate every caller adds counters cache.go only
3 shard the map to cut lock contention impossible without touching callers cache.go onlyسناریوی واقعی: schema دیتابیس (پشت repository پنهانش کنید؛ Data Persistence in Design)؛ ارائهدهندهٔ نرخ ارز؛ چیدمان فایل یک export؛ سیاست retry یک کلاینت HTTP؛ فناوری صف پشت «بعداً بفرست».
درمان: تصمیمهایی را که احتمال تغییرشان هست فهرست کنید (روش Parnas)، برای هر کدام یک ماژول بگذارید، و فقط آنچه صدازننده لازم دارد را بیرون بدهید. کد: cache عمیق در Go، CurrencyConverter در Laravel.
Interface بهعنوان قرارداد (Interfaces as contracts) حیاتی
به زبان ساده: interface یعنی هر چیزی که صدازننده باید بداند تا از یک ماژول درست استفاده کند: نه فقط امضای متدها، بلکه رفتار، خطاها، قواعد ترتیب و کاراییای که میتواند به آن تکیه کند.
بدفهمی رایج: «interface همان کلیدواژهٔ interface است.» Ousterhout آن را به بخش رسمی ("method signatures, public variables") و بخش غیررسمی ("overall behavior, side effects, constraints on usage") تقسیم میکند و بخش غیررسمی "can only be described with comments." تابعی در Go که ErrEmptyCart برمیگرداند آن خطا را در قراردادش دارد، چه نوشته باشید چه نه.
تعریف: قرارداد (contract) پیششرط دارد (آنچه صدازننده تضمین میکند)، پسشرط (آنچه ماژول تضمین میکند)، ناوردا، رفتار خطا و وعدههای غیرکارکردی (idempotency، تأخیر، ایمنی همروندی). صفحهٔ Liskov Substitution قواعد جایگزینی را پوشش میدهد و ISP باریک نگه داشتن هر interface را. Go Code Review Comments قاعدهٔ جایگذاری Go را میدهد: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types." مستندات Laravel قراردادهایش را "a set of interfaces that define the core services provided by the framework" توصیف میکند.
| بخش قرارداد | Go | Laravel / PHP | بین سرویسها |
|---|---|---|---|
| امضا | مجموعهٔ متد | متدهای interface، typeها | مسیر OpenAPI، پیام protobuf |
| خطاها | sentinel error، errors.Is | exception تایپدار | status code، schema بدنهٔ خطا |
| رفتار | doc comment | PHPDoc | مستندات API، مثال |
| ترتیب / چرخهٔ عمر | constructor مقدار آماده برمیگرداند | binding در container، constructor | کلید idempotency، نسخهبندی |
| همروندی | "safe for concurrent use" | (معمولاً یک درخواست) | محدودیت نرخ، تحویل at-least-once |
درمان: interface را جایی که مصرف میشود تعریف کنید، کوچک نگهش دارید، بخش غیررسمی را مستند کنید، و با contract test آزمایشش کنید. کد: interface سمت مصرفکننده در Go، قرارداد + provider در Laravel.
ماژول عمیق و کمعمق (Deep vs shallow modules) حیاتی
به زبان ساده: ماژول عمیق (deep module) پشت یک interface کوچک کارکرد زیادی میدهد؛ ماژول کمعمق (shallow) تقریباً به اندازهٔ چیزی که صرفهجویی میکند، یاد گرفتن لازم دارد.
بدفهمی رایج: «شکستن یک class به classهای کوچک زیاد همیشه پیچیدگی را کم میکند.» هر class یک interface اضافه میکند که کسی باید یادش بگیرد. Ousterhout: "Many courses teach students that 'classes should be small': results in shallow classes" و "Classitis: small classes taken to the extreme."
تعریف: یادداشتهای Ousterhout: "Deep class: small interface, lots of functionality"؛ class کمعمق: "Complex interface and/or not much functionality. Invoking a method isn't much easier than just typing in the code of the method." مثال کلاسیک عمیق او I/O فایل در Unix است (open، read، write، lseek، close که چیدمان دیسک، cache، مجوزها و دستگاهها را پنهان میکنند). پرچم قرمزش متد عبوری (pass-through method) است که فراخوانی را با همان امضا جلو میفرستد و انتزاعی اضافه نمیکند ("Each layer's abstraction should be different from the layer above it and the layer below it").
لبهٔ بالای هر جعبه interface است (آنچه باید یاد بگیرید) و مساحتش کارکرد (آنچه میگیرید). cache عمیق فقط Get و Set را بیرون میدهد و قفل، انقضا، بیروناندازی، ساعت و چیدمان ذخیره را پنهان میکند؛ cache کمعمق mutex، map و یک helper انقضا را بیرون میدهد و هر صدازننده باید پروتکل قفل، جستوجو، بررسی انقضا و حذف را تکرار کند.
| علامت | عمیق | کمعمق |
|---|---|---|
| اندازهٔ interface نسبت به پیادهسازی | خیلی کوچکتر | تقریباً هماندازه |
| صدازنندهها راهاندازی یا پروتکل را تکرار میکنند | نه | بله |
| پیادهسازی آزادانه عوض میشود | بله | نه، صدازنندهها به آن وابستهاند |
| شکل رایج | CurrencyConverter::convert، io.Reader، net/http.Client.Do | classهای getter/setter، XRepositoryInterface که آینهٔ Eloquent است، serviceهای عبوری |
درمان: تکههای کمعمقی را که همیشه با هم استفاده میشوند ادغام کنید، کد تکراری صدازنندهها را به داخل ماژول بکشید، و برای نیاز امروز interfaceی «somewhat generic» (به عبارت Ousterhout) بسازید.
جداسازی دغدغهها و دغدغههای همهجاگیر (Separation of concerns & Cross-cutting concerns) حیاتی
به زبان ساده: هر دغدغه (قاعدهٔ کسبوکار، HTTP، ذخیرهسازی، امنیت، لاگ) جای خودش را دارد، تا بتوانید دربارهٔ یکی فکر کنید و عوضش کنید بیآنکه بقیه درگیر شوند.
بدفهمی رایج: «separation of concerns یعنی لایهها: controller، service، repository.» لایهها یک راه جدا کردن دغدغههای فنیاند. منظور Dijkstra هر جنبهای است که بشود "in isolation for the sake of its own consistency" مطالعهاش کرد: درستی در برابر کارایی، سیاست در برابر سازوکار، قاعدهٔ قیمت در برابر انتقال HTTPاش. لایهبندی کنید ولی دو دغدغهٔ کسبوکاری را در یک service قاطی کنید، باز هم نقض است.
تعریف: دغدغه (concern) جنبهای از سیستم با دلیل تغییر خودش است. دغدغهٔ همهجاگیر (cross-cutting concern) دغدغهای است که همزمان به ماژولهای زیادی مربوط است: لاگ، احراز هویت، مجوزدهی، معیارها، tracing، تراکنش، cache، محدودیت نرخ، اعتبارسنجی ورودی. اگر دستی پخش شوند، درهمتنیدگی (tangling: دغدغههای زیاد در یک تابع) و پراکندگی (scattering: یک دغدغه در تابعهای زیاد) میسازند. ابزارهای معمول middleware و decorator، hookهای فریمورک، event، و در بعضی زبانها برنامهنویسی جنبهگرا (AspectJ، Spring AOP) است.
Change request Tangled handler Middleware + pure rule
1 switch logging to slog JSON edit every handler edit Logging middleware
2 rotate API token header name edit every handler edit RequireToken
3 change 10% discount to 12% edit handler (risk: breaks auth path) edit TotalCents, unit test only
4 add tracing span per request edit every handler add one middleware| دغدغهٔ همهجاگیر | Go | Laravel |
|---|---|---|
| احراز هویت | middleware به شکل func(http.Handler) http.Handler | middleware (auth:sanctum، سفارشی) |
| مجوزدهی | middleware یا بررسی صریح در use case | Policy، Gate |
| لاگ / tracing | middleware، log/slog، handlerهای OpenTelemetry | middleware، log context، Telescope/Pulse |
| تراکنش | تابع use case با db.BeginTx | DB::transaction در action |
| اعتبارسنجی | decode + validate در adapter handler | Form Request |
| Cache | decorator دور یک interface | Cache::remember داخل یک ماژول عمیق |
| اثر جانبی بعد از یک واقعیت | انتشار event | events + listener صفدار |
درمان: قاعدهٔ کسبوکار را از انتقال و I/O آزاد نگه دارید؛ دغدغههای همهجاگیر را در middleware یا decorator بگذارید؛ بگذارید واکنشها به eventها subscribe کنند. کد: middleware در Go، middleware در Laravel، events در Laravel.
یکپارچگی مفهومی (Conceptual integrity) مهم
به زبان ساده: کل سیستم طوری حس میشود که انگار یک ذهن طراحیاش کرده: یک روش نامگذاری، یک روش مدیریت خطا، یک روش صفحهبندی، یک مدل از دامنه.
بدفهمی رایج: «یکپارچگی مفهومی یعنی یک نفر همه چیز را بنویسد.» Brooks معماری (مشخصات بیرونی) را از پیادهسازی جدا میکند و میگوید طراحی "must proceed from one mind, or from a very small number of agreeing resonant minds"، در حالی که پیادهسازی هنوز دستهای زیادی لازم دارد. "The design of an implementation, given an architecture, requires and allows as much design creativity."
تعریف: Brooks: "Simplicity and straightforwardness proceed from conceptual integrity. Every part must reflect the same philosophies and the same balancing of desiderata." و دربارهٔ قابلیتهایی که جا نمیافتند: "Good features and ideas that do not integrate with a system's basic concepts are best left out."
تیمها چطور از دستش میدهند:
| علت | چه شکلی است | پادزهر |
|---|---|---|
| نویسندگان زیاد، بدون مالک مفاهیم | سه سبک صفحهبندی: ?page=، ?offset=، cursor | نقش معمار یا مرجع طراحی برای مشخصات بیرونی |
| رشد قابلیتبهقابلیت | هر endpoint JSON خطای خودش را اختراع میکند | یک قالب خطا (مثلاً RFC 9457 problem details) که در middleware تحمیل شود |
| جابهجایی تیم | تیم تازه مسئلهٔ قدیمی را جور دیگری حل میکند | ADR که تصمیم و دلیلش را ثبت کند |
| قاطی کردن فریمورک | نیمی از اپ Eloquent، نیمی SQL خام با آرایه | راهنمای مکتوب «اینجا X را اینطور انجام میدهیم» و قواعد lint |
| میکروسرویس بدون platform | هر سرویس auth، لاگ و config خودش را دارد | paved road / کتابخانههای مشترک، راهنمای سبک API |
| کپی از اینترنت | الگوهایی که با فریمورک میجنگند | بازبینی در برابر راهنما، نه سلیقه |
قبل و بعد (یکپارچگی مفهومی):
Before After (one API style guide)
1 GET /orders?page=2&per_page=20 GET /orders?cursor=abc&limit=20
2 GET /customers?offset=40&limit=20 GET /customers?cursor=def&limit=20
3 GET /invoices/list/3 GET /invoices?cursor=ghi&limit=20
4 errors: {"error":"x"}, {"message":"x"}, "x" errors: application/problem+json everywhereدرمان: آن چند تصمیمی را که همهٔ بخشها باید شریک باشند مکتوب کنید (نامگذاری، خطا، صفحهبندی، شناسه، منطقهٔ زمانی، پول، auth)، دلیلش را در ADR ثبت کنید (Architecture Decisions)، و به قابلیتهایی که جا نمیافتند «نه» بگویید. به همین دلیل است که Architecture vs Design نقش معمار را همانجا میگذارد که میگذارد.
Connascence تکمیلی
به زبان ساده: دو تکه کد connascent هستند وقتی تغییر یکی، تغییر دیگری را برای درست ماندن برنامه لازم کند. connascence اسم نوع توافقی است که با هم دارند.
بدفهمی رایج: «connascence فقط اسم دیگر coupling است.» مقیاسی دقیقتر با سه محور است. دو ماژول ممکن است هر دو «data coupled» باشند در حالی که یک جفت فقط روی یک نام توافق دارد (راحت عوض میشود) و جفت دیگر روی ترتیب پنج آرگومان ترتیبی (شکننده).
تعریف: connascence.io: "Connascence is a software quality metric & a taxonomy for different types of coupling"، سنجیده بر قدرت (strength: "the ease with which that type of coupling can be refactored")، درجه (degree: "Does the coupling in question affect 2 entities, or 200?") و محلی بودن (locality: "Code that is close together ... should typically have more, and higher forms of connascence than code that is far apart"). "Static connascences are considered to be weaker than dynamic connascences."
| شکل (ضعیف به قوی) | ایستا / پویا | دو تکه باید توافق کنند روی | مثال | جایگزین ضعیفتر |
|---|---|---|---|---|
| Name | ایستا | یک نام | صدا زدن Charge | (همین ضعیفترین است) |
| Type | ایستا | یک type | int سنت در برابر float یورو | value type (Money) |
| Meaning (قرارداد) | ایستا | معنای یک مقدار | role == 2 یعنی ادمین؛ "9999-9999-9999-9999" کارت تست است | ثابت اسمدار، enum |
| Position | ایستا | ترتیب مقادیر | New(name, email, true, false, 2) | فیلد اسمدار، struct گزینهها |
| Algorithm | ایستا | یک الگوریتم یکسان | کلاینت و سرور هر دو HMAC یا checksum حساب میکنند | یک تابع یا کتابخانهٔ مشترک |
| Execution (ترتیب) | پویا | ترتیب اجرا | Init() قبل از Send() | constructor که شیء آماده برمیگرداند |
| Timing | پویا | زمانبندی اجرا | race بین نوشتن و خواندن cache؛ فرضهای timeout | همگامسازی، idempotency |
| Value | پویا | مقادیری که باید سازگار بمانند | دو نسخه از یک قیمت؛ جمع cacheشده | یک منبع حقیقت، مشتق کنید |
| Identity | پویا | ارجاع به یک نمونهٔ واحد | دو سرویس باید یک ردیف را بهروز کنند | یک مالک، ID به جای ارجاع شیء |
Step Connascence Degree Locality Action
1 role == 2 in 30 places meaning 30 across 6 packages high risk: refactor
2 → const Admin Role = 2 name 30 across 6 packages safe: rename is mechanical
3 New(name, email, true, false, 2) position 12 across 3 packages refactor to User{...}
4 two locals in one 10-line func position 1 same function leave it: local and visibleقاعدهٔ سرانگشتی: شکلهای قوی را به ضعیف تبدیل کنید (connascence of meaning یا position به connascence of name یا type)، درجه را کم کنید، و هر connascence قویای که میماند را محلی نگه دارید (داخل یک تابع یا package). کد: connascence قبل و بعد در Go.
نگاه هر زبان و ابزار
| زبان / فریمورک | واحد پنهانسازی | سازوکار interface | تحمیل مرز | معیار و قاعده |
|---|---|---|---|---|
| Go | package (internal/ برای خصوصی ماژول) | interface ضمنی، تعریفشده در سمت مصرفکننده | کامپایلر: نام unexported، internal/، ممنوعیت چرخهٔ import | gocyclo، gocognit، golangci-lint، go-arch-lint، go list -deps |
| PHP / Laravel | class + پوشهٔ ماژول یا package Composer | interface، contracts لاراول، binding در container | private/readonly، لایههای deptrac، تستهای Pest arch() | phpmetrics، PHPStan/Larastan، deptrac |
| Java / Spring | package + ماژول JPMS | interface، bean در Spring | package-private، module-info.java، ArchUnit | CK (CBO، LCOM، FAN-IN/OUT)، SonarQube |
| C# / .NET | assembly | interface، DI container | internal، ارجاع پروژه، NetArchTest | code metrics در Visual Studio (class coupling، cyclomatic) |
| TypeScript | ES module + package | typeهای ساختاری | نقشهٔ exports، قواعد import در eslint، dependency-cruiser | dependency-cruiser، قاعدهٔ complexity در eslint |
سازوکار
پیچیدگی cyclomatic (Cyclomatic complexity) مهم
معیار McCabe مسیرهای مستقل خطی در گراف جریان کنترل یک تابع را میشمارد: v(G) = e - n + 2p (یالها، گرهها، مؤلفههای همبند). در عمل ابزارها تصمیمها را میشمارند. README ابزار gocyclo قواعدش را میگوید: "1 is the base complexity of a function, +1 for each 'if', 'for', 'case', '&&' or '||'". سقف خود McCabe عدد 10 بود، "reasonable, but not magical." این معیار مسیرهای تست را میسنجد، نه فهم را: یک switch تخت با ۱۵ case امتیاز 16 میگیرد و خواندنش آسان است؛ سه حلقهٔ تودرتو با returnهای زودهنگام ممکن است 6 بگیرد و سخت باشد. ابزارهای cognitive complexity (SonarQube، gocognit) برای نزدیک شدن به خوانایی به تودرتویی وزن میدهند.
go install github.com/fzipp/gocyclo/cmd/gocyclo@latest
gocyclo -over 10 ./... # exit code 1 if any function is above 10
gocyclo -top 10 -avg . # ten worst plus the averageLCOM: کمبود انسجام متدها تکمیلی
LCOM (Lack of Cohesion of Methods) میشمارد چند جفت متد یک class هیچ فیلد مشترکی ندارند، منهای جفتهایی که دارند (نسخهٔ اول Chidamber و Kemerer)، یا در نسخههای بعدی (LCOM*، LCOM-HS، LCOM4) متدها چند گروه جدا از هم میسازند. README ابزار CK هشدار میدهد که نسخهٔ اول "is not reliable." phpmetrics مقدار lcom را گزارش میکند و توضیح میدهد: "A non-cohesive class may need to be restructured into two or more smaller classes." از آن برای پیدا کردن نامزد استفاده کنید، هرگز بهعنوان دروازهٔ CI: classی که همه چیز را به یک وابستگی واگذار میکند امتیاز خوب میگیرد و باز هم میتواند کمعمق باشد.
Fan-in، fan-out و معیارهای package مهم
| معیار | فرمول | الگوی سالم | الگوی ناسالم |
|---|---|---|---|
| Fan-in (Ca) | ماژولهایی که به این وابستهاند | بالا روی ماژولهای کوچک و پایدار (money، time) | بالا روی ماژولی که هر هفته عوض میشود |
| Fan-out (Ce) | ماژولهایی که این به آنها وابسته است | بالا فقط در composition root (main، service provider) | بالا در کد دامنه |
| Instability I | Ce / (Ca + Ce) | وابستگیها به سمت I کمتر | هستهٔ پایدار adapter ناپایدار را import میکند |
| Abstractness A | typeهای انتزاعی / همهٔ typeها | packageهای پایدار انتزاعیاند | پایدار و concrete («zone of pain») |
| Distance D | abs(A + I - 1) | نزدیک 0 («main sequence») | نزدیک 1 |
| Structural complexity (Card و Agresti، phpmetrics) | مجذور fan-out | پایین | با هر فراخوانی سریع رشد میکند |
فصل DIP نمودار main sequence را کشیده است.
قواعد معماری به شکل تست حیاتی
معیارها توصیف میکنند؛ قواعد جلوگیری میکنند. هر دو اکوسیستم ابزاری دارند که وقتی import ممنوع ظاهر شود CI را شکست میدهد.
go-arch-lint فایل .go-arch-lint.yml را میخواند (از README آن: "Linter used to enforce some good project structure and validate top level architecture (code layers)"):
version: 3
workdir: internal
components:
handler: { in: handlers/* }
service: { in: services/** }
repository: { in: domain/*/repository }
model: { in: models }
commonComponents:
- models
deps:
handler:
mayDependOn:
- service
service:
mayDependOn:
- repositorygo install github.com/fe3dback/go-arch-lint@latest
go-arch-lint check --project-path .deptrac برای PHP ("helps you communicate, visualize and enforce architectural decisions"): لایهها را با collectorها تعریف کنید و یک ruleset بنویسید که چه کسی از چه کسی مجاز است استفاده کند.
# deptrac.yaml: module boundaries for a Laravel modular monolith.
# Run: vendor/bin/deptrac analyse --config-file=deptrac.yaml
deptrac:
paths:
- ./app
layers:
- name: BillingContracts
collectors:
- type: directory
value: app/Modules/Billing/Contracts/.*
- name: BillingInternal
collectors:
- type: directory
value: app/Modules/Billing/Internal/.*
- name: Reporting
collectors:
- type: directory
value: app/Modules/Reporting/.*
- name: Http
collectors:
- type: directory
value: app/Http/.*
ruleset:
Http:
- BillingContracts
- Reporting
Reporting:
- BillingContracts
BillingInternal:
- BillingContracts
BillingContracts: ~composer require --dev deptrac/deptrac
vendor/bin/deptrac analyse --config-file=deptrac.yaml
composer global require 'phpmetrics/phpmetrics'
phpmetrics --report-html=report ./app # ccn, lcom, afferent/efferent coupling, instabilityChange coupling از git تکمیلی
ابزارهای ایستا importها را میبینند؛ دو فایلی را که هیچ importی بینشان نیست ولی همیشه با هم عوض میشوند نمیبینند (دانش مشترک، external coupling، نشت از در پشتی). فصل SRP کوئری git + SQLite را دارد؛ آن را برای هر پوشهٔ ماژول اجرا کنید و امتیاز بالا بین مرزهای ماژول را coupling پنهان بخوانید.
جدول ابزارها تکمیلی
| ابزار | زبان | میسنجد / تحمیل میکند | دروازهٔ رایج CI |
|---|---|---|---|
| gocyclo | Go | cyclomatic complexity هر تابع | gocyclo -over 15 ./... |
| gocognit | Go | cognitive complexity | از طریق golangci-lint |
| golangci-lint | Go | اجرای gocyclo، gocognit، depguard و غیره | golangci-lint run |
| go-arch-lint | Go | وابستگیهای مجاز بین componentها | go-arch-lint check |
| phpmetrics | PHP | ccn، lcom، Ca/Ce/instability، maintainability index | گزارش HTML، آستانه با اسکریپت |
| deptrac | PHP | وابستگیهای مجاز بین لایهها | vendor/bin/deptrac analyse |
Pest arch() | PHP | انتظاراتی مثل «App\Modules\Billing نباید در X استفاده شود» | ./vendor/bin/pest --filter=arch |
| PHPStan / Larastan | PHP | typeها (غافلگیری connascence of type را کم میکند) | phpstan analyse |
Go
Coupling: قبل و بعد
package قبل یک DB و Currency سراسری را شریک است (common coupling)، کل *Order را برای خواندن Lines میگیرد (stamp coupling)، و خروجیاش را با دو boolean تعیین میکند (control coupling).
// Package report is the "before" side of the coupling scale.
// It compiles and works, but it shows common, stamp and control coupling.
package report
import (
"context"
"database/sql"
"fmt"
)
// DB is common coupling: every importer can read or replace it.
var DB *sql.DB
// Currency is common coupling too: a global that silently changes output.
var Currency = "EUR"
// Order is the full record. Callers that need two fields still get all of it.
type Order struct {
ID int64
CustomerEmail string
ShippingAddress string
Notes string
Lines []Line
TotalCents int64
}
// Line is one order line.
type Line struct {
SKU string
Qty int
PriceCents int64
}
// LoadOrder depends on the package-level DB (common coupling).
func LoadOrder(ctx context.Context, id int64) (*Order, error) {
o := &Order{ID: id}
err := DB.QueryRowContext(ctx,
`SELECT customer_email, shipping_address, notes FROM orders WHERE id = $1`, id).
Scan(&o.CustomerEmail, &o.ShippingAddress, &o.Notes)
if err != nil {
return nil, err
}
return o, nil
}
// Total takes the whole Order (stamp coupling) and mutates it as a side effect.
func Total(o *Order) {
o.TotalCents = 0
for _, l := range o.Lines {
o.TotalCents += int64(l.Qty) * l.PriceCents
}
}
// Render is control coupled: the caller passes a flag that picks the branch.
func Render(o *Order, asCSV bool, withNotes bool) string {
if asCSV {
if withNotes {
return fmt.Sprintf("%d,%d,%s,%q\n", o.ID, o.TotalCents, Currency, o.Notes)
}
return fmt.Sprintf("%d,%d,%s\n", o.ID, o.TotalCents, Currency)
}
s := fmt.Sprintf("Order %d: %.2f %s", o.ID, float64(o.TotalCents)/100, Currency)
if withNotes && o.Notes != "" {
s += " (" + o.Notes + ")"
}
return s
}بعد: مقدار ورودی، مقدار خروجی. Store اتصالش را دریافت میکند؛ قالببندها تابعهای جدا هستند؛ Money مبلغ و ارز را کنار هم نگه میدارد تا از هم جدا نیفتند (connascence of value که محلی شده).
// Package report is the "after" side: data coupling only, no globals, no flags.
package report
import (
"context"
"database/sql"
"fmt"
)
// Money is a value: amount and currency always travel together.
type Money struct {
Cents int64
Currency string
}
// Summary is the smallest structure the formatters need.
type Summary struct {
OrderID int64
Total Money
}
// Line is one order line.
type Line struct {
Qty int
Unit Money
}
// Total is data coupled: it receives exactly the data it needs and returns a value.
func Total(lines []Line, currency string) Money {
t := Money{Currency: currency}
for _, l := range lines {
t.Cents += int64(l.Qty) * l.Unit.Cents
}
return t
}
// CSV and Text replace the asCSV flag with two functions; the caller picks by name.
func CSV(s Summary) string {
return fmt.Sprintf("%d,%d,%s\n", s.OrderID, s.Total.Cents, s.Total.Currency)
}
// Text renders a human-readable line.
func Text(s Summary) string {
return fmt.Sprintf("Order %d: %.2f %s", s.OrderID, float64(s.Total.Cents)/100, s.Total.Currency)
}
// Store owns its connection; nobody else can swap it at runtime.
type Store struct {
db *sql.DB
}
// NewStore receives the dependency explicitly.
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
// Summary loads only the columns the report needs.
func (s *Store) Summary(ctx context.Context, id int64) (Summary, error) {
out := Summary{OrderID: id}
err := s.db.QueryRowContext(ctx,
`SELECT total_cents, currency FROM orders WHERE id = $1`, id).
Scan(&out.Total.Cents, &out.Total.Currency)
return out, err
}پنهانسازی اطلاعات: cache کمعمق و عمیق
// Package cache is a shallow module: its interface is almost as big as its body.
// Every caller must know about the mutex, the map and the expiry rule.
package cache
import (
"sync"
"time"
)
// Entry is exported, so its layout is part of the interface.
type Entry struct {
Value []byte
ExpiresAt time.Time
}
// Cache exposes its lock and its map (information leakage).
type Cache struct {
Mu sync.Mutex
Items map[string]Entry
}
// New returns an empty cache.
func New() *Cache { return &Cache{Items: map[string]Entry{}} }
// IsExpired forces callers to implement the expiry protocol themselves.
func (c *Cache) IsExpired(e Entry, now time.Time) bool { return now.After(e.ExpiresAt) }
// Usage that every caller has to repeat (and can get wrong):
//
// c.Mu.Lock()
// e, ok := c.Items[key]
// if ok && c.IsExpired(e, time.Now()) {
// delete(c.Items, key)
// ok = false
// }
// c.Mu.Unlock()// Package cache is a deep module: two methods, and everything else is hidden.
package cache
import (
"sync"
"time"
)
type entry struct {
value []byte
expiresAt time.Time
}
// Cache is safe for concurrent use. Locking, expiry, eviction and the clock are private decisions.
type Cache struct {
mu sync.Mutex
items map[string]entry
order []string // insertion order, used for eviction
max int
nowFunc func() time.Time
}
// New returns a cache that holds at most maxEntries values.
func New(maxEntries int) *Cache {
return &Cache{items: make(map[string]entry), max: maxEntries, nowFunc: time.Now}
}
// Get returns the value and true if it exists and has not expired.
func (c *Cache) Get(key string) ([]byte, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.items[key]
if !ok {
return nil, false
}
if c.nowFunc().After(e.expiresAt) {
delete(c.items, key)
return nil, false
}
return e.value, true
}
// Set stores a value for ttl. When the cache is full the oldest key is evicted.
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
if _, exists := c.items[key]; !exists {
c.order = append(c.order, key)
}
c.items[key] = entry{value: value, expiresAt: c.nowFunc().Add(ttl)}
for len(c.items) > c.max && len(c.order) > 0 {
oldest := c.order[0]
c.order = c.order[1:]
delete(c.items, oldest)
}
}نسخهٔ بعد میتواند به LRU برود، map را shard کند یا معیار اضافه کند بیآنکه هیچ صدازنندهای بفهمد؛ نسخهٔ قبل حتی نام فیلدهایش را هم نمیتواند عوض کند.
Interface در سمت مصرفکننده
قبل: orders package فروشنده را import میکند و کلاینت را خودش میسازد.
// Package orders (before) imports the concrete provider and builds it itself.
package orders
import (
"context"
"os"
"academy/design-quality-principles/consumeriface/stripepay"
)
// Service is tied to one vendor, one constructor and one environment variable.
type Service struct{}
// Checkout cannot be tested without the real provider package and its configuration.
func (Service) Checkout(ctx context.Context, customerID string, cents int64) (string, error) {
client := stripepay.New(os.Getenv("STRIPE_KEY"))
return client.Charge(ctx, customerID, cents)
}بعد: orders همان یک متدی را که لازم دارد اعلام میکند؛ stripepay یک *Client concrete برمیگرداند و از orders چیزی نمیداند؛ main آنها را به هم وصل میکند.
// Package orders (after) owns the interface it needs: one method, in its own words.
package orders
import (
"context"
"errors"
)
// Payments is declared by the consumer. Any type with this method satisfies it implicitly.
type Payments interface {
Charge(ctx context.Context, customerID string, cents int64) (string, error)
}
// ErrEmptyCart is part of this package's contract.
var ErrEmptyCart = errors.New("orders: cart is empty")
// Service depends on the small interface, not on a vendor package.
type Service struct {
payments Payments
}
// NewService receives its dependency; the composition root decides which one.
func NewService(p Payments) *Service { return &Service{payments: p} }
// Checkout charges the cart total.
func (s *Service) Checkout(ctx context.Context, customerID string, cents int64) (string, error) {
if cents == 0 {
return "", ErrEmptyCart
}
return s.payments.Charge(ctx, customerID, cents)
}// Package stripepay is a provider. It returns a concrete type and defines no interface.
package stripepay
import (
"context"
"fmt"
"net/http"
"time"
)
// Client talks to a payment provider over HTTP.
type Client struct {
apiKey string
http *http.Client
}
// New returns a concrete client (Go Code Review Comments: return concrete types).
func New(apiKey string) *Client {
return &Client{apiKey: apiKey, http: &http.Client{Timeout: 5 * time.Second}}
}
// Charge charges a customer and returns the provider's charge id.
func (c *Client) Charge(ctx context.Context, customerID string, cents int64) (string, error) {
if cents <= 0 {
return "", fmt.Errorf("stripepay: amount must be positive, got %d", cents)
}
// A real client would POST to the provider here using c.http and c.apiKey.
return fmt.Sprintf("ch_%s_%d", customerID, cents), nil
}
// Refund is used by another consumer; orders never needs to know it exists.
func (c *Client) Refund(ctx context.Context, chargeID string) error { return nil }// Command cmd is the composition root: the only place that knows both packages.
package main
import (
"context"
"fmt"
"log"
"academy/design-quality-principles/consumeriface/orders"
"academy/design-quality-principles/consumeriface/stripepay"
)
type fakePayments struct{}
func (fakePayments) Charge(ctx context.Context, customerID string, cents int64) (string, error) {
return "fake_charge", nil
}
func main() {
prod := orders.NewService(stripepay.New("sk_test_example"))
id, err := prod.Checkout(context.Background(), "cus_42", 1999)
if err != nil {
log.Fatal(err)
}
fmt.Println("provider:", id)
test := orders.NewService(fakePayments{})
id, _ = test.Checkout(context.Background(), "cus_42", 1999)
fmt.Println("fake:", id)
}Connascence: position، meaning، ترتیب اجرا
// Package user (before) shows connascence of position, meaning and execution order.
package user
import (
"errors"
"fmt"
)
// User holds an int role: 0 = member, 1 = manager, 2 = admin (connascence of meaning).
type User struct {
Name, Email string
Active bool
Role int
}
// New has five positional parameters; two bools and two strings can be swapped silently
// (connascence of position).
func New(name, email string, active, verified bool, role int) User {
_ = verified
return User{Name: name, Email: email, Active: active, Role: role}
}
// IsAdmin repeats the magic number. Every caller must agree that 2 means admin.
func IsAdmin(u User) bool { return u.Role == 2 }
// Mailer must be Init-ed before Send (connascence of execution order, temporal coupling).
type Mailer struct {
host string
ready bool
}
// Init must be called first.
func (m *Mailer) Init(host string) { m.host, m.ready = host, true }
// Send fails at runtime if the caller forgot Init.
func (m *Mailer) Send(to, body string) error {
if !m.ready {
return errors.New("mailer: Init not called")
}
fmt.Printf("smtp %s -> %s: %s\n", m.host, to, body)
return nil
}// Package user (after) turns strong connascence into weak connascence of name and type.
package user
import (
"errors"
"fmt"
)
// Role is a named type; the compiler checks it (connascence of type).
type Role int
// Named constants replace magic numbers (connascence of meaning becomes connascence of name).
const (
Member Role = iota
Manager
Admin
)
// User is built from named fields.
type User struct {
Name, Email string
Active bool
Verified bool
Role Role
}
// IsAdmin compares against a name, not a number.
func (u User) IsAdmin() bool { return u.Role == Admin }
// Example call site: every field is named, order does not matter.
var Example = User{Name: "Sara", Email: "sara@example.com", Active: true, Role: Admin}
// Mailer cannot exist in a half-initialised state.
type Mailer struct {
host string
}
// NewMailer is the only way to build a Mailer, so "Init before Send" cannot be forgotten.
func NewMailer(host string) (*Mailer, error) {
if host == "" {
return nil, errors.New("mailer: host required")
}
return &Mailer{host: host}, nil
}
// Send needs no readiness check.
func (m *Mailer) Send(to, body string) error {
fmt.Printf("smtp %s -> %s: %s\n", m.host, to, body)
return nil
}جداسازی دغدغهها: middleware
// Package handler (before) tangles four concerns in one function:
// authentication, logging, timing and the business rule.
package handler
import (
"encoding/json"
"log"
"net/http"
"time"
)
// Price handles GET /price?qty=N.
func Price(w http.ResponseWriter, r *http.Request) {
start := time.Now()
if r.Header.Get("Authorization") != "Bearer secret-token" {
log.Printf("denied %s %s", r.Method, r.URL.Path)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
qty := 1
if r.URL.Query().Get("qty") == "10" {
qty = 10
}
total := qty * 499
if qty >= 10 {
total = total * 90 / 100
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]int{"total_cents": total})
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
}// Package handler (after) separates concerns: the rule, the HTTP adapter,
// and cross-cutting middleware are three different pieces.
package handler
import (
"encoding/json"
"log/slog"
"net/http"
"strconv"
"time"
)
// TotalCents is the business rule: no HTTP, no logging, trivially testable.
func TotalCents(qty int) int {
total := qty * 499
if qty >= 10 {
total = total * 90 / 100
}
return total
}
// Price is the HTTP adapter: decode, call the rule, encode.
func Price(w http.ResponseWriter, r *http.Request) {
qty, err := strconv.Atoi(r.URL.Query().Get("qty"))
if err != nil || qty < 1 {
qty = 1
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]int{"total_cents": TotalCents(qty)})
}
// RequireToken is a cross-cutting concern applied to any handler.
func RequireToken(token string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+token {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// Logging is another cross-cutting concern.
func Logging(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Info("request", "method", r.Method, "path", r.URL.Path, "duration", time.Since(start))
})
}
// Routes composes the pieces; the order of wrapping is the only place they meet.
func Routes(log *slog.Logger, token string) http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /price", RequireToken(token, http.HandlerFunc(Price)))
return Logging(log, mux)
}نگاه Go
Go چند تا از این اصلها را در خود ابزار ساخته است. شناسههای unexported همان کپسولهسازیاند؛ package واحد پنهانسازی اطلاعات است؛ internal/ یک package را فقط از درخت والدش قابل import میکند؛ چرخهٔ import خطای کامپایل است، پس دو package که به هم نیاز دارند مجبورند مالک واقعی مفهوم مشترک را پیدا کنند. interfaceها ضمنی برآورده میشوند و همین interface سمت مصرفکننده را ممکن میکند: مصرفکننده میتواند interface یکمتدی تعریف کند که type شخص ثالث از قبل برآوردهاش میکند. Go proverbs میگوید "The bigger the interface, the weaker the abstraction" و "A little copying is better than a little dependency": هر دو قاعدهٔ couplingاند. io.Reader و io.Writer نمونهٔ درسی interfaceهای عمیق در کتابخانهٔ استانداردند: هر کدام یک متد، پیادهشده توسط فایل، سوکت، بافر، جریان gzip و بدنهٔ HTTP.
shop/
cmd/api/main.go # composition root: the only file with Ce to everything
internal/
orders/ # core: declares Payments, Inventory interfaces it needs
payments/stripe/ # adapter: returns *Client, imports nothing from orders
inventory/postgres/ # adapter
httpapi/ # transport + middleware (cross-cutting concerns)
.go-arch-lint.yml # forbids orders -> payments/*, inventory/*Laravel
Coupling: قبل و بعد
controller جدول خصوصی billing را میخواند، config سراسری را در عمق قالببندی میخواند، و خروجی را با flagهای boolean عوض میکند.
<?php
// app/Http/Controllers/OrderReportController.php
// Common coupling (config + another module's table), stamp coupling (whole model),
// control coupling (a format flag) in one controller.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OrderReportController extends Controller
{
public function __invoke(Request $request, Order $order)
{
// Reaches into the billing module's private table (content-like coupling).
$paid = DB::table('billing_payments')->where('order_id', $order->id)->sum('amount_cents');
return response(
$this->render($order, $paid, $request->boolean('csv'), $request->boolean('notes')),
);
}
// The flags decide which branch runs: control coupling.
private function render(Order $order, int $paid, bool $csv, bool $notes): string
{
$currency = config('shop.currency'); // global, read anywhere (common coupling)
if ($csv) {
return $notes
? "{$order->id},{$paid},{$currency},\"{$order->notes}\"\n"
: "{$order->id},{$paid},{$currency}\n";
}
return sprintf('Order %d: %.2f %s', $order->id, $paid / 100, $currency);
}
}بعد: billing قرارداد PaymentTotals را منتشر و در service provider خودش bind میکند؛ گزارش از یک مقدار کوچک OrderSummary استفاده میکند؛ قالببندی دو class است؛ config یک بار در لبه با giveConfig خوانده میشود (قابلیت مستند container در Laravel 13).
<?php
// app/Modules/Billing/Contracts/PaymentTotals.php: the billing module's published contract.
namespace App\Modules\Billing\Contracts;
interface PaymentTotals
{
public function paidCents(int $orderId): int;
}
// app/Modules/Billing/Internal/EloquentPaymentTotals.php: only billing touches its own table.
namespace App\Modules\Billing\Internal;
use App\Modules\Billing\Contracts\PaymentTotals;
use Illuminate\Support\Facades\DB;
final class EloquentPaymentTotals implements PaymentTotals
{
public function paidCents(int $orderId): int
{
return (int) DB::table('billing_payments')->where('order_id', $orderId)->sum('amount_cents');
}
}
// app/Modules/Reporting/OrderSummary.php: the smallest data the formatters need (data coupling).
namespace App\Modules\Reporting;
final readonly class OrderSummary
{
public function __construct(
public int $orderId,
public int $paidCents,
public string $currency,
) {}
}
// app/Modules/Reporting/Formatters.php: two named functions instead of a boolean flag.
namespace App\Modules\Reporting;
final class CsvOrderFormatter
{
public function format(OrderSummary $s): string
{
return "{$s->orderId},{$s->paidCents},{$s->currency}\n";
}
}
final class TextOrderFormatter
{
public function format(OrderSummary $s): string
{
return sprintf('Order %d: %.2f %s', $s->orderId, $s->paidCents / 100, $s->currency);
}
}
// app/Http/Controllers/OrderReportController.php: depends on a contract and a value.
namespace App\Http\Controllers;
use App\Models\Order;
use App\Modules\Billing\Contracts\PaymentTotals;
use App\Modules\Reporting\CsvOrderFormatter;
use App\Modules\Reporting\OrderSummary;
class OrderReportController extends Controller
{
public function __construct(private PaymentTotals $payments, private string $currency) {}
public function csv(Order $order, CsvOrderFormatter $formatter)
{
$summary = new OrderSummary($order->id, $this->payments->paidCents($order->id), $this->currency);
return response($formatter->format($summary))->header('Content-Type', 'text/csv');
}
}
// app/Modules/Billing/BillingServiceProvider.php: the only place that knows the implementation.
namespace App\Modules\Billing;
use App\Http\Controllers\OrderReportController;
use App\Modules\Billing\Contracts\PaymentTotals;
use App\Modules\Billing\Internal\EloquentPaymentTotals;
use Illuminate\Support\ServiceProvider;
final class BillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(PaymentTotals::class, EloquentPaymentTotals::class);
// Config is read once, at the edge, and passed in as a plain value.
$this->app->when(OrderReportController::class)
->needs('$currency')
->giveConfig('shop.currency');
}
}ماژول عمیق: CurrencyConverter
<?php
// app/Services/RatesClient.php: a shallow wrapper. One method per HTTP call,
// so every caller still has to know caching, retries, the URL and the JSON shape.
namespace App\Services;
use Illuminate\Support\Facades\Http;
class RatesClient
{
public function fetch(string $base): array
{
return Http::get("https://rates.example.com/latest?base={$base}")->json();
}
}
// app/Http/Controllers/CheckoutController.php: one of many callers repeating the same knowledge.
namespace App\Http\Controllers;
use App\Services\RatesClient;
use Illuminate\Support\Facades\Cache;
class CheckoutController extends Controller
{
public function total(RatesClient $client, int $cents, string $to)
{
$rates = Cache::remember('rates:EUR', 3600, fn () => $client->fetch('EUR'));
$rate = $rates['rates'][$to] ?? throw new \RuntimeException("no rate for {$to}");
return ['cents' => (int) round($cents * $rate), 'currency' => $to];
}
}<?php
// app/Modules/Currency/CurrencyConverter.php: a deep module. One method in, everything else hidden:
// the provider URL, the JSON shape, caching, retries, timeouts and rounding.
namespace App\Modules\Currency;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
final readonly class Money
{
public function __construct(public int $cents, public string $currency) {}
}
final class UnknownCurrency extends \DomainException {}
final class CurrencyConverter
{
private const BASE = 'EUR';
private const TTL_SECONDS = 3600;
public function convert(Money $amount, string $to): Money
{
if ($amount->currency === $to) {
return $amount;
}
$rates = $this->rates();
$from = $rates[$amount->currency] ?? throw new UnknownCurrency($amount->currency);
$target = $rates[$to] ?? throw new UnknownCurrency($to);
return new Money((int) round($amount->cents / $from * $target), $to);
}
/** @return array<string, float> rates relative to BASE, including BASE itself */
private function rates(): array
{
return Cache::remember('currency:rates:'.self::BASE, self::TTL_SECONDS, function (): array {
$json = Http::retry(3, 200)
->timeout(5)
->get('https://rates.example.com/latest', ['base' => self::BASE])
->throw()
->json();
return [self::BASE => 1.0] + $json['rates'];
});
}
}
// app/Http/Controllers/CheckoutController.php: the caller knows one method and one value type.
namespace App\Http\Controllers;
use App\Modules\Currency\CurrencyConverter;
use App\Modules\Currency\Money;
class CheckoutController extends Controller
{
public function total(CurrencyConverter $converter, int $cents, string $to)
{
$total = $converter->convert(new Money($cents, 'EUR'), $to);
return ['cents' => $total->cents, 'currency' => $total->currency];
}
}convert(Money, string): Money آدرس ارائهدهنده، شکل JSON، Cache::remember، Http::retry، timeout و حساب نرخ متقاطع را پنهان میکند. عوض کردن ارائهدهنده یا store مربوط به cache فقط یک فایل را ویرایش میکند.
Events: حذف وابستگی زمانی داخل اپ
مستندات events در Laravel: "Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other."
<?php
// app/Actions/PlaceOrder.php: the use case knows every reaction to an order.
// Adding "notify the warehouse" means editing, retesting and redeploying this class.
namespace App\Actions;
use App\Mail\OrderConfirmation;
use App\Models\Order;
use App\Services\Analytics;
use App\Services\SlackNotifier;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class PlaceOrder
{
public function __construct(private SlackNotifier $slack, private Analytics $analytics) {}
public function handle(array $data): Order
{
$order = DB::transaction(fn () => Order::create($data));
Mail::to($order->email)->send(new OrderConfirmation($order)); // slow SMTP in the request
$this->slack->post("#sales", "New order {$order->id}"); // Slack down = checkout down
$this->analytics->track('order_placed', ['id' => $order->id]);
return $order;
}
}<?php
// app/Events/OrderPlaced.php: a fact, published after the transaction commits.
namespace App\Events;
use App\Models\Order;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(public Order $order) {}
}
// app/Actions/PlaceOrder.php: the use case knows only its own job.
namespace App\Actions;
use App\Events\OrderPlaced;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
class PlaceOrder
{
public function handle(array $data): Order
{
return DB::transaction(function () use ($data) {
$order = Order::create($data);
OrderPlaced::dispatch($order);
return $order;
});
}
}
// app/Listeners/SendOrderConfirmation.php: queued, retried, discovered automatically
// because it lives in app/Listeners and type-hints the event in handle().
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Mail\OrderConfirmation;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
class SendOrderConfirmation implements ShouldQueue
{
public function handle(OrderPlaced $event): void
{
Mail::to($event->order->email)->send(new OrderConfirmation($event->order));
}
}
// app/Listeners/PostOrderToSlack.php: a Slack outage now delays a message, not a checkout.
namespace App\Listeners;
use App\Events\OrderPlaced;
use App\Services\SlackNotifier;
use Illuminate\Contracts\Queue\ShouldQueue;
class PostOrderToSlack implements ShouldQueue
{
public function __construct(private SlackNotifier $slack) {}
public function handle(OrderPlaced $event): void
{
$this->slack->post('#sales', "New order {$event->order->id}");
}
}ShouldDispatchAfterCommit باعث میشود event فقط بعد از commit تراکنش فرستاده شود؛ listenerهای ShouldQueue روی worker اجرا میشوند، پس از کار افتادن Slack دیگر checkout را از کار نمیاندازد. listenerهای داخل app/Listeners با متد handle تایپدار، توسط event discovery ثبت میشوند.
جداسازی دغدغهها: middleware، قاعده، adapter
<?php
// app/Http/Middleware/EnsureApiToken.php: authentication is a cross-cutting concern.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureApiToken
{
public function handle(Request $request, Closure $next): Response
{
if ($request->bearerToken() !== config('services.pricing.token')) {
abort(401);
}
return $next($request);
}
}
// app/Modules/Pricing/QuantityDiscount.php: the business rule. No HTTP, no logging.
namespace App\Modules\Pricing;
final class QuantityDiscount
{
public function totalCents(int $qty, int $unitCents = 499): int
{
$total = $qty * $unitCents;
return $qty >= 10 ? intdiv($total * 90, 100) : $total;
}
}
// app/Http/Controllers/PriceController.php: the HTTP adapter.
namespace App\Http\Controllers;
use App\Modules\Pricing\QuantityDiscount;
use Illuminate\Http\Request;
class PriceController extends Controller
{
public function __invoke(Request $request, QuantityDiscount $pricing)
{
$qty = max(1, $request->integer('qty', 1));
return ['total_cents' => $pricing->totalCents($qty)];
}
}
// routes/api.php: concerns meet only where they are composed.
// Route::get('/price', PriceController::class)->middleware(EnsureApiToken::class);نگاه Laravel
| قابلیت Laravel | نقش در کیفیت طراحی |
|---|---|
Contracts (Illuminate\Contracts\*) و interfaceهای خودتان | interface بهعنوان قرارداد؛ به آن وابسته شوید، پیادهسازی را bind کنید |
| Service provider | composition root هر ماژول؛ تنها جایی که پیادهسازیها را میشناسد |
Contextual binding (when()->needs()->give()، giveConfig) | common coupling به config() داخل منطق را حذف میکند |
| Events + listener صفدار | وابستگی زمانی و control coupling بین واکنشها را حذف میکند |
| Middleware | دغدغههای همهجاگیر (auth، لاگ، throttling) |
| Form Request، Policy | اعتبارسنجی و مجوزدهی بهعنوان دغدغههای جدا |
پوشههای ماژول (app/Modules/*) یا packageهای محلی Composer | پنهانسازی اطلاعات در سطح ماژول |
deptrac / Pest arch() | تحمیل مرز ماژول در CI |
| Facades | راحتاند، ولی فراخوانی static یک وابستگی پنهان است: در کد دامنه contract تزریق کنید؛ مستندات Laravel این دو را در «Contracts vs. Facades» مقایسه میکند |
حل مسئلههای کلاسیک
| مسئله | راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
state سراسری (var DB، config() در منطق) | وابستگی صریح | پارامتر constructor؛ خواندن config در لبه | تستپذیر، قابل دیدن | constructorهای بلندتر |
| آرگومان flag | شکستن تابع | یک تابع اسمدار برای هر رفتار | ترکیب نامعتبر وجود ندارد | تابعهای بیشتر |
| پارامتر کل رکورد | typeهای باریک | slice، ID، DTO، value object بدهید | تغییر فیلدهای بیربط موج نمیزند | کد نگاشت |
| wrapper کمعمق / عبوری | ادغام و عمیق کردن | کد صدازننده را به داخل ماژول بکشید | interface کل کوچکتر | ماژول بزرگتر |
utils / helpers | منحل کردن | هر تابع به مصرفکنندهاش یا package اسمدار | functional cohesion | packageهای بیشتر |
| دست بردن در جدول ماژول دیگر | قرارداد منتشرشده | interface، view یا API متعلق به ماژول | مالک میتواند schema را عوض کند | یک لایهٔ واسط بیشتر |
| عدد جادویی و آرگومان ترتیبی | typeهای اسمدار | enum، ثابت، struct گزینهها | کامپایلر کمک میکند | کمی کد بیشتر |
| ترتیب فراخوانی اجباری | constructor، typeهای حالت | شیء آماده برگردانید؛ typestate | استفادهٔ غلط ناممکن | راهاندازی کمانعطافتر |
| اثر جانبی همگام | Events | واقعیت را dispatch کنید؛ listener صفدار | جداسازی شکست | سازگاری نهایی |
| قراردادهای ناهمگون | یکپارچگی مفهومی | راهنمای سبک، ADR، قواعد lint، middleware مشترک | سیستم قابل پیشبینی | مالک لازم دارد |
جدول مشترک بین ماژولها
وقتی ماژول دیگری باید دادهٔ شما را بخواند و هنوز نمیتوانید API اضافه کنید، یک view را بهعنوان قرارداد منتشر کنید و جدول را خصوصی نگه دارید. view همان interface است؛ جدول همان تصمیم پنهان.
-- PostgreSQL: billing owns its tables; reporting may read only the published view.
CREATE SCHEMA billing;
CREATE TABLE billing.payments (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL,
amount_cents BIGINT NOT NULL,
provider TEXT NOT NULL,
raw_response JSONB
);
CREATE VIEW billing.order_paid_v1 AS
SELECT order_id, SUM(amount_cents) AS paid_cents
FROM billing.payments GROUP BY order_id;
CREATE ROLE reporting_app LOGIN;
GRANT USAGE ON SCHEMA billing TO reporting_app;
GRANT SELECT ON billing.order_paid_v1 TO reporting_app; -- not on billing.payments
-- billing can now split payments into two tables; it only has to keep order_paid_v1 stable.فراخوانیهای پرحرف بین ماژولها
مقالهٔ Microservices فاولر: "A naive conversion from in-memory method calls to RPC leads to chatty communications which don't perform well. Instead you need to replace the fine-grained communication with a coarser-grained approach." به جای getPrice(sku) در حلقه، quote(cart) بگذارید؛ به جای سه فراخوانی (موجودی، قیمت، مشتری)، یک فراخوانی به مالکی که داده را دارد، یا read modelهای محلی که با event تغذیه میشوند.
وابستگی زمانی به وابستگیهای کند یا ناپایدار
اگر صدازننده برای پاسخ دادن به جواب نیاز ندارد، event منتشر کنید (درونفرایندی: events لاراول با listener صفدار؛ بین سرویسها: outbox + broker). اگر جواب را لازم دارد، timeout، circuit breaker و مسیر جایگزین اضافه کنید و بپذیرید که وابستگی میماند.
انتخاب
| وضعیت | توصیه | تکنیک تکمیلی | دلیل |
|---|---|---|---|
| تابعی boolean دارد که رفتار را انتخاب میکند | به دو تابع اسمدار بشکنید | گامهای مشترک private بمانند | حذف control coupling |
| ماژولی ذخیرهگاه یا قفلش را بیرون داده | عمیقش کنید | پشت APIی به سبک Get/Set پنهان کنید | پنهانسازی اطلاعات |
| دو ماژول یک جدول را شریکاند | یک مالک + view یا API | schema برای هر ماژول، grant | حذف common coupling |
| classی دیگری را میپیچد و همهٔ فراخوانیها را جلو میفرستد | inline کنید | مگر انتزاع متفاوتی اضافه کند | عبوری کمعمق |
package utils بزرگ میشود | منحلش کنید | Move Function | coincidental cohesion |
| interface فقط برای mock، تعریفشده در سمت پیادهساز | به مصرفکننده ببرید، کوچکش کنید | قاعدهٔ Go Code Review Comments | مصرفکننده مالک قراردادش است |
| اثر جانبیای که میتواند مستقل شکست بخورد | event + listener صفدار | ShouldDispatchAfterCommit | حذف وابستگی زمانی |
| زنجیرهٔ فراخوانی همگام روی ۳+ سرویس | API درشتدانهتر یا async | read model، outbox | دسترسپذیریها ضرب میشوند |
| connascence قوی داخل یک تابع | رهایش کنید | محلی نگهش دارید | محلی بودن ارزانش میکند |
| connascence قوی بین سرویسها | با قرارداد name/type عوض کنید | schema registry، event نسخهدار | درجه و فاصله بالاست |
| تیمهای زیاد، APIهای ناهمگون | مالک یکپارچگی مفهومی | راهنمای سبک API، ADR | Brooks: ذهنهای کم برای معماری |
| حلقهٔ داغ، حساس به کارایی | کمی coupling را بپذیرید | اول اندازه بگیرید | غیرمستقیم بودن هزینه دارد |
در معماری: از یک فرایند تا سیستم توزیعشده
همین پنج ویژگی در هر مقیاسی صدق میکنند؛ آنچه عوض میشود قیمت اشتباه است. داخل یک فرایند، وابستگی بد یک refactoring هزینه دارد. بین سرویسها، یک deploy هماهنگ، یک زنجیرهٔ قطعی یا یک مهاجرت داده.
تصویر سه coupling رایج در سطح سرویس را نشان میدهد: در چپ دیتابیس مشترک (shared database، یعنی common coupling که تغییر schema را به هماهنگی دو تیم گره میزند)؛ در وسط زنجیرهٔ همگام پرحرف (chatty) که در آن سرویس سفارش برای هر خط موجودی، قیمت و مشتری را صدا میزند و دسترسپذیریها ضرب و تأخیرها جمع میشوند (temporal coupling)؛ و در راست درمان: هر سرویس مالک دادهٔ خودش است و OrderPlaced را از طریق outbox به broker میفرستد، billing و shipping به شکل async مصرف میکنند و فقط data coupling روی یک قرارداد نسخهدار باقی میماند.
Monolith (یکپارچه): یک فرایند، یک دیتابیس
چطور ظاهر میشود: packageها و classها. ساختن coupling ارزان است (هر class میتواند هر class دیگری را صدا بزند) و درست کردنش هم ارزان (کامپایلر و IDE همهٔ صدازنندهها را پیدا میکنند).
سادهترین استفادهٔ درست: جایگاههای فریمورک برای دغدغهها (middleware، form request، action، listener)، بدون متغیر سراسری در کد دامنه، ماژول عمیق برای بخشهای سخت (پول، مالیات، نرخ، جستوجو).
مثال (ساده): یک وبلاگ: PostController ← action PublishPost ← event PostPublished ← listener صفدار NotifySubscribers. controller نمیداند ایمیل وجود دارد.
مثال (پیچیده): فروشگاهی که OrderServiceش قیمتگذاری، موجودی، PDF فاکتور، Slack و analytics را پشت سر هم صدا میزد. به یک ماژول عمیق Pricing، یک event OrderPlaced با listenerهای صفدار و یک CurrencyConverter که ارائهدهندهٔ نرخ را پنهان میکند شکسته شد.
Modular monolith و چند دیتابیس
چطور ظاهر میشود: هر ماژول (یک تیم، یک توانایی کسبوکار) قرارداد عمومی و درونیات خصوصی دارد، از جمله جدولهای خصوصی. این پنهانسازی اطلاعات با ضمانت اجراست.
قواعد: ماژولها از طریق قرارداد یا event درونفرایندی حرف میزنند؛ هیچ ماژولی جدول دیگری را نمیخواند (view یا API، مثل SQL بالا)؛ مرزها با deptrac یا go-arch-lint در CI تست میشوند. Modular Monolith را ببینید.
مثال: app/Modules/{Catalog,Ordering,Billing} که هر کدام service provider، پوشهٔ Contracts و پوشهٔ Internal دارند؛ deptrac وابستگی Ordering → Billing\Internal را ممنوع میکند.
میکروسرویسها: coupling با یک شبکه در وسط
آنچه میماند: همهٔ ویژگیها. آنچه عوض میشود: هر شکل coupling حالا هزینهٔ زمان اجرا دارد.
| coupling درونفرایندی | معادل در سطح سرویس | هزینه | درمان |
|---|---|---|---|
| Content | سرویس دیتابیس سرویس دیگر را میخواند | تغییر schema تیمی را که نمیشناسید میشکند | دیتابیس برای هر سرویس؛ مالکیت داده |
| Common | دیتابیس مشترک یا کلیدهای cache مشترک | microservices.io: "Development time coupling" و "Runtime coupling" | یک مالک برای هر جدول و پیشوند کلید |
| External | JSON بینسخه که هر دو طرف دستی parse میکنند | شکست بیصدا | schema registry، contract test |
| Control | flagهایی مثل ?mode=fast روی API | صدازننده منطق طرف مقابل را کد میکند | endpointهای جدا |
| Stamp | برگرداندن کل مشتری برای یک فیلد | پهنای باند، هر تغییر موج میزند | endpointهای هدفمند، انتخاب فیلد در GraphQL |
| Temporal | زنجیرهٔ فراخوانی همگام | دسترسپذیری ضرب، تأخیر جمع میشود | event async، outbox، read model محلی |
| فراخوانی ریزدانهٔ پرحرف | N فراخوانی برای هر درخواست | تأخیر × N | API درشتدانهتر |
| Change coupling | سرویسهایی که همیشه با هم deploy میشوند | distributed monolith | کشیدن دوبارهٔ مرزها (Service Boundaries) |
Request: place order with 5 lines
1 chatty: orders -> price x5, stock x5, customer x1 11 calls, all must be up, p99 adds up
2 coarse: orders -> pricing.quote(cart), stock.reserve(cart) 2 calls
3 async: orders writes order + outbox(OrderPlaced) in one tx, returns 202
4 billing and shipping consume OrderPlaced when they are ready
5 only shared thing: the OrderPlaced v1 schema (data coupling on a contract)مثال: checkout رویداد OrderPlaced را از طریق outbox منتشر میکند؛ billing و shipping مشترکش میشوند. افزودن سرویس وفاداری یک مشترک تازه است، نه تغییری در checkout. Event-Driven Architecture و Service Communication را ببینید.
دادهٔ توزیعشده: replica، cache و schema مشترک
کجا میشکند: connascence of value و identity توزیعشده میشوند. قیمت cacheشده و قیمت دیتابیس باید یکی باشند؛ دو سرویس که هر کدام نسخهٔ خودشان از آدرس مشتری را نگه میدارند باید همگرا شوند. تأخیر replica «خواندن بعد از نوشتن» را به connascence زمانی تبدیل میکند.
پادزهرها: یک منبع حقیقت برای هر واقعیت؛ نسخهها مشتقاند و همینطور برچسب میخورند (read modelهایی که با event یا CDC تغذیه میشوند)؛ TTL و نسخه روی مقادیر cacheشده؛ مصرفکنندهٔ idempotent تا تحویل دوباره مشکل identity نسازد.
مسیر مقیاس: ۱×، ۱۰×، ۱۰۰×
| مقیاس | ساختار | عمل کیفیت طراحی |
|---|---|---|
| 1× (یک تیم) | Monolith، پوشه بر اساس قابلیت | بدون متغیر سراسری در منطق، ماژول عمیق برای بخشهای سخت، gocyclo/phpmetrics در CI |
| 10× (چند تیم) | Modular monolith | قرارداد برای هر ماژول، schema برای هر ماژول، deptrac/go-arch-lint، راهنمای سبک API |
| 100× (تیمهای زیاد) | سرویس برای هر توانایی | دیتابیس برای هر سرویس، قرارداد event نسخهدار، async بهطور پیشفرض، «paved road» پلتفرم برای دغدغههای همهجاگیر، مرجع طراحی برای یکپارچگی مفهومی |
آزمایشگاه: اندازه بگیر، refactor کن، دوباره اندازه بگیر
همه چیز بدون اینترنت از ماژول snippet اجرا میشود.
راهاندازی.
cd docs/snippets/design/design-quality-principles/go
gofmt -l . && go vet ./... # no output, then nothing: cleanگام ۱: پیچیدگی و fan-out مثال coupling. دستور metrics قواعد gocyclo را با go/ast اجرا میکند و importهای هر package را فهرست میکند.
// Command metrics prints, for every Go package under a directory, the cyclomatic
// complexity of each function (gocyclo rules) and the package's imports (fan-out).
//
// go run ./metrics ./coupling
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// complexity follows gocyclo: 1 + if, for, range, non-default case/comm clause, && and ||.
func complexity(fn *ast.FuncDecl) int {
c := 1
ast.Inspect(fn, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt:
c++
case *ast.CaseClause:
if x.List != nil {
c++
}
case *ast.CommClause:
if x.Comm != nil {
c++
}
case *ast.BinaryExpr:
if x.Op == token.LAND || x.Op == token.LOR {
c++
}
}
return true
})
return c
}
func main() {
root := "."
if len(os.Args) > 1 {
root = os.Args[1]
}
imports := map[string]map[string]bool{}
fset := token.NewFileSet()
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
f, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return err
}
dir := filepath.Dir(path)
if imports[dir] == nil {
imports[dir] = map[string]bool{}
}
for _, imp := range f.Imports {
imports[dir][strings.Trim(imp.Path.Value, `"`)] = true
}
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
fmt.Printf("%-28s %-14s cyclo=%d\n", dir, fn.Name.Name, complexity(fn))
}
}
return nil
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
dirs := make([]string, 0, len(imports))
for d := range imports {
dirs = append(dirs, d)
}
sort.Strings(dirs)
for _, d := range dirs {
list := make([]string, 0, len(imports[d]))
for p := range imports[d] {
list = append(list, p)
}
sort.Strings(list)
fmt.Printf("%-28s fan-out=%d %s\n", d, len(list), strings.Join(list, " "))
}
}go run ./metrics ./coupling
# coupling/before Render cyclo=5
# coupling/before Total cyclo=2
# coupling/after Total cyclo=2
# coupling/after CSV cyclo=1
# coupling/after Text cyclo=1Render به خاطر دو flag و یک && امتیاز 5 میگیرد؛ دو قالببند اسمدار هر کدام 1.
گام ۲: جداسازی دغدغهها.
go run ./metrics ./soc
# soc/before Price cyclo=4
# soc/after TotalCents cyclo=2 (the rule: unit-testable without HTTP)
# soc/after Price cyclo=3 (the adapter)
# soc/after RequireToken cyclo=2 (cross-cutting, reused by every route)مجموع زیاد پایین نیامد؛ آنچه عوض شد این است که هر تابع حالا یک دلیل تغییر دارد و قاعدهٔ تخفیف هیچ net/httpی در مسیرش ندارد.
گام ۳: وابستگی ورودی و خروجی.
go list -f '{{.ImportPath}}: {{join .Imports " "}}' ./consumeriface/...
# .../consumeriface/before: .../consumeriface/stripepay context os
# .../consumeriface/cmd: .../consumeriface/orders .../consumeriface/stripepay context fmt log
# .../consumeriface/orders: context errors
# .../consumeriface/stripepay: context fmt net/http timeI = Ce / (Ca + Ce) را فقط با شمردن packageهای پروژه حساب کنید: orders (بعد) Ce = 0 دارد، پس I = 0؛ cmd با Ce = 2 و Ca = 0 مقدار I = 1 دارد؛ orders (قبل) Ce = 1 (stripepay) و I = 1. طراحی بعد همهٔ وابستگیها را به سمت هستهٔ پایدار میبرد.
گام ۴: عمداً یک مرز را بشکنید. import _ "academy/design-quality-principles/consumeriface/stripepay" را به consumeriface/orders/orders.go اضافه کنید. انتظار: هنوز کامپایل میشود (Go قاعدهٔ لایه ندارد) ولی go list حالا Ce = 1 برای orders نشان میدهد. به همین دلیل go-arch-lint اضافه میکنید؛ با config بخش قواعد معماری و ممنوع بودن وابستگی orders به adapterها، go-arch-lint check شکست میخورد. import را حذف کنید.
گام ۵: connascence. در connascence/before دو boolean را در یک فراخوانی New جابهجا کنید (New("a", "b", false, true, 2)). انتظار: کامپایل میشود، کاربر اشتباه ساخته میشود. همین را با فیلدهای اسمدار after.User{...} امتحان کنید: ترتیب دیگر مهم نیست، و Role: 2 باید Role: Admin نوشته شود تا خوانا باشد.
گام ۶ (Laravel). در یک اپ Laravel 13، classهای CouplingAfter.php را در مسیرهایشان و deptrac.yaml را در ریشه بگذارید، بعد DB::table('billing_payments') را به controller اضافه کنید. انتظار: vendor/bin/deptrac analyse رد نمیشود (facade در هیچ لایهای نیست) ولی قاعدهٔ Pest arch() به شکل expect('App\Http')->not->toUse('Illuminate\Support\Facades\DB') شکست میخورد. بعد phpmetrics --report-html=report ./app را اجرا کنید و lcom و instability را برای controller قدیم و جدید مقایسه کنید.
| اندازهگیری | قبل | بعد |
|---|---|---|
| بیشترین cyclomatic در قالببندی گزارش | 5 (Render) | 1 (CSV، Text) |
متغیر سراسری در report | 2 (DB، Currency) | 0 |
packageهای پروژه که orders import میکند | 1 (stripepay) | 0 |
Instability در orders | 1.0 | 0.0 |
| متدهای cache که صدازننده باید بداند | ۴ نام + پروتکل | 2 (Get، Set) |
| تابعهایی که با تغییر تخفیف عوض میشوند | Price (که auth و لاگ هم دارد) | فقط TotalCents |
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| coupling پایین یعنی صفر وابستگی | ماژولها باید حرف بزنند؛ هدف وابستگی کم، ضعیف و یکطرفه است (فاولر ۲۰۰۱) |
| class کوچک همیشه بهتر است | classهای کمعمق زیاد اندازهٔ کل interface را بالا میبرند («classitis»، Ousterhout) |
| فیلد private یعنی پنهانسازی اطلاعات | getter/setter برای همه چیز طراحی را نشت میدهد؛ پنهانسازی دربارهٔ تصمیمهاست |
| interface بهتنهایی وابستگی را میبُرد | flag، رکورد کامل و قاعدهٔ ترتیب فراخوانی از روی interface هم وابسته میکنند |
| interface جایش کنار پیادهسازی است | در Go جایش کنار مصرفکننده است (Go Code Review Comments) |
| ناپایداری بد است | adapterها باید ناپایدار باشند؛ کد پایدار نباید به آنها وابسته شود |
| cyclomatic complexity خوانایی را میسنجد | مسیرها را برای تست میشمارد؛ تودرتویی و نامگذاری برای خواندن مهمترند |
| LCOM میگوید class را چطور بشکنید | خوشههای اشتراک فیلد را پیدا میکند، نه مسئولیتها را |
| جداسازی دغدغهها یعنی controller/service/repository | لایهها یک تقسیم فنیاند؛ دغدغههای کسبوکاری هم باید جدا شوند |
| یکپارچگی مفهومی یعنی یک نفر همهٔ کد را بنویسد | یک ذهن (یا چند ذهن همصدا) مالک معماری است؛ دستهای زیادی پیاده میکنند |
| میکروسرویس خودبهخود coupling پایین میدهد | دیتابیس مشترک و زنجیرهٔ همگام distributed monolith میسازند |
| پیامرسانی async همهٔ coupling را حذف میکند | وابستگی زمانی را حذف میکند؛ schema پیام هنوز قرارداد است |
| هر تکراری باید حذف شود | تکرار coupling میسازد، ولی ادغام کد متعلق به actorهای مختلف آنها را بیشتر به هم گره میزند (SRP) |
چکیده
| موضوع | به خاطر بسپارید |
|---|---|
| پیچیدگی | نشانهها: change amplification، cognitive load، unknown unknowns. علتها: وابستگی، ابهام |
| ذاتی در برابر عارضی | ذاتی را مهار کنید، عارضی را حذف (Brooks ۱۹۸۶) |
| نردبان coupling | Content، common، external، control، stamp، data (تنگترین به شلترین) |
| شکلهای دیگر coupling | Temporal (ترتیب/دسترسپذیری)، change coupling (git)، pathological = content |
| معیارهای package | Ca ورودی، Ce خروجی، I = Ce / (Ca + Ce)؛ به سمت I کمتر وابسته شوید |
| نردبان cohesion | Coincidental، logical، temporal، procedural، communicational، sequential، functional |
| پنهانسازی اطلاعات | تصمیمهای تغییرپذیر را پنهان کنید (Parnas ۱۹۷۲)؛ کپسولهسازی سازوکار است |
| Interface | بخش رسمی + غیررسمی؛ Go: در سمت مصرفکننده اعلام کنید، type concrete برگردانید |
| ماژول عمیق | interface کوچک، پنهان زیاد؛ پرچم قرمز: متد عبوری، classitis |
| جداسازی دغدغهها | قاعده، انتقال، ذخیرهسازی جدا؛ همهجاگیرها در middleware/decorator/event |
| یکپارچگی مفهومی | یک مجموعه ایده؛ نقش معمار، ADR، راهنمای سبک؛ قابلیت ناجور را کنار بگذارید |
| Connascence | strength، degree، locality؛ name و type ضعیفاند، meaning/position/timing قوی |
| معیارها | سقف McCabe عدد 10؛ gocyclo، phpmetrics (ccn، lcom، instability) |
| قواعد در CI | go-arch-lint، deptrac، Pest arch() |
| سرویسها | بدون DB مشترک، API درشتدانه، async برای اثر جانبی، قرارداد نسخهدار |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — سه نشانهٔ پیچیدگی از نظر Ousterhout چیست و دو علتش کدام است؟ مهم
پاسخ
پاسخ: Change amplification، cognitive load، unknown unknowns؛ ناشی از وابستگی و ابهام. پیچیدگی را ببینید.
۲ — اینها را از تنگترین به شلترین مرتب کنید: stamp، content، data، control، common، external. تکمیلی
پاسخ
پاسخ: Content، common، external، control، stamp، data. Coupling را ببینید.
۳ — func Render(o *Order, asCSV bool) از کدام دو نوع coupling استفاده میکند و چطور درستش میکنید؟ مهم
پاسخ
پاسخ: Stamp coupling (کل *Order) و control coupling (asCSV). یک مقدار کوچک Summary بدهید و به CSV(s) و Text(s) بشکنید. Coupling در Go را ببینید.
۴ — تابع boot() دیتابیس را باز میکند، cache را گرم میکند و به Slack پیام میدهد. کدام سطح cohesion است؟ مهم
پاسخ
پاسخ: Temporal cohesion: اجزا فقط چون همزمان اجرا میشوند کنار هماند. Cohesion را ببینید.
۵ — classی فقط فیلد private دارد و برای هر کدام getter و setter عمومی. پنهانسازی اطلاعات دارد؟ حیاتی
پاسخ
پاسخ: کپسولهسازی بله، پنهانسازی اطلاعات نه: چیدمان فیلدها همان interface است. پنهانسازی اطلاعات را ببینید.
۶ — در Go، interface Payments که orders استفاده میکند کجا باید تعریف شود و stripepay.New چه برگرداند؟ حیاتی
پاسخ
پاسخ: در orders، یعنی مصرفکننده؛ stripepay.New یک *Client concrete برمیگرداند. Interface بهعنوان قرارداد را ببینید.
۷ — متد عبوری (pass-through) چیست و چرا پرچم قرمز است؟ مهم
پاسخ
پاسخ: متدی که با همان امضا و بدون انتزاع تازه به متد دیگری جلو میفرستد؛ interface اضافه میکند بدون کارکرد، و ماژول را کمعمق میکند. عمیق و کمعمق را ببینید.
۸ — package A مقدار Ca = 6 و Ce = 2 دارد. ناپایداریاش چقدر است و آیا میتواند به package B با I = 0.8 وابسته شود؟ مهم
پاسخ
پاسخ: I = 2 / (6 + 2) = 0.25. وابستگی به B (0.8) قاعدهٔ "depend upon packages whose I metric is lower than yours" را نقض میکند. Instability را ببینید.
۹ — role == 2، New(a, b, true, false) و Init() before Send() را بر اساس شکل connascence دستهبندی کنید. تکمیلی
پاسخ
پاسخ: Meaning (ایستا)، position (ایستا)، execution order (پویا). درمان: ثابت اسمدار، فیلد اسمدار، constructor. Connascence را ببینید.
۱۰ — دو سرویس یک جدول customers را میخوانند و مینویسند. اسم این coupling و دو هزینهای که microservices.io میشمارد چیست؟ حیاتی
پاسخ
پاسخ: Common coupling در سطح سرویس؛ development-time coupling (هماهنگی تغییر schema) و runtime coupling (تداخل با هم). میکروسرویسها را ببینید.
۱۱ — یک تیم چطور یکپارچگی مفهومی را از دست میدهد؟ دو پادزهر نام ببرید. مهم
پاسخ
پاسخ: نویسندگان زیادی که قابلیتها را با قراردادهای خودشان اضافه میکنند و هیچ مالکی برای مفاهیم نیست. پادزهر: نقش معمار/مرجع طراحی، ADR، راهنمای سبک API که با middleware و lint تحمیل شود. یکپارچگی مفهومی را ببینید.
۱۲ — آیا جایگزینی یک فراخوانی همگام با event همهٔ coupling را حذف میکند؟ حیاتی
پاسخ
پاسخ: نه. وابستگی زمانی را حذف میکند؛ schema رویداد یک قرارداد data coupling باقی میماند که نسخهبندی لازم دارد. Temporal coupling را ببینید.
واژهنامه
| اصطلاح | معنا |
|---|---|
| پیچیدگی (Complexity) | هر چیزی در ساختار سیستم که فهم و تغییرش را سخت میکند (Ousterhout) |
| تقویت تغییر (Change amplification) | یک تغییر ساده ویرایش در جاهای زیاد لازم دارد |
| بار شناختی (Cognitive load) | آنچه برنامهنویس برای یک تغییر باید بداند |
| ناشناختههای ناشناخته (Unknown unknowns) | دانش لازمی که جایی که تغییر را میدهید دیده نمیشود |
| ابهام (Obscurity) | اطلاعات مهم آشکار نیست |
| پیچیدگی ذاتی (Essential complexity) | پیچیدگی ذاتی مسئله (Brooks ۱۹۸۶) |
| پیچیدگی عارضی (Accidental complexity) | پیچیدگیای که ابزارها و انتخابهای ما اضافه کردهاند |
| وابستگی (Coupling) | قدرت پیوندی که یک اتصال بین ماژولها میسازد |
| Content coupling | استفاده یا تغییر درونیات ماژول دیگر؛ Page-Jones آن را pathological مینامد |
| Pathological coupling | نام Page-Jones برای content coupling، تنگترین سطح |
| Common coupling | اشتراک دادهٔ سراسری تغییرپذیر |
| External coupling | اشتراک قالب، پروتکل یا دستگاه تحمیلی از بیرون |
| Control coupling | پاس دادن flagی که رفتار طرف مقابل را انتخاب میکند |
| Stamp coupling | پاس دادن کل ساختار وقتی فقط بخشی لازم است |
| Data coupling | پاس دادن فقط دادهٔ پایهای لازم |
| وابستگی زمانی (Temporal coupling) | وابستگی به ترتیب یا همزمانی اجرا یا دسترسپذیری |
| Change (logical) coupling | فایلهایی که در تاریخچهٔ نسخه با هم تغییر میکنند |
| وابستگی ورودی (Afferent coupling، Ca) | تعداد classهای بیرونی که به یک package وابستهاند |
| وابستگی خروجی (Efferent coupling، Ce) | تعداد classهای بیرونی که package به آنها وابسته است |
| ناپایداری (Instability، I) | Ce / (Ca + Ce)، از 0 پایدار تا 1 ناپایدار |
| Fan-in / fan-out | صدازنندههای یک واحد / واحدهایی که صدا میزند |
| انسجام (Cohesion، binding) | اجزای یک ماژول چقدر قوی به هم تعلق دارند |
| انسجام coincidental / logical / temporal / procedural / communicational / sequential / functional | هفت سطح cohesion، از ضعیفترین به قویترین |
| پنهانسازی اطلاعات (Information hiding) | پنهان کردن تصمیمهای تغییرپذیر پشت interface (Parnas ۱۹۷۲) |
| کپسولهسازی (Encapsulation) | سازوکارهای زبان که دسترسی به درونیات را محدود میکنند |
| نشت اطلاعات (Information leakage) | تصمیم طراحیای که بیش از یک ماژول از آن خبر دارد |
| تجزیهٔ زمانی (Temporal decomposition) | شکستن کد بر اساس ترتیب اجرا؛ علت رایج نشت |
| Interface | هر چه صدازننده باید بداند: امضای رسمی بهاضافهٔ رفتار غیررسمی |
| قرارداد (Contract) | تضمینها و تعهدهای یک interface، شامل خطا و ترتیب |
| ماژول عمیق (Deep module) | interface کوچک، کارکرد پنهان زیاد |
| ماژول کمعمق (Shallow module) | interfaceی تقریباً به پیچیدگی پیادهسازیاش |
| متد عبوری (Pass-through method) | متدی که بدون افزودن انتزاع فراخوانی را جلو میفرستد |
| Classitis | نام Ousterhout برای classهای ریز کمعمق فراوان |
| جداسازی دغدغهها (Separation of concerns) | پرداختن به هر جنبه بهتنهایی (Dijkstra ۱۹۷۴) |
| دغدغهٔ همهجاگیر (Cross-cutting concern) | دغدغهای که به ماژولهای زیادی مربوط است: لاگ، auth، tracing، تراکنش |
| درهمتنیدگی / پراکندگی (Tangling / scattering) | دغدغههای زیاد در یک جا / یک دغدغه در جاهای زیاد |
| یکپارچگی مفهومی (Conceptual integrity) | یک مجموعه ایدهٔ منسجم در کل سیستم (Brooks ۱۹۷۵) |
| Connascence | دو عنصر باید با هم تغییر کنند تا درست بمانند (Page-Jones) |
| Strength / degree / locality | محورهای connascence: سختی refactor، تعداد متأثر، فاصله |
| Connascence ایستا / پویا (Static / dynamic) | دیدهشدنی در کد منبع / فقط در زمان اجرا |
| پیچیدگی cyclomatic (Cyclomatic complexity) | تعداد مسیرهای مستقل، v = e - n + 2p (McCabe ۱۹۷۶) |
| LCOM | Lack of Cohesion of Methods، کمبود انسجام متدها |
| gocyclo / go-arch-lint | ابزارهای Go: cyclomatic complexity؛ قواعد وابستگی بین componentها |
| phpmetrics / deptrac | ابزارهای PHP: گزارش معیارها؛ قواعد وابستگی بین لایهها |
| Distributed monolith | سرویسهایی که باید با هم تغییر و deploy شوند |
| API پرحرف (Chatty API) | فراخوانیهای ریزدانهٔ راه دور که تأخیر و شکست را چند برابر میکنند |
منابع
- D. L. Parnas، "On the Criteria To Be Used in Decomposing Systems into Modules"، Communications of the ACM 15(12)، ۱۹۷۲. PDF
- W. P. Stevens، G. J. Myers، L. L. Constantine، "Structured Design"، IBM Systems Journal 13(2)، ۱۹۷۴ (بازچاپ ۱۹۹۹). PDF
- E. W. Dijkstra، "On the role of scientific thought" (EWD447)، ۱۹۷۴. آرشیو Dijkstra (نسخهٔ بایگانیشده)
- F. P. Brooks، The Mythical Man-Month، فصل ۴ «Aristocracy, Democracy, and System Design». PDF درسی (University of Michigan)
- F. P. Brooks، "No Silver Bullet: Essence and Accident in Software Engineering"، ۱۹۸۶. PDF
- T. J. McCabe، "A Complexity Measure"، IEEE Transactions on Software Engineering، دسامبر ۱۹۷۶. PDF
- J. Ousterhout، یادداشتهای درس CS 190: The Nature of Complexity، Modular Design؛ صفحهٔ کتاب A Philosophy of Software Design
- R. C. Martin، Design Principles and Design Patterns، ۲۰۰۰ (Ca، Ce، I، SDP). PDF
- M. Fowler، "Reducing Coupling"، IEEE Software، ۲۰۰۱. PDF؛ Design Stamina Hypothesis؛ J. Lewis و M. Fowler، Microservices
- connascence.io: overview، strength، locality، degree، meaning
- T. Barrett-Powell، "Coupling"، ACCU ۲۰۱۰ (ارجاع به Page-Jones ۱۹۸۸ دربارهٔ pathological coupling). PDF
- Wikipedia (منبع ثانویه): Coupling (computer programming)، Connascence
- C. Richardson، Shared database pattern
- Go: Code Review Comments: Interfaces، Go Proverbs، gocyclo، go-arch-lint
- PHP: PhpMetrics metrics، deptrac، CK metrics tool
- Laravel 13: Contracts، Events، Service Container (contextual binding)، Middleware