Skip to content

UML در عمل: نمودارهای Class، Sequence، State، Activity، Component، Package و Deployment ​

"The objective of UML is to provide system architects, software engineers, and software developers with tools for analysis, design, and implementation of software-based systems as well as for modeling business and similar processes." — Object Management Group، OMG Unified Modeling Language Version 2.5.1 (formal/2017-12-05)، بند ۱ «Scope»، دسامبر ۲۰۱۷

خلاصه (Summary): UML یک زبان تصویری استاندارد برای نرم‌افزار است: ۱۴ نوع نمودار، نیمی برای ساختار (چه چیزهایی وجود دارند) و نیمی برای رفتار (در طول زمان چه اتفاقی می‌افتد). در کار روزمره حدود هفت‌تا از آن‌ها لازم است؛ به‌شکل طرح دستی (sketch) کشیده می‌شوند و به‌صورت متن در مخزن کد می‌مانند. تمرکز (Focus): ۱۴ نمودار و اینکه هرکدام به چه سؤال واقعی جواب می‌دهد؛ نمادگذاری نمودار کلاس با جزئیات (visibility، multiplicity، شش خط رابطه، association class، qualifier، stereotype، OCL)؛ نمادگذاری sequence، state machine و activity؛ نماهای component، package و deployment؛ سه حالت استفادهٔ Fowler؛ PlantUML و Mermaid؛ مدل C4؛ خواندن کد Go و Laravel و تبدیلش به نمودار. هدف یادگیری (Learning goal): برای هر سؤال طراحی نمودار درست را انتخاب کنید، آن را در پنج دقیقه به‌صورت متن PlantUML یا Mermaid درست بکشید، هر UMLی را که همکارتان نشان می‌دهد بخوانید، و نمودارها را با تولید خودکار یا تست در برابر کد Go و Laravel صادق نگه دارید.

این صفحه مرجع کامل UML است، آن‌طور که مهندس‌های شاغل واقعاً از آن استفاده می‌کنند: تاریخچه (Booch، Rumbaugh، Jacobson و OMG)، هر ۱۴ نوع نمودار UML 2.5.1، جزئیات نمادگذاری که بیشترین بدخوانی را می‌سازند، تقسیم‌بندی sketch/blueprint/programming language از Fowler، UML متنی با PlantUML و Mermaid، مدل C4 به‌عنوان مکمل امروزی برای معماری، و یک سیستم checkout که شش بار کشیده و در Go و Laravel پیاده شده است. همسایه‌ها را دوباره درس نمی‌دهیم: فرق معماری و طراحی در Architecture vs Design است، کارت‌های CRC و طراحی مفهومی در The Design Process، ایده‌های شیءگرایی پشت هر جعبه در Object-Oriented Modeling، مسئولیت کلاس‌ها در Low-Level Design و نمودارهای الگوها در Design Patterns. interface به‌عنوان درز (seam) در Interface Segregation و Dependency Inversion آمده است.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
هر ۱۴ نمودار و سه جدول رابطه در یک صفحههمه‌چیز در یک دقیقه
چرا نمادگذاری استاندارد لازم است و چه هزینه‌ای داردچرا UML وجود دارد
Booch، OMT، OOSE، OMG، از UML 1.x تا 2.5.1از کجا آمده
sketch در برابر blueprint در برابر programming languageسه حالت Fowler
دسته‌بندی ساختار و رفتار۱۴ نمودار
visibility، multiplicity، پیکان‌ها، association class، qualifier، stereotype، OCLنمودار کلاس
object، package، component، composite structure، profile، deploymentنمودارهای ساختاری
use case، activity، state machineنمودارهای رفتاری
sequence، communication، interaction overview، timingنمودارهای تعامل
frame، metamodel، XMI، گرامرهای متنیسازوکار
تبدیل package در Go یا ماژول Laravel به نمودار کلاسخواندن Go، خواندن Laravel
checkout در شش نما و کد Go و LaravelGo، Laravel، سیستم کامل
UML در برابر C4، و کدام نمودار برای کدام سؤالUML و C4، انتخاب
نمودار برای monolith، ماژول، سرویس و replicaدر معماری
تمرین عملی: تولید، رندر و تست نمودارآزمایشگاه
باورهای غلط، چکیده، خودآزمایی، همهٔ اصطلاح‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

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

۱۴ نمودار UML 2.5.1. فهرست از Annex A مشخصه (specification) است؛ ستون «استفادهٔ روزانه» قضاوت ما از تجربه است، نه حرف مشخصه.

نمودارخانوادهبه چه سؤالی جواب می‌دهدکی سراغش برویداستفادهٔ روزانه؟PlantUML / Mermaid
Classساختار (Structure)چه typeهایی هست و چه رابطه‌ای دارند؟مدل دامنه، API ماژول، بازبینی طراحیبلهYes / Yes
Objectساختارحافظه در یک لحظه چه شکلی است؟توضیح یک شکل دادهٔ پیچیده، fixture تستگاهیYes / No
Packageساختارکدام ماژول به کدام وابسته است؟لایه‌بندی، قاعدهٔ import، modular monolithبلهYes / via flowchart
Componentساختارکدام قطعهٔ قابل‌تعویض چه interfaceی ارائه می‌دهد و چه لازم دارد؟ports and adapters، مرز plug-inبلهYes / via flowchart or C4
Composite structureساختاردرون یک کلاس یا component چه سیم‌کشی‌ای هست؟سیستم‌های embedded، part و portبه‌ندرتPartial / No
Deploymentساختارچه چیزی کجا اجرا می‌شود و ماشین‌ها چطور حرف می‌زنند؟زیرساخت، محیط‌ها، failoverبلهYes / via C4Deployment
Profileساختارکدام stereotypeها UML را برای دامنهٔ من گسترش می‌دهند؟سازندگان ابزار، توسعه‌هایی مثل SysMLبه‌ندرتNo / No
Use caseرفتار (Behaviour)چه کسی برای چه هدفی از سیستم استفاده می‌کند؟کارگاه تعیین دامنه (متن مهم‌تر است)به‌ندرتYes / No
Activityرفتارچه گام‌هایی، با چه ترتیبی، توسط چه کسی، به‌موازات؟گردش‌کار کسب‌وکار، pipeline، sagaبلهYes / via flowchart
State machineرفتاریک چیز در چه حالت‌هایی می‌تواند باشد و چه چیزی جابه‌جایش می‌کند؟سفارش، پرداخت، اشتراک، پروتکلبلهYes / Yes
Sequenceتعامل (Interaction)چه کسی، به چه ترتیبی، چه کسی را صدا می‌زند؟جریان API، اشکال‌زدایی، بازبینی کدبلهYes / Yes
Communicationتعاملچه کسی با چه کسی حرف می‌زند (پیام‌های شماره‌دار روی پیوندها)؟همکاری‌های کوچک روی تختهبه‌ندرتNo / No
Interaction overviewتعاملچند تعامل چطور پشت هم زنجیر می‌شوند؟سناریوی بلند از تکه‌های sequenceبه‌ندرتNo / No
Timingتعاملحالت‌ها روی محور زمان چطور عوض می‌شوند؟بی‌درنگ (real-time) و سخت‌افزار، timeoutبه‌ندرتYes / No

شش خط نمودار کلاس. هر سطر در بلوک نمودار کلاس باز می‌شود.

رابطهخطبه زبان سادهPlantUML / Mermaidکد معمول
انجمن (Association)خط پر، پیکان باز اختیاریA ارجاعی ماندگار به B داردA --> Bفیلدی که B یا شناسهٔ B را نگه می‌دارد
تجمیع (Aggregation)خط پر، لوزی توخالی سمتِ کلB جزئی از A است اما می‌تواند مشترک باشد یا بیشتر بماندA o-- Bslice از اشاره‌گر به چیزهای مشترک
ترکیب (Composition)خط پر، لوزی توپر سمتِ کلA مالک B است؛ B با A می‌میردA *-- Bslice از مقدار؛ ON DELETE CASCADE
وابستگی (Dependency)خط‌چین، پیکان بازA برای مدت کوتاه از B استفاده می‌کند (پارامتر، متغیر محلی، ساختن)A ..> Bآرگومان تابع، new B()
تعمیم (Generalization)خط پر، مثلث توخالی سمتِ والدA نوعی B استA --|> Bextends؛ embedding در Go این نیست
تحقق (Realization)خط‌چین، مثلث توخالی سمتِ interfaceA interfaceِ B را پیاده می‌کندA ..|> Bimplements در PHP؛ ضمنی در Go

پیکان‌های نمودار sequence.

پیامخط و سر پیکان (UML 2.5.1، 17.4.4)PlantUMLMermaid
فراخوانی هم‌گام (Synchronous call)خط پر، سر توپرA -> BA->>B
سیگنال یا فراخوانی ناهم‌گام (Asynchronous)خط پر، سر بازA ->> BA-)B
پاسخ (Reply)خط‌چینB --> A یا returnB-->>A
ساختن (Create)خط‌چین با سر باز، به سرِ lifeline تازهcreate B و بعد A -> Bcreate participant B
حذف (Delete)پیامی که به X روی lifeline ختم می‌شودdestroy Bdestroy B
گم‌شده / یافته (Lost / found)نقطهٔ سیاه در انتها / در ابتداA ->x B (lost), [o-> B (found)not supported

چرا UML وجود دارد ​

طراحی‌ای که نتوانید نشانش بدهید، طراحی‌ای است که فقط خودتان می‌توانید بازبینی‌اش کنید. پیش از ۱۹۹۷ هر روش شیءگرا جعبه‌ها و پیکان‌های خودش را داشت و نمودار یک تیم برای تیم بعدی راهنمای علائم لازم داشت. UML نمادگذاری را ثابت کرد تا لوزی توپر در هر کتاب، ابزار و بازبینی کدی یک معنا داشته باشد. معامله همان همیشگی است: زبان مشترک دقیق‌تر است و یادگرفتنش هزینه دارد.

جعبه و خط دلبخواهیUMLمدل C4
هزینهٔ یادگیری صفرهزینهٔ یادگیری واقعی (مشخصه ۷۹۶ صفحه است)هزینهٔ یادگیری کم
هر پیکان راهنما لازم داردپیکان‌ها معنای ثابت دارندپیکان‌ها رابطه‌های برچسب‌دارند
سطح‌ها را قاطی می‌کند (کلاس کنار سرور)نماها را با نوع نمودار جدا می‌کندنماها را با سطح zoom جدا می‌کند
با کد قابل بررسی نیستاز کد قابل تولید و قابل تست استسطح code معمولاً تولیدی است
برای یک جلسه خوب استبرای بازبینی طراحی و آموزش خوب استبرای مستندسازی معماری خوب است
UML DiagramStructure diagrams (7)Behavior diagrams (7)ClassObjectPackageComponentComposite StructureDeploymentProfileUse CaseActivityState MachineInteraction diagramsSequenceCommunicationInteraction OverviewTiming= the seven used most in practiceSource: OMG UML 2.5.1 (formal/2017-12-05), Annex A, Figure A.5

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

تشبیهی که در کل صفحه از آن استفاده می‌کنیم: مجموعهٔ نقشه‌های یک ساختمان. یک خانه نقشهٔ معماری، نقشهٔ برق، نقشهٔ لوله‌کشی و نقشهٔ محوطه دارد. هیچ‌کس همهٔ سیم‌ها و لوله‌ها را در یک تصویر نمی‌کشد؛ هر نقشه به یک سؤال برای یک خواننده جواب می‌دهد و همه‌شان یک ساختمان را توصیف می‌کنند. UML همان مجموعهٔ نقشه برای نرم‌افزار است: نمودار کلاس نقشهٔ معماری است، نمودار sequence «وقتی کسی زنگ را می‌زند چه می‌شود»، نمودار deployment نقشهٔ محوطه. علائم استاندارد است تا برق‌کاری از شهر دیگر هم بتواند بخواندشان.

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

  1. «UML یک فرایند سنگین است.» UML نمادگذاری است. فرایند سنگینی که در دههٔ ۱۹۹۰ همراهش آمد (Rational Unified Process) چیز جدایی است. یک طرح دو دقیقه‌ای روی تخته با پیکان‌های درست، UML است.
  2. «نمودار باید همه‌چیز را نشان بدهد.» خود مشخصه دربارهٔ multiplicity برعکسش را می‌گوید: "If no multiplicity is shown on the diagram, no conclusion may be drawn about the multiplicity in the model." نمودار یک نما از مدل است؛ کنار گذاشتن چیزها عادی است.
  3. «UML مرده، به‌جایش C4 بکشید.» C4 ساختار ایستای معماری را در چهار سطح zoom پوشش می‌دهد و FAQ خودش می‌گوید "supplement the C4 diagrams with UML state diagrams, timing diagrams, etc if you need to". نمودار sequence و state machine در C4 جایگزینی ندارند.

از کجا آمده ​

مشخصه ریشه را در همان بند اول می‌گوید:

"The initial versions of UML (UML 1) originated with three leading object-oriented methods (Booch, OMT, and OOSE), and incorporated a number of best practices from modeling language design, object-oriented programming, and architectural description languages." — OMG UML 2.5.1، بند ۱

این سه روش مال کسانی بود که بعدها «سه رفیق» (three amigos) خوانده شدند: Grady Booch (روش Booch)، James Rumbaugh (OMT یا Object Modeling Technique) و Ivar Jacobson (OOSE یا Object-Oriented Software Engineering که use case را آورد). صفحهٔ کتاب Fowler اهمیتش را خلاصه می‌کند:

"The UML appeared in 1997 to eliminate the bedlam that had overtaken graphical modeling languages in the object-oriented world." — Martin Fowler، صفحهٔ کتاب UML Distilled، martinfowler.com

سالرویدادمنبع
1994Rational Software، James Rumbaugh را استخدام می‌کند؛ کار Booch و OMT ادغام می‌شودWikipedia (ثانویه)
1995Ivar Jacobson به Rational می‌پیوندد؛ OOSE و use case وارد می‌شوندWikipedia (ثانویه)
Jan 1997UML Partners نسخهٔ UML 1.0 را به OMG پیشنهاد می‌دهندWikipedia (ثانویه)
Nov 1997OMG نسخهٔ UML 1.1 را می‌پذیردWikipedia (ثانویه)
1997UML Distilled از Fowler، نخستین کتاب UMLصفحهٔ کتاب Fowler
2003ویراست سوم UML Distilled برای UML 2 بازنویسی می‌شودصفحهٔ کتاب Fowler
2005UML 2.0 جای 1.5 را می‌گیرد؛ ISO/IEC 19501:2005 منتشر می‌شودWikipedia (ثانویه)
2012ISO/IEC 19505-1:2012 (زیرساخت UML 2)Wikipedia (ثانویه)
Dec 2017UML 2.5.1، سند OMG به شمارهٔ formal/2017-12-05 (نسخهٔ جاری)صفحهٔ جلد مشخصه

UML 2.0 عملگرهای تعامل (alt، opt، loop، par، ref) را اضافه کرد که نمودار sequence را واقعاً کاربردی کردند، و UML 2.5 متن را برای خوانایی بازنویسی کرد: "The UML Infrastructure no longer forms part of the UML specification. The entire UML specification is constituted in this document." همان بند سطح‌های انطباق L0 تا L3 را هم حذف کرد: "A tool either complies with the whole of UML or it does not." فهرست نسخه‌های منتشرشده در سایت OMG این است: 1.5، 2.0، 2.1.2، 2.2، 2.3، 2.4.1، 2.5.1. زبان قیدی که کنار UML می‌نشیند، یعنی OCL، مشخصهٔ جداگانهٔ OMG است و صفحه‌اش می‌گوید: "OCL version 2.4 is the latest version of OCL that is aligned with UML 2.4.1 and MOF 2.4.1."

دو رشتهٔ بعدی برای کار روزمره مهم‌اند. UML متنی (اول PlantUML، بعد Mermaid) نمودار را وارد کنترل نسخه کرد و GitHub امروز Mermaid را داخل Markdown رندر می‌کند. و مدل C4 از Simon Brown، که FAQ آن می‌گوید "was inspired by UML and the 4+1 model for software architecture"، راهی سبک‌تر برای کشیدن معماری به تیم‌ها داد؛ نماهای 4+1 کروختن جدِ آن در طرف معماری است.

سه حالت Fowler: sketch، blueprint، programming language ​

یادداشت ۲۰۰۳ Fowler در bliki توضیح می‌دهد چرا سر UML دعوا می‌شود: "people differ about what should be in the UML because there are differing fundamental views about what the UML should be." او سه حالت (mode) نام می‌برد.

حالتهدفعبارت Fowlerابزارامروز کجا زندگی می‌کند
طرح دستی (Sketch)انتقال سریع یک ایده"The essence of sketching is selectivity."تخته، PlantUML، Mermaidبازبینی طراحی، PR، مستندات
نقشهٔ اجرایی (Blueprint)تحویل طراحی کامل به برنامه‌نویس"a UmlMode that focuses on completeness"ابزار CASE، round-trip engineeringحوزه‌های تحت مقررات و ایمنی‌محور
زبان برنامه‌نویسی (Programming language)تولید برنامه از مدل"I don't believe that graphical programming will succeed just because it's graphical."MDA، executable UMLکاربرد محدود (embedded، بعضی مولدهای کد state machine)

"Hence my sound-bite “comprehensiveness is the enemy of comprehensibility”" — Martin Fowler، UmlAsSketch، bliki

هر حالت دو جهت دارد. مهندسی رو به جلو (forward engineering) پیش از کدنویسی می‌کشد؛ مهندسی معکوس (reverse engineering) از کد موجود می‌کشد تا آن را بفهمد. ابزارهای blueprint که هر دو را انجام می‌دهند round-trip نامیده می‌شوند؛ Fowler ابزارهایی را که خود کد منبع را مخزن می‌دانند "tripless" می‌نامد. این صفحه برای حالت sketch نوشته شده، با یک عادت قرض‌گرفته از blueprint: طرح را به‌صورت متن کنار کد نگه دارید و تستش کنید تا بی‌صدا نپوسد.

مفهوم‌ها، یکی‌یکی ​

هر بلوک یک ترتیب ثابت دارد: به زبان ساده، باور غلط رایج، تعریف دقیق (جایی که عبارت مهم است از UML 2.5.1 نقل‌قول شده)، یک توالی یا سناریو، موقعیت‌های واقعی، نمادگذاری، و خود نمودار به‌صورت متن PlantUML و Mermaid. مثال سراسری یک checkout است: مشتری سفارش می‌دهد، موجودی رزرو می‌شود، کارت شارژ می‌شود، سفارش پرداخت و ارسال می‌شود.

۱۴ نمودار: ساختار در برابر رفتار حیاتی ​

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

بدفهمی رایج: «هر سیستمی هر ۱۴ نمودار را لازم دارد.» مشخصه این دسته‌بندی را "a logical organization" می‌نامد و اضافه می‌کند که "the boundaries between the various kinds of diagram types are not strictly enforced." بیشتر تیم‌ها هفت‌تا را به کار می‌برند و بیشتر طراحی‌های تکی دو یا سه‌تا لازم دارند.

تعریف: از Annex A در UML 2.5.1: "Structure diagrams show the static structure of the objects in a system. That is, they depict those elements in a specification that are irrespective of time." و: "Behavior diagrams show the dynamic behavior of the objects in a system, including their methods, collaborations, activities, and state histories."

text
     Design question                                  First diagram    Second diagram
1    "What is an Order made of?"                       class            object (one example)
2    "What happens when the customer clicks Pay?"     sequence         activity (if many actors)
3    "Can a shipped order be canceled?"                state machine    -
4    "Which module may import which?"                 package          component
5    "What runs on which server?"                     deployment       C4 container

سناریوی واقعی: بازبینی طراحی یک قابلیت بازپرداخت (refund) یک state machine لازم دارد (آیا از «shipped» به «refunded» راه هست؟) و یک نمودار sequence (چه کسی PSP را صدا می‌زند، چه کسی رویداد را منتشر می‌کند)؛ هیچ‌کس نمودار use case لازم ندارد. یک سند onboarding یک نمودار container از C4 و یک نمودار کلاس از هستهٔ دامنه می‌خواهد.

قاب نمودار (Diagram frame). Annex A اجازه می‌دهد هر نموداری داخل یک قاب بنشیند که سرعنوانش [<kind>]<name>[<parameters>] است، با نوع‌های کوتاه act، cmp، dep، sd، pkg، stm، uc (و شکل‌های بلند مثل class). وقتی گوشهٔ نموداری sd PlaceOrder می‌بینید، یعنی نمودار sequenceی به نام PlaceOrder.

نمودار کلاس (Class diagram) حیاتی ​

به زبان ساده: جعبه‌ها typeها هستند، بخش‌ها (compartment) فهرست می‌کنند که هر type چه نگه می‌دارد و چه کاری بلد است، و سبک خط بین دو جعبه می‌گوید چه رابطه‌ای دارند.

بدفهمی رایج: «لوزی یعنی has-a.» هر association یعنی has-a. لوزی توخالی (aggregation) تقریباً چیزی اضافه نمی‌کند؛ مشخصه می‌گوید "Precise semantics of shared aggregation varies by application area and modeler." فقط لوزی توپر (composition) معنای قوی و قابل‌آزمون دارد.

تعریف: نماد کلاس مستطیلی است با بخش نام و بخش‌های اختیاری attribute و operation. attributeها از گرامر property در بند 9.5.4 پیروی می‌کنند: [<visibility>] ['/'] <name> [':' <prop-type>] ['[' <multiplicity-range> ']'] ['=' <default>] ['{' <prop-modifier> [',' <prop-modifier>]* '}']، با <visibility> ::= ‘+’ | ‘-‘ | ‘#’ | ‘~’ (علامت‌های نقل‌قول در خط property یکدست شده‌اند).

«entity»Order+ id : OrderId {readOnly}- status : OrderStatus = Pending# placedAt : DateTime [0..1]~ lines : OrderLine [1..*] {ordered}+ /total : Money+ addLine(sku : String, qty : Integer) : void+ fire(e : Event) : Boolean+ {static} create(c : CustomerId) : Order- recalc() : void+ public · - private · # protected · ~ package/ derived · [m..n] multiplicity · {…} constraintunderline or {static} = static; italic name = abstractABAssociationA knows B (navigable to B)PlantUML/Mermaid: -->ABAggregationB is part of A, may be sharedPlantUML/Mermaid: o--ABCompositionA owns B; B dies with APlantUML/Mermaid: *--ABDependencyA uses B (temporary, «use»)PlantUML/Mermaid: ..>ABGeneralizationA is a kind of BPlantUML/Mermaid: --|>ABRealizationA implements interface BPlantUML/Mermaid: ..|>10..*Spec: hollow diamond = shared, filled = composite (11.5.4); dashed arrow = Dependency (7.7.4); hollow triangle = Generalization (9.2.4)

در تصویر، سمت چپ یک کلاس با سه بخش است که هر چهار نماد visibility، یک attribute مشتق‌شده (/total)، multiplicity و قید را نشان می‌دهد؛ سمت راست شش خط رابطه است، هرکدام با معنا و توکن PlantUML/Mermaid آن.

دیدپذیری (Visibility).

نمادنام UMLJava / C#PHPGo
+publicpublicpublicشناسهٔ export‌شده (حرف بزرگ)
-privateprivateprivateمعادلی برای هر type ندارد
#protectedprotectedprotectedمعادل ندارد (وراثت ندارد)
~packagepackage-private (Java)معادل نداردشناسهٔ export‌نشده: در کل package دیده می‌شود

چندی (Multiplicity). به شکل [lower..upper] روی property یا سر association نوشته می‌شود؛ * یعنی بی‌کران؛ اگر روی نمودار نیامده باشد یعنی «نشان داده نشده»، نه «یک»، هرچند در گرامر attribute، نبودِ multiplicity یعنی "implies a multiplicity of 1 (exactly one)".

نوشتهیعنیکد معمول
1دقیقاً یکیفیلد غیر null
0..1اختیاریفیلد nullable، اشاره‌گر، ?Type
* or 0..*هر تعدادslice، collection، hasMany
1..*دست‌کم یکیcollection به‌همراه قاعدهٔ اعتبارسنجی
2..4محدودقاعدهٔ دامنه (مثلاً ۲ تا ۴ بازیکن)
{ordered}, {unique}, {readOnly}modifierهای propertyslice مرتب، مجموعه، فیلد تغییرناپذیر

شش رابطه. عبارت مشخصه برای هر خط: Dependency "is shown as a dashed arrow between two model Elements"؛ "A Realization is shown as a dashed line with a triangular arrowhead at the end that corresponds to the realized Element"؛ Generalization "is shown as a line with a hollow triangle as an arrowhead"؛ و برای associationها، "When one end has aggregation = AggregationKind::shared a hollow diamond is added" در حالی که composition "differs in having the diamond filled in". معنای composition:

"Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it." — OMG UML 2.5.1، 9.5.3

مستندات PlantUML همین را خلاصه می‌کند: "The part cannot exist without the whole" (composition) و "The part can exist independently of the whole" (aggregation). پیمایش‌پذیری (navigability) پیکان باز روی سر association است؛ "A small x on the end of an Association indicates the end is not navigable."

کلاس انجمنی (Association class). وقتی خودِ پیوند داده دارد، پیوند یک کلاس است. مشخصه: "An AssociationClass is shown as a Class symbol attached to the Association path by a dashed line." مثال‌های کلاسیک: Enrollment بین Student و Course (نمره، تاریخ)؛ OrderLine بین Order و Product (تعداد، قیمت لحظهٔ فروش). در پایگاه‌دادهٔ رابطه‌ای یک جدول واسط با ستون‌های اضافه می‌شود؛ در Laravel یک belongsToMany با withPivot('qty', 'unit_price') یا یک pivot model سفارشی.

انجمن مقیدشده (Qualified association). qualifier جعبهٔ کوچکی روی یک سر است که مثل کلید map عمل می‌کند: Order [lineNo] → 0..1 OrderLine یعنی «با داشتن یک سفارش و یک شمارهٔ سطر، حداکثر یک سطر هست». مشخصه: سرِ qualified "has qualifiers that partition the instances associated with an instance at that end". در کد یک map است یا یک کلید یکتای مرکب (order_id, line_no).

abstract، interface، enumeration، stereotype. "The name of an abstract Classifier is shown in italics, where permitted by the font in use" (یا با {abstract}). interface کلیدواژهٔ «interface» دارد؛ enumeration «enumeration»؛ data type «dataType». stereotypeی مثل «entity»، «control»، «boundary» یا «repository» یک توسعهٔ profile است که به عنصر یک نقش می‌چسباند؛ کلیدواژه‌های داخل گیومه که خود UML تعریف کرده (مثل «interface» یا «use») stereotype نیستند ولی همان‌طور کشیده می‌شوند.

قید (Constraint) و OCL. هرچه داخل آکولاد بیاید قید است: {qty > 0}، {ordered}، {xor}. قیدهای دقیق را می‌شود با OCL نوشت، برای نمونه:

text
context Order
  inv atLeastOneLine: self.lines->notEmpty()
  inv totalMatches:   self.total = self.lines->collect(subtotal)->sum()
context Order::fire(e : Event)
  pre:  e = Event::stockReserved implies self.lines->notEmpty()

در عمل OCL در ابزارهای مدل‌محور دیده می‌شود؛ در کد، همین قاعده‌ها به اعتبارسنجی، قید CHECK پایگاه‌داده و تست تبدیل می‌شوند.

سناریوی واقعی: بازبینی دامنهٔ Order/OrderLine/Product که در آن سؤال composition («آیا سطر بدون سفارشش وجود دارد؟») قاعدهٔ ON DELETE کلید خارجی را تعیین می‌کند؛ بازبینی یک ماژول Laravel که در آن interface به‌همراه realization نشان می‌دهد StripeGateway قابل تعویض است؛ بازبینی کدی که در آن یک مثلث وراثت، مشکل Liskov در Square extends Rectangle را لو می‌دهد.

نمودار کلاس کامل checkout در سیستم کامل کشیده شده است؛ متنش این است:

text
@startuml
hide circle
class Customer {
  - id : CustomerId
  - email : String
}
class Order <<entity>> {
  - id : OrderId
  - status : OrderStatus
  + /total : Money
  + addLine(sku, qty, price)
  + fire(e : Event)
}
class OrderLine {
  - sku : String
  - qty : Integer {qty > 0}
  - unitPrice : Money
  + /subtotal() : Money
}
class Product {
  - sku : String
  - price : Money
}
enum OrderStatus {
  Pending
  Reserved
  Paid
  Shipped
  Canceled
}
abstract class Payment {
  - amount : Money
}
class CardPayment
class WalletPayment
interface PaymentGateway {
  + charge(o, amt)
}
class StripeGateway
class CheckoutService <<control>> {
  + placeOrder(cmd)
}
Customer "1" -- "0..*" Order
' qualifier syntax from PlantUML's "Qualified associations" section
Order [lineNo] *-- "0..1" OrderLine : lines
OrderLine "0..*" --> "1" Product
Order --> OrderStatus : status
Order "1" -- "0..*" Payment
Payment <|-- CardPayment
Payment <|-- WalletPayment
CheckoutService ..> Order : <<create>>
CheckoutService ..> PaymentGateway : <<use>>
PaymentGateway <|.. StripeGateway
@enduml
mermaid
classDiagram
  class Customer {
    -CustomerId id
    -String email
  }
  class Order {
    <<entity>>
    -OrderId id
    -OrderStatus status
    +total() Money
    +addLine(sku, qty, price)
    +fire(Event e)
  }
  class OrderLine {
    -String sku
    -int qty
    -Money unitPrice
    +subtotal() Money
  }
  class OrderStatus {
    <<enumeration>>
    Pending
    Reserved
    Paid
    Shipped
    Canceled
  }
  class Payment {
    <<abstract>>
    -Money amount
  }
  class PaymentGateway {
    <<interface>>
    +charge(o, amt)
  }
  Customer "1" -- "0..*" Order
  Order "1" *-- "1..*" OrderLine : lines
  OrderLine "0..*" --> "1" Product
  Order --> OrderStatus : status
  Order "1" -- "0..*" Payment
  Payment <|-- CardPayment
  Payment <|-- WalletPayment
  CheckoutService ..> Order : create
  CheckoutService ..> PaymentGateway : use
  PaymentGateway <|.. StripeGateway
  %% Mermaid has no qualifiers and no derived (/) marker

نمودار شیء (Object diagram) تکمیلی ​

به زبان ساده: عکسی از حافظه: شیءهای مشخص با مقدارهایشان، به هم پیوند خورده، در یک لحظه.

بدفهمی رایج: «نمودار شیء همان نمودار کلاس با نام‌های دیگر است.» این نمودار نمونه‌ها را نشان می‌دهد، پس multiplicity به شمارش واقعی تبدیل می‌شود و می‌توانید حالتی را ببینید که قاعده را می‌شکند (سفارش بدون سطر، دو مشتری با یک سبد مشترک).

تعریف: شیء یک InstanceSpecification است: "An InstanceSpecification represents the possible or actual existence of instances in a modeled system". مثل کلاس کشیده می‌شود با نامی زیرخط‌دار به شکل name : Type و slotهایی به شکل attribute = value.

text
     Moment   Object state (after PlaceOrder succeeded)
1    t0       c7:Customer  --  o1:Order{status=pending}
2    t1       o1 *-- l1:OrderLine{lineNo=1, qty=2}, l2:OrderLine{lineNo=2, qty=1}
3    t2       o1{status=paid, /total=33.00 EUR}

سناریوی واقعی: توضیح یک ساختار بازگشتی (درخت دسته‌بندی، فهرست قطعات)؛ مستندکردن fixture تست؛ نشان‌دادن دقیق اینکه یک رکورد خراب در production چه شکلی داشت به تیم پشتیبانی.

Object diagram (a snapshot)Communication diagramc7 : Customeremail = "a@b.io"o1 : Orderid = "o-1"status = paid/total = 33.00 EURl1 : OrderLinelineNo = 1sku = "BOOK-1"qty = 2l2 : OrderLinelineNo = 2sku = "PEN-9"qty = 1:Client:CheckoutService:Inventory:PaymentGateway:OrderRepo:Broker1: placeOrder()1.1: reserve()1.2: charge()1.3: save()1.4: publish()Message order lives in the numbers, not the layout.Underlined name : Type = an instance; slots hold values.

نیمهٔ چپ تصویر نمودار شیء است: c7 : Customer به o1 : Order با وضعیت paid پیوند دارد و آن سفارش دو OrderLine با شمارهٔ ۱ و ۲ دارد. نیمهٔ راست همان checkout را به شکل نمودار communication نشان می‌دهد (پایین‌تر توضیح داده شده).

text
@startuml
object "c7 : Customer" as c7 {
  email = "a@b.io"
}
object "o1 : Order" as o1 {
  id = "o-1"
  status = paid
}
object "l1 : OrderLine" as l1 {
  lineNo = 1
  qty = 2
}
object "l2 : OrderLine" as l2 {
  lineNo = 2
  qty = 1
}
c7 -- o1
o1 *-- l1
o1 *-- l2
@enduml
mermaid
%% Mermaid has no object diagram; a classDiagram with instance names is the usual stand-in
classDiagram
  class c7_Customer {
    email = "a@b.io"
  }
  class o1_Order {
    id = "o-1"
    status = paid
  }
  class l1_OrderLine {
    lineNo = 1
    qty = 2
  }
  c7_Customer -- o1_Order
  o1_Order *-- l1_OrderLine

نمودار بسته (Package diagram) مهم ​

به زبان ساده: پوشه‌ها و پیکان‌های «اجازهٔ import» بین آن‌ها.

بدفهمی رایج: «نمودار package همان درخت پوشه‌هاست.» درخت پوشه شامل‌بودن را نشان می‌دهد؛ ارزش نمودار package در پیکان‌های وابستگی است که بعد می‌توانید اجبارشان کنید (internal/ در Go، تست معماری، قاعده‌هایی به سبک deptrac).

تعریف: package یک فضای نام (namespace) برای عنصرهای قابل‌بسته‌بندی است و به شکل پوشه‌ای با زبانه کشیده می‌شود. وابستگی بین packageها پیکان خط‌چین است، به‌طور اختیاری با «import» (import عمومی: نام‌های واردشده دیدنی می‌شوند) یا «access» (import خصوصی)؛ مشخصه: "The keyword «import» is shown near the dashed arrow if the visibility is public; otherwise, the keyword «access» is shown to indicate private visibility." و «merge» برای package merge (که داخل خود metamodel قدیمی UML به کار می‌رفت و در برنامه‌ها کم دیده می‌شود).

text
     Rule drawn on the package diagram         Enforced by
1    web ..> checkout                         Go: import path; PHP: architecture test
2    checkout ..> payments, inventory          only through interfaces (ports)
3    payments, inventory ..> platform          platform imports nothing above it
4    nobody ..> web                           a cycle here fails the Go build

سناریوی واقعی: نقشهٔ ماژول‌های یک modular monolith؛ قاعدهٔ لایه‌بندی («دامنه هیچ چیزی از زیرساخت import نمی‌کند») که فصل Dependency Inversion اجبارش می‌کند؛ پیداکردن چرخهٔ import پیش از آنکه Go از کامپایل سر باز بزند.

Use case diagramPackage diagramShopCustomerPSPPlace orderAuthenticateApply coupon«include»«extend»[coupon entered]webcheckoutpaymentsinventoryplatform«import»«use»«use»

نیمهٔ راست تصویر نمودار package است: web پکیج checkout را import می‌کند، checkout از payments و inventory استفاده می‌کند، هر دو به platform وابسته‌اند و هیچ پیکانی به web نمی‌رسد. نیمهٔ چپ نمودار use case است که در بخش خودش می‌آید.

text
@startuml
package web {}
package checkout {}
package payments {}
package inventory {}
package platform {}
web ..> checkout : <<import>>
checkout ..> payments : <<use>>
checkout ..> inventory : <<use>>
payments ..> platform
inventory ..> platform
@enduml
mermaid
flowchart TB
  web["pkg web"] -. import .-> checkout["pkg checkout"]
  checkout -. use .-> payments["pkg payments"]
  checkout -. use .-> inventory["pkg inventory"]
  payments -.-> platform["pkg platform"]
  inventory -.-> platform

نمودار مؤلفه (Component diagram) حیاتی ​

به زبان ساده: قطعه‌های ساختمانی قابل‌تعویض با پریز و دوشاخه: هر قطعه چه چیزی عرضه می‌کند (provided interface) و به چه چیزی نیاز دارد (required interface).

بدفهمی رایج: «component یعنی میکروسرویس.» در UML، component هر واحد ماژولار و قابل‌تعویضی است: یک package در Go با یک درز interface، یک ماژول Laravel، یک کتابخانه یا یک سرویس. محل اجرا سؤال جدایی است و جایش نمودار deployment است.

تعریف: "A Component represents a modular part of a system that encapsulates its contents and whose manifestation is replaceable within its environment." interfaceها از دو راه وصل می‌شوند (بند 10.4.4): interface عرضه‌شده با "a circle or ball, often also called lollipop" و interface موردنیاز با "a half-circle or socket". توپی که داخل سوکت نشسته assembly connector است. port یک نقطهٔ تعامل نام‌دار روی مرز component است.

text
     Request                       Component       Required -> Provided
1    POST /orders                  Web API         PlaceOrder  -> Checkout
2    charge card                   Checkout        PaymentGateway -> PSP adapter
3    reserve stock                 Checkout        Inventory  -> Inventory adapter
4    persist                       Checkout        Orders     -> Order store

سناریوی واقعی: سرویس hexagonal («ports and adapters») که مؤلفهٔ دامنه‌اش PaymentGateway را لازم دارد و دو adapter آن را عرضه می‌کنند (Stripe در production و یک fake در تست)؛ package لاراولی که service providerش یک contract را به پیاده‌سازی bind می‌کند؛ سیستم plug-in (Microkernel).

«component»Web APInet/http · routes/api.php«component»Checkoutdomain + use casesPlaceOrder«component»PSP adapter«component»Inventory adapter«component»Order storePaymentGatewayInventoryOrdersBall (lollipop) = provided interface · socket = required interface · ball in socket = assembly connector

در تصویر، Web API سوکت PlaceOrder دارد که توپش را Checkout عرضه می‌کند؛ Checkout سه سوکت PaymentGateway، Inventory و Orders دارد و سه adapter توپ‌های متناظر را عرضه می‌کنند.

text
@startuml
component "Web API" as Web
component Checkout
component "PSP adapter" as PSP
component "Inventory adapter" as Inv
component "Order store" as Store
() PlaceOrder
() PaymentGateway
() "Inventory" as InvPort
() Orders
Checkout - PlaceOrder
Web ..> PlaceOrder : use
PSP - PaymentGateway
Inv - InvPort
Store - Orders
Checkout ..> PaymentGateway : use
Checkout ..> InvPort : use
Checkout ..> Orders : use
@enduml
mermaid
%% Mermaid has no UML component diagram; flowchart with circle nodes as interfaces
flowchart LR
  Web["«component» Web API"] -- requires --> PO(("PlaceOrder"))
  PO --- Checkout["«component» Checkout"]
  Checkout -- requires --> PG(("PaymentGateway"))
  PG --- PSP["«component» PSP adapter"]
  Checkout -- requires --> INV(("Inventory"))
  INV --- InvA["«component» Inventory adapter"]
  Checkout -- requires --> ORD(("Orders"))
  ORD --- Store["«component» Order store"]

نمودارهای Composite structure و Profile تکمیلی ​

به زبان ساده: نمودار composite structure یک جعبه را باز می‌کند و partها و portهای سیم‌کشی‌شدهٔ داخلش را نشان می‌دهد؛ نمودار profile stereotypeهای خودتان را تعریف می‌کند.

بدفهمی رایج: «composite structure همان composition است.» composition یک رابطه روی نمودار کلاس است؛ نمودار composite structure سیم‌کشی زمان اجرای partهای داخل یک classifier را نشان می‌دهد که با connector از طریق port به هم وصل‌اند.

تعریف: نمودار composite structure "Shows the internal structure of a StructuredClassifier" (Annex B، نوع‌های نمودار). نمودار profile، stereotypeهایی را نشان می‌دهد که metaclassها را گسترش می‌دهند: "A Stereotype defines an extension for one or more metaclasses". SysML، زبان مهندسی سیستم، معروف‌ترین profile روی UML است.

نمودارکی می‌ارزدخوانندهٔ معمول
Composite structureکنترلرهای embedded، قطعه‌های سخت‌افزار/نرم‌افزار، componentی با زیرمؤلفه و port درونیمهندسان سیستم
Profileتعریف یک‌بارهٔ «aggregateRoot»، «repository»، «microservice» تا ابزار بتواند اعتبارسنجی‌شان کندسازندگان ابزار، تیم‌های معماری

نمودار استقرار (Deployment diagram) حیاتی ​

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

بدفهمی رایج: «deployment یعنی YAML کوبرنتیز.» نمودار تصویر توپولوژی است؛ یک نمودار برای هر محیط (production، staging) عادی است، چون clustering و replicaها فرق دارند.

تعریف: "A Node is computational resource upon which Artifacts may be deployed, via Deployment relationships, for execution." nodeها جعبه‌های سه‌بعدی‌اند و می‌توانند تودرتو باشند؛ نوع‌های استاندارد «device» و «executionEnvironment» هستند. "An artifact is the specification of a physical piece of information that is used or produced by a software development process, or by deployment and operation of a system"، برای نمونه "source files, scripts, and binary executable files, a table in a database system". یک artifact یک component را «manifest» می‌کند. خط‌های بین nodeها مسیر ارتباطی (communication path) هستند و با پروتکل برچسب می‌خورند.

text
     Hop                       From -> To                      Protocol    Failure to plan for
1    customer request          Browser -> Load balancer        HTTPS       TLS expiry
2    route                     Load balancer -> api pod        HTTP        pod restart
3    write order               api pod -> PostgreSQL primary   SQL/5432    failover, pool exhaustion
4    replicate                 primary -> replica              WAL stream  replica lag
5    event                     api pod -> RabbitMQ -> worker   AMQP        broker down, redelivery
6    charge                    api pod -> Stripe               HTTPS       timeout, idempotency key

سناریوی واقعی: بازبینی حادثه‌ای که باید نشان بدهد خواندن کهنه از کدام replica آمد؛ برنامهٔ ظرفیت؛ سند انطباقی که مسیرهای مجاز دادهٔ کارت را فهرست می‌کند.

«device»Browser«node»Load balancer«executionEnvironment»k8s cluster«node»api pod«artifact»checkout-api (Go)«node»worker pod«artifact»laravel-worker:1.4«node»PostgreSQL«node»replica«node»RabbitMQ«external»StripeHTTPSHTTPSQLWALAMQPHTTPSNodes are 3D boxes; artifacts are what you ship (binaries, images); lines are communication paths.

تصویر مرورگر، load balancer، cluster کوبرنتیز با دو pod (artifact برنامهٔ Go در یکی و image ورکر Laravel در دیگری)، PostgreSQL با replica، RabbitMQ و Stripe را نشان می‌دهد؛ هر خط با پروتکلش برچسب خورده است.

text
@startuml
node "Browser" as B
node "Load balancer" as LB
node "k8s cluster" {
  node "api pod" {
    artifact "checkout-api (Go)" as api
  }
  node "worker pod" {
    artifact "laravel-worker:1.4" as worker
  }
}
database "PostgreSQL" as PG
database "replica" as REP
queue "RabbitMQ" as MQ
cloud "Stripe" as ST
B -- LB : HTTPS
LB -- api : HTTP
api -- PG : SQL
PG -- REP : WAL
api -- MQ : AMQP
worker -- MQ : AMQP
api -- ST : HTTPS
@enduml
mermaid
C4Deployment
  title Checkout, production
  Deployment_Node(k8s, "k8s cluster", "Kubernetes") {
    Deployment_Node(apiPod, "api pod") {
      Container(api, "checkout-api", "Go")
    }
    Deployment_Node(workerPod, "worker pod") {
      Container(worker, "laravel-worker", "PHP 8.4")
    }
  }
  Deployment_Node(db, "PostgreSQL primary") {
    ContainerDb(pg, "orders schema", "PostgreSQL")
  }
  Rel(api, pg, "SQL", "TCP 5432")

نمودار Use case، و چرا ضعیف است مهم ​

به زبان ساده: آدمک‌ها (actor) که به بیضی‌ها (هدف‌ها) داخل یک جعبه (سیستم) وصل‌اند.

بدفهمی رایج: «نمودار use case همان use case است.» نمودار فقط نام‌ها را فهرست می‌کند. use caseهای Jacobson متن هستند: یک سناریوی اصلی موفق و شاخه‌ها (extensions). یادداشت Fowler دربارهٔ use case و story ارزش را در روایت می‌بیند: "Use cases organize requirements to form a narrative of how users relate to and use a system."

تعریف: actor نقشی بیرون از سیستم است؛ use case هدفی است که سیستم تحویل می‌دهد. «include» پیکان خط‌چینی است "pointing from the base UseCase to the included UseCase"؛ «extend» پیکان خط‌چینی است "pointing from the extending UseCase towards the extended UseCase"، به‌طور اختیاری با شرط و extension point.

چرا در عمل ضعیف است:

مشکلچه می‌شودابزار بهتر
نه ترتیب دارد، نه داده، نه خطابخش جالب (اگر کارت رد شود چه؟) دیده نمی‌شودمتن use case، نمودار sequence
بحث «include»/«extend»تیم‌ها به‌جای نیازمندی سر پیکان دعوا می‌کنندشاخه‌ها به شکل bullet ساده
کامل به نظر می‌رسد ولی کم می‌گویدده بیضی از بازبینی‌ای رد می‌شوند که هیچ چیز پیدا نکردuser story با معیار پذیرش
تجزیهٔ تابعی یواشکی وارد می‌شود«اعتبارسنجی آدرس» یک use case می‌شودفقط هدف‌های سطح کاربر

با این حال در کارگاه تعیین دامنه جای خودش را دارد: یک نمودار که actorها (از جمله actorهای فرعی مثل ارائه‌دهندهٔ پرداخت) و مرز سیستم را نشان بدهد. نیمهٔ چپ تصویر بالای بخش package همین را نشان می‌دهد: Customer به «Place order» وصل است، «Place order» «Authenticate» را include می‌کند و «Apply coupon» با شرط [coupon entered] آن را extend می‌کند.

text
@startuml
left to right direction
actor Customer
actor "Payment provider" as PSP
rectangle Shop {
  usecase "Place order" as UC1
  usecase "Authenticate" as UC2
  usecase "Apply coupon" as UC3
}
Customer -- UC1
UC1 -- PSP
UC1 .> UC2 : <<include>>
UC3 .> UC1 : <<extend>>
@enduml
mermaid
%% Mermaid has no use case diagram; stadium nodes as ovals
flowchart LR
  Customer(["actor Customer"]) --- UC1(["Place order"])
  UC1 --- PSP(["actor Payment provider"])
  UC1 -. include .-> UC2(["Authenticate"])
  UC3(["Apply coupon"]) -. extend .-> UC1

نمودار فعالیت (Activity diagram) حیاتی ​

به زبان ساده: فلوچارتی با قدرت اضافه: موازی‌کاری واقعی (fork/join)، swimlane برای اینکه هر گام را چه کسی انجام می‌دهد، و داده‌ای که بین گام‌ها جریان دارد.

بدفهمی رایج: «نمودار activity همان فلوچارت قدیمی است.» activityهای UML 2 معنای token دارند (به سبک Petri net): join صبر می‌کند تا همهٔ جریان‌های ورودی token داشته باشند، که دقیقاً رفتار گامی از saga است که منتظر دو سرویس می‌ماند. فلوچارت چنین قاعده‌ای ندارد.

تعریف: actionها (مستطیل‌های گوشه‌گرد) با control flow به هم وصل‌اند؛ initial node (نقطهٔ سیاه) و activity final node (هدف تیراندازی)؛ flow final (دایره با ضربدر) فقط یک جریان را تمام می‌کند. "A ForkNode is a ControlNode that splits a flow into multiple concurrent flows"؛ join آن‌ها را هم‌گام می‌کند. "A DecisionNode is a ControlNode that chooses between outgoing flows"، با guard داخل کروشه؛ merge node شاخه‌ها را بدون انتظار دوباره یکی می‌کند. "An ActivityPartition is a kind of ActivityGroup for identifying ActivityNodes that have some characteristics in common" که به شکل swimlane کشیده می‌شود. object nodeها (مستطیل‌هایی مثل o : Order [paid]) داده را روی object flow حمل می‌کنند.

text
     Token                     Node                 Rule
1    one token                 fork                 becomes two tokens: Reserve stock || Authorize payment
2    token A arrives           join                 waits
3    token B arrives           join                 both present -> one token continues to Create order
4    [invalid] at decision     decision             exactly one outgoing guard must be true
5    token reaches bullseye    activity final       the whole activity ends, all tokens destroyed

سناریوی واقعی: گردش‌کار checkout یا onboarding که از چند تیم می‌گذرد؛ pipeline داده با مرحله‌های موازی؛ sagaیی که مسیرهای جبرانی‌اش باید دیده شوند؛ Bus::batch در Laravel که jobهایش موازی اجرا می‌شوند و callback then نقش join را دارد.

CustomerCheckoutWarehousePaymentsSubmit cartValidate cart[invalid]Fix cart[valid]forkReserve stockAuthorize paymentjoinCreate ordero : Order[paid]Read confirmationSend confirmation

تصویر چهار swimlane دارد: Customer سبد را می‌فرستد، Checkout اعتبارسنجی می‌کند، decision سبد نامعتبر را برای اصلاح برمی‌گرداند، fork دو کار «Reserve stock» (در Warehouse) و «Authorize payment» (در Payments) را هم‌زمان شروع می‌کند، join منتظر هر دو می‌ماند، و بعد سفارش ساخته می‌شود و object node یعنی o : Order [paid] به «Send confirmation» می‌رود.

text
@startuml
|Customer|
start
repeat :Submit cart;
  |Checkout|
  :Validate cart;
backward:Fix cart;
repeat while (cart invalid?) is (yes)
->no;
fork
  |Warehouse|
  :Reserve stock;
fork again
  |Payments|
  :Authorize payment;
end fork
|Checkout|
:Create order;
note right: object flow o : Order [paid]
:Send confirmation;
|Customer|
:Read confirmation;
stop
@enduml
mermaid
flowchart TB
  subgraph Customer
    s((start)) --> submit[Submit cart]
    fix[Fix cart]
    readc[Read confirmation] --> e(((End)))
  end
  subgraph Checkout
    validate[Validate cart] --> valid{valid?}
    create[Create order] --> obj[/o : Order paid/]
    obj --> send[Send confirmation]
  end
  subgraph Warehouse
    reserve[Reserve stock]
  end
  subgraph Payments
    auth[Authorize payment]
  end
  submit --> validate
  valid -- no --> fix --> submit
  valid -- yes --> reserve & auth
  reserve & auth --> create
  send --> readc

نمودار ماشین حالت (State machine diagram) حیاتی ​

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

بدفهمی رایج: «یک ستون status با dropdown یعنی state machine.» بدون جدول گذار (transition)، هر کدی می‌تواند هر وضعیتی را بگذارد و نتیجه‌اش باگ «اول shipped بعد دوباره pending» است. ارزش نمودار در پیکان‌هایی است که نکشیده‌اید.

تعریف: حالت‌ها مستطیل گوشه‌گردند؛ برچسب transition از گرامر بند 14.2.4 پیروی می‌کند: [<trigger> [‘,’ <trigger>]* [‘[‘ <guard>’]’] [‘/’ <behavior-expression>]]، یعنی رویداد [شرط] / اثر. هر حالت می‌تواند رفتارهای entry /، exit / و do / داشته باشد. حالت مرکب (composite state) region دارد؛ حالتی که چند region دارد متعامد (isOrthogonal) است و regionهایش هم‌زمان اجرا می‌شوند و با خط‌چین جدا کشیده می‌شوند. pseudostateها شامل initial (نقطه)، choice، junction، fork، join، entry/exit point، terminate و history هستند: "Deep history (deepHistory) represents the full state configuration of the most recent visit to the containing Region"، در حالی که "Shallow history (shallowHistory) represents a return to only the topmost substate". رویداد زمانی به شکل after(15 min) و رویداد تغییر به شکل when(stock = 0) نوشته می‌شود.

text
     Event                    From        Guard                 To          Effect
1    stockReserved            Pending     [lines not empty]     Reserved    reserve()
2    paymentCaptured          Reserved    -                     Paid        -
3    paymentDeclined          Reserved    -                     Canceled    release()
4    after(15 min)            Pending     -                     Canceled    -
5    dispatched               Paid        -                     Fulfilment  enters both regions
6    hold, then resume        Fulfilment  -                     H* -> same substates as before
7    cancel                   Paid        -                     (no arrow)  rejected: illegal transition

سناریوی واقعی: چرخهٔ عمر سفارش، پرداخت، اشتراک و بازپرداخت؛ حالت‌های اتصال TCP؛ تأیید سند؛ هر ستونی که نامش status است. کد Go و Laravel پایین ماشین سطح بالا را پیاده می‌کند: Fulfilment به یک حالت Shipped تخت شده و تایمر ۱۵ دقیقه‌ای و history مربوط به hold/resume کنار گذاشته شده‌اند. وقتی کد و نمودار سطح بالا از هم فاصله بگیرند یک تست شکست می‌خورد.

Pendingentry / startTimer(15m)ReservedPaidstockReserved[lines not empty] / reserve()paymentCapturedCanceledcancelafter(15 min)paymentDeclined/ release()FulfilmentdispatchedH*PackingInTransitshippedInvoicingInvoicedcompletionOnHoldholdresume

در تصویر، Pending با entry / startTimer(15m) شروع می‌شود؛ stockReserved [lines not empty] / reserve() به Reserved می‌رود؛ از Reserved با paymentCaptured به Paid و با paymentDeclined / release() به Canceled؛ dispatched وارد حالت مرکب Fulfilment با دو region متعامد می‌شود؛ hold به OnHold می‌برد و resume از طریق H* (deep history) همان زیرحالت‌های قبلی را برمی‌گرداند. کد این فصل Fulfilment را برای سادگی به یک حالت Shipped تخت کرده است. region بالایی هم initial pseudostate دارد (برای ورود عادی) و هم H* (برای بازگشت از OnHold).

text
@startuml
[*] --> Pending
Pending : entry / startTimer(15m)
Pending --> Reserved : stockReserved [lines not empty] / reserve()
Pending --> Canceled : cancel
Pending --> Canceled : after(15 min)
Reserved --> Paid : paymentCaptured
Reserved --> Canceled : paymentDeclined / release()
Paid --> Fulfilment : dispatched
state Fulfilment {
  [*] --> Packing
  Packing --> InTransit : shipped
  InTransit --> [*]
  --
  [*] --> Invoicing
  Invoicing --> Invoiced
  Invoiced --> [*]
}
Fulfilment --> OnHold : hold
OnHold --> Fulfilment[H*] : resume
Fulfilment --> [*]
Canceled --> [*]
@enduml
mermaid
stateDiagram-v2
  [*] --> Pending
  Pending: Pending (entry / startTimer)
  Pending --> Reserved: stockReserved [lines not empty] / reserve()
  Pending --> Canceled: cancel, after(15 min)
  Reserved --> Paid: paymentCaptured
  Reserved --> Canceled: paymentDeclined / release()
  Paid --> Fulfilment: dispatched
  state Fulfilment {
    [*] --> Packing
    Packing --> InTransit: shipped
    InTransit --> [*]
    --
    [*] --> Invoicing
    Invoicing --> Invoiced
    Invoiced --> [*]
  }
  Fulfilment --> OnHold: hold
  OnHold --> Fulfilment: resume (Mermaid has no history pseudostate)
  Fulfilment --> [*]
  Canceled --> [*]

نمودار توالی (Sequence diagram) حیاتی ​

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

بدفهمی رایج: «نمودار sequence الگوریتم را نشان می‌دهد.» یک رد اجرا (trace) را نشان می‌دهد. حلقه و شاخه با combined fragment ممکن است، اما نموداری پر از alt تودرتو کدی است که بد کشیده شده؛ برای هر سناریو یک نمودار جدا بکشید.

تعریف: "A Lifeline represents an individual participant in the Interaction." execution specificationها (activation) "thin rectangles (gray or white) on the lifeline" هستند. نوع پیام‌ها طبق بند 17.4.4: "An asynchronous Message ... has an open arrow head"، "A synchronous Message ... has a filled arrow head"، "A reply Message ... has a dashed line"، "An object creation Message ... has a dashed line with an open arrow head"، و پیام حذف به یک destruction occurrence (یک X) ختم می‌شود. "A lost Message is a Message where the sending event occurrence is known, but there is no receiving event occurrence"؛ found message برعکس آن است. gate یک سر پیام روی مرز یک interaction یا fragment است.

تکه‌های ترکیبی (Combined fragments) و عملگرهای تعامل.

عملگرمعنا (UML 2.5.1، 17.6.3)کاربرد
alt"At most one of the operands will be chosen"؛ [else] نقیض بقیه استشاخهٔ موفق در برابر شکست
opt"either the (sole) operand happens or nothing happens"گام اختیاری (ایمیل اگر کاربر خواسته)
loop"The loop operand will be repeated a number of times"، loop(min,max)تلاش دوباره، صفحه‌بندی
par"a parallel merge between the behaviors of the operands"فراخوانی‌های پخشی (fan-out)
breakoperand اجرا می‌شود "instead of the remainder of the enclosing InteractionFragment"خروج زودهنگام روی خطا
criticaloperand اتمی است: بدون درهم‌آمیختگیبخشی زیر قفل
neg, assertرد نامعتبر؛ تنها رد معتبرمشخص‌کردن رفتار ممنوع
seq, strictترتیب ضعیف در برابر سخت‌گیرانه بین operandهاکم؛ مدل‌سازی دقیق
ignore, considerکدام پیام‌ها (بی)ربط‌اندکم
refیک InteractionUse: "a shorthand for copying the contents of the referenced Interaction"استفادهٔ دوباره از «Authenticate» در چند نمودار
text
     Step  Lifeline -> lifeline              Arrow                   Code (Go)
1     1    Client -> CheckoutService         sync, filled head       svc.PlaceOrder(ctx, ...)
2     2    CheckoutService --> o:Order       «create», dashed open   checkout.NewOrder(id, customer)
3     3    CheckoutService -> Inventory      sync                    s.Inventory.Reserve(...)
4     4    alt [captured] / [declined]       combined fragment       if err := s.Payments.Charge(...); err != nil
5     5    CheckoutService ->> Broker        async, open head        s.Events.Publish(...) without waiting
6     6    CheckoutService --> Client        reply, dashed           return o, nil

سناریوی واقعی: جریان API در توضیح یک pull request؛ بازتولید race بین webhook و redirect؛ نشان‌دادن اینکه کدام سرویس مالک retry است؛ مستندکردن handshake در OAuth یا پرداخت؛ توضیح یک گام saga و جبرانش.

:Client:CheckoutService:Inventory:PaymentGateway:OrderRepo:Brokero:OrderplaceOrder(items)«create»reserve(lines)okalt[captured]charge(o, total)paymentIdfire(paymentCaptured)[declined]release(o)fire(paymentDeclined)save(o)opt[paid]OrderPaid201 / 402Filled head = synchronous call; dashed = reply or «create»; open head on solid line = asynchronous signal.

در تصویر، Client با پیام هم‌گام placeOrder شروع می‌کند، سرویس با پیام «create» یک lifeline تازه برای o:Order می‌سازد، موجودی را رزرو می‌کند، و fragment alt دو operand دارد: [captured] که شارژ موفق است و [declined] که موجودی آزاد و سفارش لغو می‌شود. بعد سفارش ذخیره می‌شود و در fragment opt [paid] رویداد OrderPaid با پیکان سر باز (ناهم‌گام) به broker می‌رود.

text
@startuml
participant Client
participant ":CheckoutService" as S
participant ":Inventory" as I
participant ":PaymentGateway" as P
participant ":OrderRepo" as R
queue ":Broker" as B
Client -> S ++ : placeOrder(items)
create Order
S --> Order : <<create>>
S -> I : reserve(lines)
I --> S : ok
alt captured
  S -> P : charge(o, total)
  P --> S : paymentId
  S -> Order : fire(paymentCaptured)
else declined
  S -> I : release(o)
  S -> Order : fire(paymentDeclined)
end
S -> R : save(o)
opt paid
  S ->> B : OrderPaid
end
return 201 / 402
@enduml
mermaid
sequenceDiagram
  participant C as Client
  participant S as CheckoutService
  participant I as Inventory
  participant P as PaymentGateway
  participant R as OrderRepo
  participant B as Broker
  C->>+S: placeOrder(items)
  create participant O as Order
  S-->>O: «create»
  S->>I: reserve(lines)
  I-->>S: ok
  alt captured
    S->>P: charge(o, total)
    P-->>S: paymentId
    S->>O: fire(paymentCaptured)
  else declined
    S->>I: release(o)
    S->>O: fire(paymentDeclined)
  end
  S->>R: save(o)
  opt paid
    S-)B: OrderPaid
  end
  S-->>-C: 201 / 402

نمودار ارتباط (Communication diagram) تکمیلی ​

به زبان ساده: همان پیام‌های نمودار sequence، اما روی پیوندهای بین شیءها و با شماره (1، 1.1، 1.2) به‌جای ترتیب بالا به پایین.

بدفهمی رایج: «نوع دیگری از اطلاعات است.» همان تعامل است که از سمت ساختار دیده می‌شود: برای «چه کسی با چه کسی حرف می‌زند» خوب است و برای «به چه ترتیبی» ضعیف. UML 1 اسمش را collaboration diagram گذاشته بود.

تعریف: lifelineها جعبه‌هایی‌اند که با link به هم وصل‌اند؛ هر پیام یک برچسب شماره‌دار با پیکان کوچک است؛ شماره‌های تودرتو (1.1، 1.2) یعنی فراخوانی‌هایی که هنگام رسیدگی به پیام 1 انجام می‌شوند. نیمهٔ چپ تصویر نمودار شیء شیءها را نشان می‌دهد و نیمهٔ راستش checkout را به شکل نمودار communication. نه PlantUML و نه Mermaid نوع نمودار communication ندارند؛ تقریب معمول یک نمودار شیء با برچسب‌های شماره‌دار روی پیوندهاست.

text
     Number   Link                           Message
1    1        Client - CheckoutService       placeOrder()
2    1.1      CheckoutService - Inventory    reserve()
3    1.2      CheckoutService - PSP          charge()
4    1.3      CheckoutService - OrderRepo    save()
5    1.4      CheckoutService - Broker       publish()
text
@startuml
' no communication diagram type: object diagram with numbered link labels
object ":Client" as C
object ":CheckoutService" as S
object ":Inventory" as I
object ":PaymentGateway" as P
object ":OrderRepo" as R
object ":Broker" as B
C -- S : 1: placeOrder() >
S -- I : 1.1: reserve() >
S -- P : 1.2: charge() >
S -- R : 1.3: save() >
S -- B : 1.4: publish() >
@enduml
mermaid
%% no communication diagram type: flowchart with numbered edge labels
flowchart LR
  C[":Client"] -- "1: placeOrder()" --> S[":CheckoutService"]
  S -- "1.1: reserve()" --> I[":Inventory"]
  S -- "1.2: charge()" --> P[":PaymentGateway"]
  S -- "1.3: save()" --> R[":OrderRepo"]
  S -- "1.4: publish()" --> B[":Broker"]

نمودارهای Interaction overview و Timing تکمیلی ​

به زبان ساده: interaction overview یک نمودار activity است که جعبه‌هایش نمودارهای sequence کامل (یا ref به آن‌ها) هستند؛ نمودار timing حالت‌های lifelineها را روی محور افقی زمان می‌گذارد.

بدفهمی رایج: «نمودار timing برای نمودار کارایی است.» حالت در طول زمان را با قید مدت ({t..t+3s}) نشان می‌دهد؛ تصویر طبیعی timeout، debounce و handshake سخت‌افزاری.

تعریف: هر دو نمودار تعامل‌اند (Annex A: "Interaction Overview Diagram - Interactions"، "Timing Diagram - Interactions"). PlantUML نمودار timing را پشتیبانی می‌کند (شرکت‌کننده‌های robust و concise)؛ Mermaid هیچ‌کدام را ندارد.

نموداربه درد چه می‌خوردمثال
Interaction overviewزنجیرکردن سناریوها: ورود، بعد checkout، بعد (alt) 3-D Secureref Authenticate → decision → ref PlaceOrder
Timingtimeout و مدت حالت‌هاسفارش حداکثر ۱۵ دقیقه Pending می‌ماند، بعد Canceled

سازوکار ​

مدل، نمودار و نمادگذاری سه چیز جدا هستند مهم ​

Annex A با همین تمایز شروع می‌شود: "A UML model consists of elements such as packages, classes, and associations. The corresponding UML diagrams are graphical representations of parts of the UML model." مدل در مخزن یک ابزار (یا در کد شما) زندگی می‌کند؛ هر نمودار یک نمای فیلترشده است. برای همین یک کلاس می‌تواند روی ده نمودار با بخش‌های متفاوت ظاهر شود.

لایهچیستاستانداردبرای چه کسی مهم است
نحو انتزاعی (Abstract syntax)metamodel: Class، Property، Association، Lifeline…UML 2.5.1 (مبتنی بر MOF)سازندگان ابزار
معناشناسی (Semantics)یک composition یا join یعنی چهبندهای semantics در UML 2.5.1هرکس سر پیکان بحث می‌کند
نمادگذاری (Notation)شکل‌ها و گرامرهای متنیبندهای notation در UML 2.5.1هرکس نمودار می‌کشد
تبادل (Interchange)ذخیرهٔ مدل و نمودار بین ابزارهافایل‌های XMI (UML.xmi)، UML DI (Annex B)مهاجرت بین ابزارها
قیدها (Constraints)قاعده‌های دقیق روی مدلOCL 2.4تیم‌های مدل‌محور

گرامرهای متنی که واقعاً تایپ می‌کنید ​

text
property    [+|-|#|~] [/] name [: Type] [[m..n]] [= default] [{readOnly, ordered, unique, id, ...}]
operation   [+|-|#|~] name ( [in|out|inout] p : Type [= default], ... ) [: ReturnType] [{query, ...}]
transition  trigger [, trigger]* [ [guard] ] [ / effect ]
state       name  /  entry / action  /  do / activity  /  exit / action
message     [attribute =] name ( arguments ) [: return-value]
multiplicity 1 | 0..1 | * | 0..* | 1..* | m..n
frame       sd | stm | act | cmp | dep | pkg | uc  <name> [parameters]

نمودار به‌مثابهٔ کد: متن کجا می‌ماند و چطور رندر می‌شود حیاتی ​

UML متنی تصویر را به یک diff قابل‌بازبینی تبدیل می‌کند. PlantUML برای use case خودش را "Text in, diagram out" معرفی می‌کند و همهٔ نمودارهای UML این صفحه جز communication، interaction overview و profile را پوشش می‌دهد؛ Mermaid نمودار کلاس، sequence و state را بومی پشتیبانی می‌کند و بقیه را با flowchart یا نمودارهای C4 خودش تقریب می‌زند. GitHub، Mermaid را رندر می‌کند:

"Diagram rendering is available in GitHub Issues, GitHub Discussions, pull requests, wikis, and Markdown files." — GitHub Docs، Creating diagrams

و "To create a Mermaid diagram, add Mermaid syntax inside a fenced code block with the mermaid language identifier."

روشچطورچرا
منبع را کنار کد نگه داریدdocs/diagrams/*.puml، *.mmd یا بلوک کد در README.mdنمودار در همان PR کد عوض می‌شود
در CI رندر کنیدPlantUML یا Mermaid CLI به SVG هنگام mergeبازبین تصویر را می‌بیند، مخزن متن را نگه می‌دارد
آنچه تولیدشدنی است را تولید کنیدنمودار کلاس/package از کد (goplantuml، ابزار umlgen پایین، فرمان Laravel پایین)نمودار تولیدی نمی‌پوسد
آنچه نیت را حمل می‌کند دستی بنویسیدsequence، state، deploymentکد نیت، ترتیب و توپولوژی را خوب نشان نمی‌دهد
نمودار دستی را تست کنیدمتن را در تست parse کنید و با کد مقایسه کنیدفاصله‌گرفتن، build را می‌شکند (آزمایشگاه)
هر نمودار یک سؤالنام فایل سؤال را می‌گوید: checkout-declined.pumlFowler: گزینش‌گری

خواندن یک package در Go و تبدیلش به نمودار کلاس ​

Go روشن‌ترین مثال ناهمخوانی بین مدل شیء UML و یک زبان واقعی است. FAQ زبان Go به سؤال «آیا Go شیءگراست؟» این‌طور جواب می‌دهد: "Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy." و دربارهٔ interface:

"A Go type implements an interface by implementing the methods of that interface, nothing more." — The Go FAQ، Why doesn't Go have "implements" declarations?

سازهٔ Goعنصر UMLنکته
type Order struct{...}Classفیلدها attribute، متدهای با receiver مقداری یا اشاره‌گری operation
شناسهٔ export‌شده / export‌نشده+ / ~دیدپذیری Go در سطح package است، پس ~ (package) نه - (private)
type PaymentGateway interface{...}«interface»معمولاً در package مصرف‌کننده تعریف می‌شود
typeی که method setاش یک interface را برآورده می‌کندRealization ..|>ضمنی (implicit)؛ هیچ جای کد نامش را نمی‌برد. با var _ I = (*T)(nil) ادعا کنید
struct embedding یعنی type B struct{ A }Composition به‌علاوهٔ operationهای ارتقایافتهتعمیم نیست: B جایی که A لازم است قابل استفاده نیست
فیلد مقداری یا slice مثل Lines []OrderLineComposition *-- با multiplicity 0..*معنای مقداری: جزءها درون کل زندگی می‌کنند
فیلد اشاره‌گر یا interfaceAssociation -->ارجاع مشترک یا قابل‌تعویض
فقط پارامتر تابعDependency ..>
type Status string با ثابت‌ها«enumeration» (تقریبی)Go enum بسته ندارد؛ مجموعه یک قرارداد است
PackagePackage؛ internal/گراف import همان نمودار package است
type عام مثل Set[T comparable]کلاس قالبی (template) با پارامتر Tقالب‌های UML در عمل کم کشیده می‌شوند

دو نتیجه. اول، پیکان realization یک واقعیت محاسبه‌شده از method setها است، پس مولد باید از go/types (types.Implements) استفاده کند، نه جست‌وجوی متنی. دوم، interface معمولاً کنار مصرف‌کننده‌اش است، پس نمودار package نشان می‌دهد checkout مالک PaymentGateway است و stripe جز برای برآوردن آن چیزی از checkout import نمی‌کند. این همان Dependency Inversion است که کشیده شده. ابزارهای موجود: GoPlantUML ("an open-source library and CLI that generates PlantUML class diagrams from Go source code") و برنامهٔ کوتاه umlgen در snippetهای این فصل.

خواندن یک ماژول Laravel و تبدیلش به نمودار کلاس ​

سازهٔ PHP / Laravelعنصر UMLنکته
class Order extends ModelClass (اگر خواستید با stereotype «entity»)attributeهای Eloquent فیلد اعلام‌شده نیستند: migration یا $casts/casts() را بخوانید
public / protected / private+ / # / -PHP دیدپذیری package ندارد
hasMany(OrderLine::class)Association "1" -- "0..*"فقط اگر کلید خارجی cascade کند composition است (cascadeOnDelete())
belongsTo(Customer::class)Association "0..*" --> "1"از سمت فرزند پیمایش‌پذیر
hasOneAssociation "1" -- "0..1"
belongsToMany(...)->withPivot(...)Association classpivot (یا pivot model سفارشی) همان association class است
morphTo / morphManyAssociation به یک type انتزاعی یا «interface»association چندریختی؛ انتزاع را بکشید
implements PaymentGatewayRealization ..|>در PHP صریح است، برخلاف Go
extendsGeneralization --|>
use SomeTraitمعادل UML نداردبه شکل stereotype «trait» با یک dependency بکشید یا عضوهایش را در کلاس پهن کنید
enum OrderStatus: string (backed)«enumeration»caseها literal هستند؛ متدها operation
bind‌کردن contract به پیاده‌سازی در service providerاتصال component (توپ و سوکت)container همان سیم‌کشی روی نمودار component است
پوشهٔ ماژول / package ComposerPackagerequire در composer.json یک وابستگی package است

Go ​

مثال: checkout از روی نمودارها ​

order.go همان نمودار کلاس (Money، OrderLine، Order) و ماشین حالت (یک جدول گذار به‌علاوهٔ یک guard) است. شمارهٔ سطر qualifier است و Lines []OrderLine همان composition.

go
// Package checkout is the code behind the class and state machine
// diagrams of the UML chapter: every type here is one box on the
// class diagram, and Status/Fire are the state machine.
package checkout

import (
	"errors"
	"fmt"
)

// Money is a value object: two Money values with the same fields are equal.
// UML: «dataType» Money, no identity.
type Money struct {
	Cents    int64
	Currency string
}

// Add returns a new Money; Money is immutable.
func (m Money) Add(o Money) Money {
	return Money{Cents: m.Cents + o.Cents, Currency: m.Currency}
}

// Times multiplies the amount by a quantity.
func (m Money) Times(n int) Money {
	return Money{Cents: m.Cents * int64(n), Currency: m.Currency}
}

// OrderLine is a part of an Order (composition, filled diamond):
// it has no life outside its order and is deleted with it.
type OrderLine struct {
	LineNo    int // qualifier: Order[lineNo] -> 0..1 OrderLine
	SKU       string
	Qty       int
	UnitPrice Money
}

// Subtotal is a derived attribute (/subtotal in UML).
func (l OrderLine) Subtotal() Money { return l.UnitPrice.Times(l.Qty) }

// Status is the state of the Order state machine diagram.
type Status string

// The states, in the order they appear on the diagram.
const (
	Pending  Status = "pending"
	Reserved Status = "reserved"
	Paid     Status = "paid"
	Shipped  Status = "shipped"
	Canceled Status = "canceled"
)

// Event is a trigger on a transition.
type Event string

// Triggers of the Order state machine.
const (
	StockReserved Event = "stockReserved"
	PaymentOK     Event = "paymentCaptured"
	PaymentFailed Event = "paymentDeclined"
	Dispatch      Event = "dispatched"
	Cancel        Event = "cancel"
)

// transitions is the state machine as a table: source --trigger--> target.
// Anything missing from the table is an illegal transition.
var transitions = map[Status]map[Event]Status{
	Pending:  {StockReserved: Reserved, Cancel: Canceled},
	Reserved: {PaymentOK: Paid, PaymentFailed: Canceled},
	Paid:     {Dispatch: Shipped},
}

// ErrIllegalTransition is returned when a trigger has no transition
// from the current state.
var ErrIllegalTransition = errors.New("illegal transition")

// Order is the aggregate root. Lines are owned by composition;
// CustomerID is a plain association by identity, not by pointer.
type Order struct {
	ID         string
	CustomerID string
	Lines      []OrderLine
	Status     Status
}

// NewOrder is the «create» message on the sequence diagram.
func NewOrder(id, customerID string) *Order {
	return &Order{ID: id, CustomerID: customerID, Status: Pending}
}

// AddLine appends a line; the guard keeps lines immutable after reservation.
func (o *Order) AddLine(sku string, qty int, price Money) error {
	if o.Status != Pending {
		return fmt.Errorf("add line in state %s: %w", o.Status, ErrIllegalTransition)
	}
	o.Lines = append(o.Lines, OrderLine{LineNo: len(o.Lines) + 1, SKU: sku, Qty: qty, UnitPrice: price})
	return nil
}

// Total is the derived attribute /total : Money.
func (o *Order) Total() Money {
	total := Money{Currency: "EUR"}
	for _, l := range o.Lines {
		total = total.Add(l.Subtotal())
	}
	return total
}

// Fire applies a trigger. Guard: [lines not empty] on stockReserved.
func (o *Order) Fire(e Event) error {
	if e == StockReserved && len(o.Lines) == 0 {
		return fmt.Errorf("%s with no lines: %w", e, ErrIllegalTransition)
	}
	next, ok := transitions[o.Status][e]
	if !ok {
		return fmt.Errorf("%s --%s-->?: %w", o.Status, e, ErrIllegalTransition)
	}
	o.Status = next
	return nil
}

ports.go interfaceهای موردنیاز نمودار component را نگه می‌دارد. هیچ جای package نمی‌گوید کدام typeها آن‌ها را عرضه می‌کنند.

go
package checkout

import "context"

// The interfaces below are the provided/required interfaces of the
// component diagram (lollipop on the adapter, socket on the service).
// No Go type says "implements": satisfaction is implicit.

// PaymentGateway is required by Service and provided by a PSP adapter.
type PaymentGateway interface {
	Charge(ctx context.Context, orderID string, amount Money) (paymentID string, err error)
}

// Inventory is required by Service and provided by the inventory adapter.
type Inventory interface {
	Reserve(ctx context.Context, orderID string, lines []OrderLine) error
	Release(ctx context.Context, orderID string) error
}

// Orders is the repository port.
type Orders interface {
	Save(ctx context.Context, o *Order) error
}

// Publisher sends domain events (asynchronous messages on the sequence diagram).
type Publisher interface {
	Publish(ctx context.Context, topic string, payload any) error
}

service.go همان نمودار sequence است، هر پیام یک دستور، شامل fragment alt و انتشار ناهم‌گام.

go
package checkout

import (
	"context"
	"fmt"
)

// Service is the «control» lifeline of the checkout sequence diagram.
// It depends on four interfaces (dashed «use» arrows on the class diagram).
type Service struct {
	Orders    Orders
	Inventory Inventory
	Payments  PaymentGateway
	Events    Publisher
}

// Item is one requested line in a PlaceOrder command.
type Item struct {
	SKU   string
	Qty   int
	Price Money
}

// PlaceOrder follows the sequence diagram message by message.
func (s *Service) PlaceOrder(ctx context.Context, id, customerID string, items []Item) (*Order, error) {
	o := NewOrder(id, customerID) // create message
	for _, it := range items {
		if err := o.AddLine(it.SKU, it.Qty, it.Price); err != nil {
			return nil, err
		}
	}
	// 1: reserve stock (synchronous call, filled arrow head)
	if err := s.Inventory.Reserve(ctx, o.ID, o.Lines); err != nil {
		return nil, fmt.Errorf("reserve: %w", err)
	}
	if err := o.Fire(StockReserved); err != nil {
		return nil, err
	}
	// 2: charge; the alt fragment has two operands
	if _, err := s.Payments.Charge(ctx, o.ID, o.Total()); err != nil {
		// [declined]: compensate, then cancel
		_ = s.Inventory.Release(ctx, o.ID)
		_ = o.Fire(PaymentFailed)
		_ = s.Orders.Save(ctx, o)
		return o, fmt.Errorf("charge: %w", err)
	}
	// [captured]
	if err := o.Fire(PaymentOK); err != nil {
		return nil, err
	}
	if err := s.Orders.Save(ctx, o); err != nil {
		return nil, err
	}
	// 3: asynchronous message (open arrow head): fire and forget
	_ = s.Events.Publish(ctx, "order.paid", map[string]any{"id": o.ID, "total": o.Total().Cents})
	return o, nil
}

memory.go یک adapter است که Orders را به‌طور ضمنی برآورده می‌کند؛ ادعای زمان کامپایل تنها رد مکتوب پیکان realization است.

go
package checkout

import (
	"context"
	"sync"
)

// MemoryOrders is an in-memory adapter. It never says "implements Orders",
// yet umlgen draws `Orders <|.. MemoryOrders`, because its method set
// satisfies the interface. The compile-time assertion below is the only
// place the relationship is written down.
type MemoryOrders struct {
	mu   sync.Mutex
	byID map[string]Order
}

var _ Orders = (*MemoryOrders)(nil)

// Save stores a copy of the order.
func (m *MemoryOrders) Save(_ context.Context, o *Order) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.byID == nil {
		m.byID = make(map[string]Order)
	}
	m.byID[o.ID] = *o
	return nil
}

نگاه Go ​

ساختار را تولید کنید، رفتار را دستی بنویسید. نماهای کلاس و package یک ماژول Go از روی کد قابل تولیدند: go list -deps و go list -f با یک قالب imports نمودار package را می‌دهند؛ go/types فیلدها، method setها و برآوردن interface را می‌دهد. مولد این فصل PlantUML چاپ می‌کند:

go
// Command umlgen reads one Go package and prints a PlantUML class diagram.
// It makes the Go/UML mismatch explicit. Exported identifiers become +
// (public) and unexported ones ~ (package), because Go visibility is per
// package, not per type. Interface satisfaction is implicit, so
// realizations are computed with types.Implements instead of being read
// from an "implements" keyword. A value or slice field of a local type
// becomes composition (*--); an interface or pointer field becomes an
// association (-->).
//
// Usage:
//
//	go run ./cmd/umlgen ./checkout > checkout.puml
package main

import (
	"fmt"
	"go/ast"
	"go/importer"
	"go/parser"
	"go/token"
	"go/types"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: umlgen <package-dir>")
		os.Exit(2)
	}
	pkg, err := load(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Print(render(pkg))
}

func load(dir string) (*types.Package, error) {
	fset := token.NewFileSet()
	paths, err := filepath.Glob(filepath.Join(dir, "*.go"))
	if err != nil {
		return nil, err
	}
	var files []*ast.File
	for _, p := range paths {
		if strings.HasSuffix(p, "_test.go") {
			continue
		}
		f, err := parser.ParseFile(fset, p, nil, 0)
		if err != nil {
			return nil, err
		}
		files = append(files, f)
	}
	if len(files) == 0 {
		return nil, fmt.Errorf("no Go files in %s", dir)
	}
	conf := types.Config{Importer: importer.ForCompiler(fset, "source", nil)}
	return conf.Check(files[0].Name.Name, fset, files, nil)
}

func vis(name string) string {
	if token.IsExported(name) {
		return "+"
	}
	return "~"
}

func short(t types.Type, pkg *types.Package) string {
	return types.TypeString(t, types.RelativeTo(pkg))
}

func render(pkg *types.Package) string {
	var b, rel strings.Builder
	scope := pkg.Scope()
	names := scope.Names()
	sort.Strings(names)
	var ifaces []*types.Named
	for _, n := range names {
		if tn, ok := scope.Lookup(n).(*types.TypeName); ok {
			if named, ok := tn.Type().(*types.Named); ok && types.IsInterface(named) {
				ifaces = append(ifaces, named)
			}
		}
	}
	fmt.Fprintf(&b, "@startuml\npackage %s {\n", pkg.Name())
	for _, n := range names {
		tn, ok := scope.Lookup(n).(*types.TypeName)
		if !ok {
			continue
		}
		named, ok := tn.Type().(*types.Named)
		if !ok {
			continue
		}
		switch u := named.Underlying().(type) {
		case *types.Interface:
			fmt.Fprintf(&b, "  interface %s {\n", n)
			for i := 0; i < u.NumMethods(); i++ {
				m := u.Method(i)
				fmt.Fprintf(&b, "    %s%s%s\n", vis(m.Name()), m.Name(), strings.TrimPrefix(short(m.Type(), pkg), "func"))
			}
			b.WriteString("  }\n")
			continue
		case *types.Struct:
			fmt.Fprintf(&b, "  class %s {\n", n)
			for i := 0; i < u.NumFields(); i++ {
				f := u.Field(i)
				fmt.Fprintf(&b, "    %s%s : %s\n", vis(f.Name()), f.Name(), short(f.Type(), pkg))
				relate(&rel, n, f.Type(), pkg)
			}
		default:
			fmt.Fprintf(&b, "  class %s <<%s>> {\n", n, short(u, pkg))
		}
		ms := types.NewMethodSet(types.NewPointer(named))
		for i := 0; i < ms.Len(); i++ {
			m := ms.At(i).Obj()
			fmt.Fprintf(&b, "    %s%s%s\n", vis(m.Name()), m.Name(), strings.TrimPrefix(short(m.Type(), pkg), "func"))
		}
		b.WriteString("  }\n")
		for _, it := range ifaces {
			iface := it.Underlying().(*types.Interface)
			if iface.NumMethods() > 0 && types.Implements(types.NewPointer(named), iface) {
				fmt.Fprintf(&rel, "%s <|.. %s\n", it.Obj().Name(), n)
			}
		}
	}
	b.WriteString("}\n")
	b.WriteString(rel.String())
	b.WriteString("@enduml\n")
	return b.String()
}

// relate turns a field type into a UML relationship line.
func relate(w *strings.Builder, owner string, t types.Type, pkg *types.Package) {
	mult := "1"
	if s, ok := t.(*types.Slice); ok {
		t, mult = s.Elem(), "0..*"
	}
	ptr := false
	if p, ok := t.(*types.Pointer); ok {
		t, ptr = p.Elem(), true
	}
	named, ok := t.(*types.Named)
	if !ok || named.Obj().Pkg() != pkg {
		return
	}
	target := named.Obj().Name()
	switch {
	case types.IsInterface(named) || ptr:
		fmt.Fprintf(w, "%s --> \"%s\" %s\n", owner, mult, target)
	default:
		fmt.Fprintf(w, "%s *-- \"%s\" %s\n", owner, mult, target)
	}
}

روی package مربوط به checkout که اجرا شود، Orders <|.. MemoryOrders، Order *-- "0..*" OrderLine و Service --> "1" PaymentGateway را چاپ می‌کند: پیکان‌های نمودار دستی، این بار مشتق از کد. رفتار را نمی‌شود همین‌طور مشتق کرد، پس از ماشین حالت با تستی محافظت می‌شود که متن PlantUML آن را parse و با جدول گذار مقایسه می‌کند:

go
package checkout

import (
	"regexp"
	"strings"
	"testing"
)

// stateDiagram is the PlantUML source of the Order state machine (top level
// only). The test fails when code and diagram drift apart, in either direction.
const stateDiagram = `
@startuml
[*] --> Pending
Pending --> Reserved : stockReserved
Pending --> Canceled : cancel
Reserved --> Paid : paymentCaptured
Reserved --> Canceled : paymentDeclined
Paid --> Shipped : dispatched
Shipped --> [*]
Canceled --> [*]
@enduml
`

var edge = regexp.MustCompile(`^(\w+) --> (\w+) : (\w+)$`)

func TestCodeMatchesStateDiagram(t *testing.T) {
	drawn := map[string]bool{}
	for _, line := range strings.Split(stateDiagram, "\n") {
		if m := edge.FindStringSubmatch(strings.TrimSpace(line)); m != nil {
			drawn[strings.ToLower(m[1])+"-"+m[3]+"-"+strings.ToLower(m[2])] = true
		}
	}
	coded := map[string]bool{}
	for from, out := range transitions {
		for ev, to := range out {
			coded[string(from)+"-"+string(ev)+"-"+string(to)] = true
		}
	}
	for k := range drawn {
		if !coded[k] {
			t.Errorf("drawn but not coded: %s", k)
		}
	}
	for k := range coded {
		if !drawn[k] {
			t.Errorf("coded but not drawn: %s", k)
		}
	}
}

func TestGuardBlocksEmptyOrder(t *testing.T) {
	o := NewOrder("o-1", "c-1")
	if err := o.Fire(StockReserved); err == nil {
		t.Fatal("guard [lines not empty] did not hold")
	}
}

فرمان demo اجرای خودش را به شکل خط‌های sequence در PlantUML چاپ می‌کند، پس می‌توانید آنچه کد واقعاً انجام داده را رندر و با نمودار طراحی‌شده مقایسه کنید:

go
// Command demo runs PlaceOrder against in-memory adapters and prints every
// message as a PlantUML sequence line, so the trace IS a sequence diagram.
//
//	go run ./cmd/demo            # happy path
//	go run ./cmd/demo -decline   # alt [declined] operand
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"

	"academy/uml-diagrams/checkout"
)

type trace struct{}

func (trace) msg(from, to, arrow, text string) { fmt.Printf("%s %s %s : %s\n", from, arrow, to, text) }

type inventory struct{ t trace }

func (i inventory) Reserve(_ context.Context, id string, lines []checkout.OrderLine) error {
	i.t.msg("Service", "Inventory", "->", fmt.Sprintf("reserve(%s, %d lines)", id, len(lines)))
	i.t.msg("Inventory", "Service", "-->", "ok")
	return nil
}

func (i inventory) Release(_ context.Context, id string) error {
	i.t.msg("Service", "Inventory", "->", "release("+id+")")
	return nil
}

type payments struct {
	t       trace
	decline bool
}

func (p payments) Charge(_ context.Context, id string, m checkout.Money) (string, error) {
	p.t.msg("Service", "PSP", "->", fmt.Sprintf("charge(%s, %d %s)", id, m.Cents, m.Currency))
	if p.decline {
		p.t.msg("PSP", "Service", "-->", "declined")
		return "", errors.New("card declined")
	}
	p.t.msg("PSP", "Service", "-->", "pay_123")
	return "pay_123", nil
}

type orders struct{ t trace }

func (r orders) Save(_ context.Context, o *checkout.Order) error {
	r.t.msg("Service", "OrderRepo", "->", "save(status="+string(o.Status)+")")
	return nil
}

type bus struct{ t trace }

func (b bus) Publish(_ context.Context, topic string, _ any) error {
	b.t.msg("Service", "Broker", "->>", "publish "+topic)
	return nil
}

func main() {
	decline := flag.Bool("decline", false, "make the PSP decline the card")
	flag.Parse()
	t := trace{}
	svc := &checkout.Service{Orders: orders{t}, Inventory: inventory{t}, Payments: payments{t, *decline}, Events: bus{t}}
	fmt.Println("@startuml")
	t.msg("Client", "Service", "->", "placeOrder(o-1)")
	o, err := svc.PlaceOrder(context.Background(), "o-1", "c-7", []checkout.Item{
		{SKU: "BOOK-1", Qty: 2, Price: checkout.Money{Cents: 1500, Currency: "EUR"}},
		{SKU: "PEN-9", Qty: 1, Price: checkout.Money{Cents: 300, Currency: "EUR"}},
	})
	if err != nil {
		t.msg("Service", "Client", "-->", "error: "+err.Error())
	} else {
		t.msg("Service", "Client", "-->", "201 "+string(o.Status))
	}
	fmt.Println("@enduml")
}

Laravel ​

مثال: همان checkout ​

ماشین حالت به شکل یک backed enum؛ هر case یک حالت است و allowedTransitions() پیکان‌های خروجی را فهرست می‌کند.

php
<?php

namespace App\Enums;

/**
 * The Order state machine diagram as a backed enum.
 * Each case is a state; allowedTransitions() is the set of outgoing arrows.
 */
enum OrderStatus: string
{
    case Pending = 'pending';
    case Reserved = 'reserved';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Canceled = 'canceled';

    /** @return list<self> */
    public function allowedTransitions(): array
    {
        return match ($this) {
            self::Pending => [self::Reserved, self::Canceled],
            self::Reserved => [self::Paid, self::Canceled],
            self::Paid => [self::Shipped],
            self::Shipped, self::Canceled => [], // final states
        };
    }

    public function canTransitionTo(self $next): bool
    {
        return in_array($next, $this->allowedTransitions(), true);
    }
}

model در Eloquent: hasMany و belongsTo همان associationها هستند، مدخل casts() attribute را به enumeration وصل می‌کند و transitionTo() هر پیکانی را که روی نمودار نیست رد می‌کند.

php
<?php

namespace App\Models;

use App\Enums\OrderStatus;
use DomainException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Class diagram: Order "1" *-- "1..*" OrderLine, Order "0..*" --> "1" Customer.
 * The composition is enforced by the foreign key ON DELETE CASCADE,
 * not by Eloquent: hasMany() alone is only an association with multiplicity.
 */
class Order extends Model
{
    protected $fillable = ['customer_id', 'status'];

    protected function casts(): array
    {
        return ['status' => OrderStatus::class];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class);
    }

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    /** Derived attribute /total in cents. */
    public function total(): int
    {
        return (int) $this->lines->sum(fn (OrderLine $l) => $l->qty * $l->unit_price_cents);
    }

    /** One transition of the state machine; illegal arrows throw. */
    public function transitionTo(OrderStatus $next): void
    {
        if (! $this->status->canTransitionTo($next)) {
            throw new DomainException("Illegal transition {$this->status->value} -> {$next->value}");
        }
        $this->status = $next;
        $this->save();
    }
}

نمودار sequence به شکل یک Action. interfaceهای بالای فایل سوکت‌های نمودار component هستند؛ یک service provider آن‌ها را به adapterها bind می‌کند.

php
<?php

namespace App\Checkout;

use App\Enums\OrderStatus;
use App\Events\OrderPaid;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

/** Required interfaces (sockets on the component diagram). */
interface PaymentGateway
{
    /** @throws PaymentDeclined */
    public function charge(int $orderId, int $amountCents): string;
}

interface Inventory
{
    /** @param array<int, array{sku: string, qty: int}> $lines */
    public function reserve(int $orderId, array $lines): void;

    public function release(int $orderId): void;
}

final class PaymentDeclined extends \RuntimeException {}

/**
 * The checkout sequence diagram as an Action: one method per lifeline message.
 */
final class PlaceOrder
{
    public function __construct(
        private readonly Inventory $inventory,
        private readonly PaymentGateway $payments,
    ) {}

    /** @param array<int, array{sku: string, qty: int, unit_price_cents: int}> $items */
    public function handle(int $customerId, array $items): Order
    {
        // «create» message: the order and its lines appear in one transaction
        $order = DB::transaction(function () use ($customerId, $items) {
            $order = Order::create(['customer_id' => $customerId, 'status' => OrderStatus::Pending]);
            $order->lines()->createMany($items);

            return $order;
        });

        // 1: synchronous call
        $this->inventory->reserve($order->id, $order->lines->map->only('sku', 'qty')->all());
        $order->transitionTo(OrderStatus::Reserved);

        // 2: alt [captured] / [declined]
        try {
            $this->payments->charge($order->id, $order->total());
        } catch (PaymentDeclined $e) {
            $this->inventory->release($order->id); // compensation
            $order->transitionTo(OrderStatus::Canceled);
            throw $e;
        }
        $order->transitionTo(OrderStatus::Paid);

        // 3: asynchronous message (open arrow head); listeners may be queued
        OrderPaid::dispatch($order);

        return $order;
    }
}

نگاه Laravel ​

رابطه‌های Eloquent نوع بازگشتی اعلام می‌کنند (HasMany، BelongsTo، BelongsToMany) و همین مهندسی معکوس را ارزان می‌کند: reflection متدهای رابطه را بدون اجرای query پیدا می‌کند و getRelated() کلاس طرف دیگر را نام می‌برد. این فرمان Artisan یک نمودار کلاس Mermaid چاپ می‌کند که می‌توانید در pull request بچسبانید:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Relation;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;

/**
 * php artisan uml:models > docs/models.mmd
 *
 * Reads app/Models, finds relationship methods by their declared return
 * type, and prints a Mermaid classDiagram. Relationships become plain
 * associations with multiplicities: Eloquent cannot tell aggregation from
 * composition; only the foreign key's ON DELETE rule can.
 */
final class UmlModels extends Command
{
    protected $signature = 'uml:models';

    protected $description = 'Print a Mermaid class diagram of the Eloquent models';

    /** Relation class => [multiplicity at this end, multiplicity at the other end] */
    private const MULTIPLICITY = [
        HasMany::class => ['"1"', '"0..*"'],
        HasOne::class => ['"1"', '"0..1"'],
        BelongsTo::class => ['"0..*"', '"1"'],
        BelongsToMany::class => ['"0..*"', '"0..*"'],
    ];

    public function handle(): int
    {
        $this->line('classDiagram');
        foreach (glob(app_path('Models/*.php')) as $file) {
            $class = 'App\\Models\\'.basename($file, '.php');
            $ref = new ReflectionClass($class);
            if (! $ref->isSubclassOf(Model::class) || $ref->isAbstract()) {
                continue;
            }
            $this->line('  class '.$ref->getShortName());
            foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                $this->relationLine($ref, $method);
            }
        }

        return self::SUCCESS;
    }

    private function relationLine(ReflectionClass $ref, ReflectionMethod $method): void
    {
        $type = $method->getReturnType();
        if ($method->class !== $ref->getName()
            || $method->getNumberOfRequiredParameters() > 0
            || ! $type instanceof ReflectionNamedType
            || ! is_subclass_of($type->getName(), Relation::class)) {
            return;
        }
        $kind = $type->getName();
        [$here, $there] = self::MULTIPLICITY[$kind] ?? ['', ''];
        // Building a relation object does not run a query; it only needs the related model.
        $related = $ref->newInstance()->{$method->getName()}()->getRelated();
        $arrow = $kind === BelongsTo::class ? '-->' : '--';
        $this->line(sprintf(
            '  %s %s %s %s %s : %s',
            $ref->getShortName(), $here, $arrow, $there, class_basename($related), $method->getName(),
        ));
    }
}

آنچه نمی‌بیند هم آموزنده است: aggregation در برابر composition در migration زندگی می‌کند (foreignId('order_id')->constrained()->cascadeOnDelete())، نه در model؛ association classها pivotهایی هستند که با withPivot('active', 'created_by') یا ->using(CustomPivot::class) اعلام می‌شوند؛ traitها عنصر UML ندارند. این‌ها را دستی بکشید و بخش تولیدی را تولیدی نگه دارید.

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

مسئلهراه‌حلچطورمزیتهزینه / محدودیت
نمودارها بعد از یک sprint می‌پوسندساختار را تولید کنید، رفتار را تست کنیدumlgen، uml:models، تست فاصلهٔ ماشین حالتنمودار غلط CI را می‌شکندفقط برای آنچه کد بیانش می‌کند کار می‌کند
نمودار همه‌چیز را نشان می‌دهد و هیچ نمی‌گویدهر نمودار یک سؤالعضوها را پنهان کنید، ۵ تا ۹ جعبه، نام فایل = سؤالدر بازبینی خواناستفایل‌های بیشتر و کوچک‌تر
دعوا سر پیکان‌هاتوافق روی شش خط و سه قاعدهcomposition = چرخهٔ عمر؛ dependency = موقت؛ aggregation = پرهیزبازبینی کوتاه‌ترکمی دقت عمداً از دست می‌رود
نمودار غلط برای سؤالجدول انتخابسؤال ترتیب → sequence؛ سؤال مجاز‌بودن → stateبه سؤال واقعی جواب می‌دهدکمی سواد UML لازم دارد
کد Go «کلاس ندارد»نگاشت typeها، method setها و packageهاجدول نگاشت Goنمودار صادق از Goپیکان realization باید محاسبه شود
نمودار معماری سطح‌ها را قاطی می‌کندسطح‌های zoom در C4 برای ساختار، UML برای رفتارUML و C4هر تصویر یک مخاطب دارددو نمادگذاری برای یادگرفتن
تصویرهایی در مخزن که کسی نمی‌تواند ویرایششان کندمنبع متنی، رندر هنگام نیازPlantUML/Mermaid داخل Markdownقابل diff و بازبینیچیدمان خودکار گاهی زشت است

سیستم کامل: checkout از سر تا ته ​

یک سیستم، شش نما، که همه همان کد را توصیف می‌کنند. وقتی به تیم می‌پیوندید به همین ترتیب بخوانیدشان.

نماسؤالتصویرکد
Classسفارش از چه ساخته شده؟پایینcheckout/order.go، Order.php
Sequenceروی «Place order» چه می‌شود؟Sequenceservice.go، PlaceOrder.php
State machineکدام تغییر وضعیت مجاز است؟State machinemap به نام transitions، enum OrderStatus
Activityچه کسی چه می‌کند، چه چیزی موازی اجرا می‌شود؟Activityگردش‌کار / هماهنگی saga
Componentکدام قطعه به کدام interface وصل می‌شود؟Componentports.go، bindingهای service provider
Deploymentچه چیزی کجا اجرا می‌شود؟Deploymentimageهای کانتینر، manifestهای k8s
Customer- id : CustomerId- email : String«entity»Order- id : OrderId- status : OrderStatus+ /total : Money+ addLine(sku, qty, price)+ fire(e : Event)lineNoOrderLine- sku : String- qty : Integer {qty > 0}- unitPrice : Money+ /subtotal() : Money0..1linesProduct- sku : String- price : Money0..*1«enumeration»OrderStatusPendingReservedPaidShippedCanceledstatus10..*Payment- amount : Money{abstract}10..*CardPayment- last4 : StringWalletPayment- provider : String«control»CheckoutService+ placeOrder(cmd)«interface»PaymentGateway+ charge(o, amt)StripeGateway- apiKey : Secret«create»«use»Filled diamond = composition, qualified by lineNo; the service depends only on the interface.

نمودار کلاس checkout: Customer یک به چند Order؛ Order سطرهایش را با composition (لوزی توپر) و از طریق qualifier lineNo در اختیار دارد؛ OrderLine به یک Product اشاره می‌کند؛ Order از enumeration OrderStatus استفاده می‌کند؛ Payment انتزاعی است و CardPayment و WalletPayment آن را تعمیم می‌دهند؛ CheckoutService سفارش را «create» می‌کند و فقط به interface PaymentGateway وابسته است که StripeGateway آن را تحقق می‌بخشد.

نمودار کلاس شِما (schema) را هم تعیین می‌کند. هر انتخاب نمادگذاری به یک قاعدهٔ مشخص پایگاه‌داده تبدیل می‌شود:

sql
-- Composition (filled diamond): lines die with their order.
-- Qualified association Order[lineNo] -> 0..1 OrderLine: composite unique key.
-- {qty > 0}: a CHECK constraint. «enumeration» OrderStatus: a CHECK list.
CREATE TABLE orders (
  id          BIGSERIAL PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers(id),          -- association 0..* -> 1
  status      TEXT   NOT NULL DEFAULT 'pending'
              CHECK (status IN ('pending','reserved','paid','shipped','canceled'))
);
CREATE TABLE order_lines (
  order_id          BIGINT  NOT NULL REFERENCES orders(id) ON DELETE CASCADE,  -- composition
  line_no           INT     NOT NULL,                                          -- qualifier
  sku               TEXT    NOT NULL REFERENCES products(sku),                 -- association -> 1 Product
  qty               INT     NOT NULL CHECK (qty > 0),                          -- constraint {qty > 0}
  unit_price_cents  BIGINT  NOT NULL,
  PRIMARY KEY (order_id, line_no)
);
-- Association class (Student, Course) -> Enrollment: a join table with its own columns.
CREATE TABLE enrollments (
  student_id BIGINT NOT NULL REFERENCES students(id),
  course_id  BIGINT NOT NULL REFERENCES courses(id),
  grade      TEXT,
  enrolled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (student_id, course_id)
);
-- Generalization Payment <|-- CardPayment, WalletPayment: single table with a type column
-- (or one table per subclass; UML does not decide this, your queries do).
CREATE TABLE payments (
  id       BIGSERIAL PRIMARY KEY,
  order_id BIGINT NOT NULL REFERENCES orders(id),
  kind     TEXT   NOT NULL CHECK (kind IN ('card','wallet')),
  amount_cents BIGINT NOT NULL,
  last4    TEXT,
  provider TEXT
);

این نگاشت روی PostgreSQL، MySQL با InnoDB (راهنمای MySQL: "As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines")، SQL Server و Oracle یکسان است؛ SQLite کلید خارجی را فقط بعد از PRAGMA foreign_keys = ON اعمال می‌کند. پایگاه‌های سندمحور مثل MongoDB، composition را با جاسازی (embedding) سطرها در سند سفارش و association را با ذخیرهٔ شناسه بیان می‌کنند.

UML و مدل C4 ​

مدل C4 "an easy to learn, developer friendly approach to software architecture diagramming" است که روی "A set of hierarchical abstractions - software systems, containers, components, and code." ساخته شده. سازنده‌اش، Simon Brown، دربارهٔ دامنه صریح است: "you don’t need to use all 4 levels of diagram; only those that add value - the system context and container diagrams are sufficient for most software development teams."

1 · System ContextShopPSPclosest UML:Use case / noneCustomer → Shop → Stripe2 · ContainersSPAAPIWorkerDBMQclosest UML:Deployment + componentSPA · API · worker · DB · MQ3 · ComponentsAPI containerCheckoutPSP adapterOrder storeclosest UML:ComponentCheckout · PSP adapter · Store4 · CodeOrder- status+ fire()OrderLine- qtyclosest UML:ClassOrder ◆— OrderLineZoom in left to right. Simon Brown: context and container diagrams are enough for most teams.

تصویر چهار سطح zoom در C4 را از چپ به راست نشان می‌دهد (context، containers، components، code) و زیر هرکدام نزدیک‌ترین نمودار UML را نام می‌برد.

سطح C4نشان می‌دهدمخاطب (سایت C4)نزدیک‌ترین UMLکدام را ترجیح بدهیم؟
System contextآدم‌ها و سیستم‌های اطراف سیستم شما"Everybody, both technical and non-technical people"Use case (actorها + مرز)C4
Containerبرنامه‌ها و انبارهای داده، فناوری‌ها، پروتکل‌هامعمار، توسعه‌دهنده، عملیاتComponent + deploymentC4
Componentcomponentهای درون یک containerمعمار، توسعه‌دهندهComponentهرکدام؛ اگر ماندگار است تولیدی
Codeکلاس‌های درون یک componentتوسعه‌دهندهClassنمودار کلاس UML، تولیدشده توسط IDE
پشتیبان: dynamicتعامل‌های شماره‌دارتوسعه‌دهندهCommunication / sequencesequence در UML
پشتیبان: deploymentنگاشت containerها به زیرساختعملیاتDeploymentهرکدام
(هیچ)حالت‌های یک موجودیتتوسعه‌دهنده، محصولState machineUML (C4 چیزی ندارد)

"Unfortunately, UML usage seems to be in decline, and many teams have reverted to using ad hoc boxes and lines diagrams once again." — C4 model FAQ، c4model.com

تقسیم کاربردی: C4 برای نقشهٔ ایستای معماری، UML برای رفتار و برای ساختار در سطح کد. FAQ خود C4 توصیه می‌کند با نمودارهای state و timing از UML تکمیلش کنید، و می‌گوید برای مستندکردن "a library, framework or SDK, you might be better off using something like UML." Mermaid از C4 پشتیبانی می‌کند (C4Context، C4Container، C4Component، C4Dynamic، C4Deployment) و "Mermaid's C4 diagram syntax is compatible with plantUML."

mermaid
C4Context
  title Shop, system context
  Person(customer, "Customer", "Buys products")
  System(shop, "Shop", "Catalogue, checkout, orders")
  System_Ext(stripe, "Stripe", "Card payments")
  System_Ext(mail, "E-mail provider")
  Rel(customer, shop, "Places orders", "HTTPS")
  Rel(shop, stripe, "Charges cards", "HTTPS")
  Rel(shop, mail, "Sends confirmations", "SMTP")

انتخاب نمودار ​

موقعیت / سؤالتوصیهتکنیک اضافهدلیل
«چه کسی، به چه ترتیبی، چه کسی را صدا می‌زند؟»Sequenceیک نمودار برای هر سناریو؛ alt برای مسیر شکستترتیب همان محور عمودی است
«آیا این تغییر وضعیت مجاز است؟»State machineتست فاصله در برابر جدول گذار کدپیکان‌های غایب همان قاعده‌ها هستند
«این دامنه از چه ساخته شده؟»Class (۵ تا ۹ جعبه)نمودار شیء برای یک مثال پیچیدهmultiplicity و چرخهٔ عمر صریح‌اند
«کدام ماژول اجازه دارد کدام را import کند؟»Packageتست معماری؛ internal/ در Goپیکان‌ها قاعدهٔ قابل‌اجبار می‌شوند
«درزهای تست/تعویض کجاست؟»Component با توپ و سوکتfake برای هر interface موردنیازports و adapterها را نشان می‌دهد
«چه چیزی کجا اجرا می‌شود؟»Deployment، یکی برای هر محیطپروتکل و port را برچسب بزنیدحادثه‌ها روی خط‌ها رخ می‌دهند
«کل سیستم چیست و چه کسی از آن استفاده می‌کند؟»C4 context + containerروی یک صفحه نگهش داریدخوانندهٔ غیرفنی
«چه کسی در چند تیم چه می‌کند، با گام‌های موازی؟»Activity با swimlanefork/join برای کار موازیهم‌زمانی و مالکیت دیده می‌شود
«هدف‌های کاربر چیست؟»متن use case (+ یک نمودار)story با معیار پذیرشنمودار تنها کم می‌گوید
timeout و مدتTiming (PlantUML) یا state machine با after()زمان محور است
توضیح طراحی در PRبلوک Mermaidروی GitHub رندر می‌شودبازبین ابزار لازم ندارد
blueprint تحت مقرراتابزار کامل UML، خروجی XMIبازبینی مدلکامل‌بودن همان نیازمندی است

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

UML با عوض‌کردن اینکه کدام نمودار بار اصلی را می‌کشد مقیاس‌پذیر می‌شود: درون یک فرایند نمودار کلاس و state مهم‌ترین‌اند؛ بین فرایندها نمودار sequence و deployment.

یکپارچه (Monolith): یک فرایند، یک پایگاه‌داده ​

چطور دیده می‌شود: یک نمودار کلاس از دامنه، یک state machine برای هر موجودیت دارای چرخهٔ عمر، یک نمودار sequence برای هر use case مهم. همه‌چیز فراخوانی متد است، پس نمودارهای sequence بیشتر پیکان هم‌گام دارند.

ساده‌ترین استفادهٔ درست: پوشهٔ docs/diagrams/ با سه فایل برای هر حوزه (<area>-class.puml، <area>-states.puml، <area>-<usecase>.puml) و هر جا ممکن است نمودار کلاس را تولید کنید.

مثال (ساده): یک وبلاگ: Post *-- Comment، Post --> Author، ماشین حالت Draft → Published → Archived.

مثال (پیچیده): checkout همین صفحه در یک برنامهٔ Laravel: Action به نام PlaceOrder، enum OrderStatus، modelهای Eloquent؛ fork نمودار activity به Bus::batch([...])->then(...) تبدیل می‌شود.

modular monolith و چند پایگاه‌داده ​

چطور دیده می‌شود: نمودار package مهم‌ترین تصویر می‌شود: یک package برای هر ماژول، پیکان فقط از طریق interfaceهای منتشرشده، و یک نمودار component برای interfaceهای عرضه‌شده و موردنیاز هر ماژول. هر ماژول مالک جدول‌های خودش است؛ نمودار کلاس در مرز ماژول می‌ایستد و به موجودیت‌های ماژول‌های دیگر فقط با شناسه اشاره می‌کند (association به یک type شناسه، نه به کلاس).

text
     Module boundary rule                         UML expression
1    checkout may call payments                    checkout ..> payments «use» (package diagram)
2    only through PaymentGateway                   socket on Checkout, lollipop on Payments (component)
3    checkout stores customer_id, not Customer     attribute customerId : CustomerId, no association line
4    payments must not import checkout             no arrow; an architecture test fails if one appears

میکروسرویس‌ها: sequence و deployment بار را می‌کشند ​

آنچه می‌ماند: نمودار component (حالا هر component یک سرویس است)، state machineها (موجودیت‌های هر سرویس)، نمودار کلاس درون هر سرویس. آنچه عوض می‌شود: نمودارهای sequence پیکان ناهم‌گام، fragment par و operand شکست پیدا می‌کنند، چون هر پیکان حالا مستقل می‌تواند شکست بخورد (Distribution of Components). شبکه را بخشی از طراحی بکشید، نه جزئیات پیاده‌سازی.

text
     Checkout saga (choreography) as a sequence
1    checkout-svc ->> broker : OrderPlaced          (async, open head; via outbox)
2    broker ->> inventory-svc : OrderPlaced
3    inventory-svc ->> broker : StockReserved
4    broker ->> payment-svc : StockReserved
5    alt [declined]  payment-svc ->> broker : PaymentFailed ; inventory-svc releases stock
6    every lifeline is a service; every arrow needs a timeout, retry rule and idempotency key

مثال: outbox پیکان ۱ را قابل اعتماد می‌کند؛ صفحهٔ saga مسیر جبرانی را می‌کشد. نمودار container در C4 جای نمودار component قدیمی را به‌عنوان نمای کلی می‌گیرد؛ نمودارهای sequence در UML هر saga را مستند می‌کنند.

دادهٔ توزیع‌شده: replica، کش و region ​

جایی که نمودار می‌شکند: نمودار sequenceی که فقط یک lifeline به نام :Database دارد، تقسیم primary/replica، کش جلوی آن و مرز region را پنهان می‌کند. آن‌ها را lifelineهای جدا بکشید؛ باگ‌ها همان‌جا زندگی می‌کنند.

text
     Read-your-writes bug, drawn honestly
1    Client -> api : POST /orders            -> api -> primary : INSERT (commit)
2    Client -> api : GET /orders/42          -> api -> replica : SELECT  (replica lag 300 ms)
3    replica --> api : not found             -> api --> Client : 404 for an order that exists
4    fix drawn: alt [read after own write within 1 s] api -> primary ; else api -> replica

یک نمودار deployment با regionها، replicaها و nodeهای کش، با برچسب حالت replication (هم‌گام یا ناهم‌گام) و جهت failover، جایش در هر runbook حادثه است. سمت پایگاه‌دادهٔ این موضوع در Replication & Failover است؛ در کش‌های مبتنی بر Redis، کش را lifeline جداگانه بکشید و TTL را روی پیکان بنویسید.

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

مقیاسساختارروش نمودارکشی
1× (یک تیم، یک برنامه)Monolithclass + state + چند sequence، به شکل Mermaid در Markdown
10× (چند تیم، یک مخزن)Modular monolithنمودار package و component که با تست اجبار می‌شوند؛ نمودار کلاس تولیدی برای هر ماژول
100× (تیم‌ها و سرویس‌های زیاد)سرویس‌ها، regionهاC4 context/container برای هر سیستم، sequence برای هر جریان بین‌سرویسی، deployment برای هر محیط، state machine برای هر aggregate

آزمایشگاه: تولید، رندر و تست نمودار ​

همه‌چیز با Go نصب‌شده و بدون شبکه اجرا می‌شود.

آماده‌سازی.

bash
cd docs/snippets/design/uml-diagrams/go
go vet ./... && go test ./...
# ok  academy/uml-diagrams/checkout

گام ۱: نمودار کلاس را از کد تولید کنید.

bash
go run ./cmd/umlgen ./checkout > /tmp/checkout.puml
grep -E '<\|\.\.|\*--|-->' /tmp/checkout.puml
# Item *-- "1" Money
# Orders <|.. MemoryOrders
# Order *-- "0..*" OrderLine
# Order *-- "1" Status
# OrderLine *-- "1" Money
# Service --> "1" Orders
# Service --> "1" Inventory
# Service --> "1" PaymentGateway
# Service --> "1" Publisher

خروجی را با نمودار کلاس دستی checkout مقایسه کنید. تفاوت‌های مورد انتظار: مولد Status را composition می‌کشد (چون فیلد مقداری است) در حالی که نمودار دستی آن را association به یک enumeration نشان می‌دهد، و مولد نمی‌تواند qualifier را بداند. به ~mu و ~byID روی MemoryOrders هم دقت کنید: export‌نشده یعنی دیدپذیری package.

گام ۲: رندرش کنید. فایل /tmp/checkout.puml را در هر رندرکنندهٔ PlantUML (plug-in محیط توسعه یا سرور PlantUML) بچسبانید. به‌عنوان تمرین، یک flag به نام -mermaid به umlgen اضافه کنید که به‌جایش classDiagram چاپ کند (سرآیند، پوشش package و نحو interface همه عوض می‌شوند) و خروجی را در یک کامنت GitHub بچسبانید.

گام ۳: توالی واقعی را ضبط کنید.

bash
go run ./cmd/demo
# @startuml
# Client -> Service : placeOrder(o-1)
# Service -> Inventory : reserve(o-1, 2 lines)
# Inventory --> Service : ok
# Service -> PSP : charge(o-1, 3300 EUR)
# PSP --> Service : pay_123
# Service -> OrderRepo : save(status=paid)
# Service ->> Broker : publish order.paid
# Service --> Client : 201 paid
# @enduml
go run ./cmd/demo -decline
# ... PSP --> Service : declined
# Service -> Inventory : release(o-1)
# Service -> OrderRepo : save(status=canceled)
# Service --> Client : error: charge: card declined

این دو اجرا همان دو operand در fragment alt هستند. هر دو را رندر کنید و کنار نمودار sequence طراحی‌شده بگذارید.

گام ۴: کاری کنید نمودار build را بشکند. در checkout/order.go به جدول گذار Paid: {Dispatch: Shipped, Cancel: Canceled} را اضافه کنید و go test ./checkout را اجرا کنید. انتظار: coded but not drawn: paid-cancel-canceled. یا پیکان را بکشید (و تصمیم بگیرید چه کسی پول را برمی‌گرداند) یا کد را حذف کنید.

گام ۵: guard را بشکنید. شرط len(o.Lines) == 0 را از Fire بردارید. انتظار: TestGuardBlocksEmptyOrder با پیام "guard [lines not empty] did not hold" شکست می‌خورد.

گام ۶ (Laravel، اختیاری). UmlModels را در یک برنامهٔ Laravel 13 با modelهای Order، OrderLine و Customer ثبت کنید و php artisan uml:models را اجرا کنید. انتظار: خروجی با classDiagram شروع می‌شود و شامل Order "1" -- "0..*" OrderLine : lines و Order "0..*" --> "1" Customer : customer است؛ آن را در توضیح PR بچسبانید تا GitHub رندرش کند.

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

باورواقعیت
UML یک فرایند استنمادگذاری است؛ فرایندها (RUP، agile) جدا هستند
نمودار باید کامل باشدنمودار یک نماست؛ نیامده یعنی «نشان داده نشده»، نه «وجود ندارد»
لوزی توخالی = has-a، توپر = has-a قویهر association یعنی has-a؛ فقط composition معنای چرخهٔ عمر تعریف‌شده دارد
پیکان روی association یعنی جریان دادهیعنی پیمایش‌پذیری (چه کسی به چه کسی می‌رسد)
embedding در Go همان وراثت استcomposition با متدهای ارتقایافته است؛ subtyping ندارد
interfaceهای Go مثل Java کشیده می‌شوندrealization ضمنی است و باید از method setها محاسبه شود
نمودار use case نیازمندی‌ها را ثبت می‌کندسناریوهای متنی ثبت می‌کنند؛ نمودار فهرست مطالب است
نمودار sequence الگوریتم را مستند می‌کندیک رد اجرا را مستند می‌کند؛ نمودار پرشاخه جایش در کد است
ستون status یعنی ماشین حالتفقط اگر جایی گذارهای غیرمجاز رد شوند
C4 جای UML را گرفتC4 معماری ایستا را پوشش می‌دهد؛ رفتار هنوز UML لازم دارد
Mermaid همهٔ UML را رندر می‌کندclass، sequence و state را بومی؛ بقیه تقریبی است
نمودارها همیشه می‌پوسندنمودار تولیدی و نمودار تست‌شده نمی‌پوسد
نمودار communication و sequence اطلاعات متفاوتی دارندهمان تعامل با چیدمان متفاوت

چکیده ​

موضوعبه خاطر بسپارید
خانواده‌ها۷ ساختاری، ۷ رفتاری (۴تا از آن‌ها تعامل)
هفت‌تای روزمرهclass، package، component، deployment، activity، state machine، sequence
Visibility+ public، - private، # protected، ~ package (export‌نشده در Go)
Multiplicity1، 0..1، *، 1..*؛ نیامده ≠ یک
شش خطassociation، aggregation (◇ توخالی)، composition (◆ توپر)، dependency (→ خط‌چین)، generalization (△)، realization (△ خط‌چین)
Compositionجزء حداکثر در یک کل؛ همراهش حذف می‌شود → ON DELETE CASCADE
Association classپیوند داده‌دار → جدول واسط / pivot با ستون
پیکان‌های sequenceتوپر = هم‌گام، باز = ناهم‌گام، خط‌چین = پاسخ/ساختن، X = حذف
Fragmentهاalt، opt، loop، par، break، critical، ref
برچسب transitionevent [guard] / effect
HistoryH سطحی (زیرحالت بالایی)، H* عمیق (پیکربندی کامل)
Componentlollipop = عرضه‌شده، socket = موردنیاز
حالت‌هاsketch (گزینشی)، blueprint (کامل)، programming language (تولیدی)
C4context و container برای همه؛ UML برای رفتار و کد
نمودار به‌مثابهٔ کدمتن در مخزن، رندر در CI، ساختار تولیدی، رفتار تست‌شده

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

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

۱ — دو خانوادهٔ نمودار و از هرکدام دو نمودار نام ببرید. حیاتی ​

پاسخ

پاسخ: ساختاری (class، object، package، component، composite structure، deployment، profile) و رفتاری (use case، activity، state machine، به‌علاوهٔ نمودارهای تعامل: sequence، communication، interaction overview، timing). ببینید ۱۴ نمودار.

۲ — لوزی توپر دقیقاً چه قولی می‌دهد که لوزی توخالی نمی‌دهد؟ مهم ​

پاسخ

پاسخ: جزء در هر لحظه حداکثر به یک کل تعلق دارد و وقتی کل حذف شود جزءهایش هم با آن حذف می‌شوند. معنای shared aggregation "varies by application area and modeler". ببینید نمودار کلاس.

۳ — فیلد export‌نشده در Go باید کدام نماد visibility را بگیرد و چرا؟ حیاتی ​

پاسخ

پاسخ: ~ (package)، چون Go شناسه‌ها را در سطح package پنهان می‌کند نه type؛ هر کدی در همان package می‌تواند از آن استفاده کند. ببینید خواندن Go.

۴ — «سطر سفارش تعداد و قیمت لحظهٔ فروش دارد و Order و Product را به هم وصل می‌کند» را در UML و SQL چطور می‌کشید؟ مهم ​

پاسخ

پاسخ: یک association class به نام OrderLine که با خط‌چین به association بین Order و Product وصل است؛ در SQL یک جدول واسط با ستون‌های خودش (در Laravel یک pivot با withPivot یا pivot model سفارشی). ببینید association class و schema.

۵ — در نمودار sequence فراخوانی هم‌گام را چطور از ناهم‌گام تشخیص می‌دهید؟ حیاتی ​

پاسخ

پاسخ: هم‌گام: خط پر با سر پیکان توپر (و معمولاً یک پاسخ). ناهم‌گام: خط پر با سر پیکان باز. پاسخ‌ها خط‌چین‌اند. ببینید نمودار sequence.

۶ — فرق alt و opt چیست؟ حیاتی ​

پاسخ

پاسخ: alt از بین چند operand دارای guard حداکثر یکی را انتخاب می‌کند؛ opt یک operand دارد که یا رخ می‌دهد یا نه، معادل altی با operand دوم خالی.

۷ — این برچسب transition را بخوانید: paymentDeclined [attempts < 3] / scheduleRetry(). مهم ​

پاسخ

پاسخ: trigger یعنی paymentDeclined، guard یعنی attempts < 3، effect یعنی scheduleRetry(): وقتی رویداد برسد و شرط درست باشد، اثر اجرا و حالت عوض می‌شود. ببینید ماشین حالت.

۸ — از یک حالت مرکب با hold خارج و با H* دوباره وارد می‌شویم. بعد از resume ماشین در چه حالتی است؟ تکمیلی ​

پاسخ

پاسخ: deep history پیکربندی کامل آخرین بازدید را برمی‌گرداند: در هر region متعامد، همان زیرحالت تودرتوی پیش از hold (مثلاً InTransit و Invoiced). shallow history یعنی H فقط زیرحالت‌های سطح بالا را برمی‌گرداند و با پیش‌فرض‌هایشان واردشان می‌شود.

۹ — چرا نمودار use case ضعیف شمرده می‌شود و به‌جایش از چه استفاده می‌کنید؟ مهم ​

پاسخ

پاسخ: نام هدف‌ها را نشان می‌دهد اما ترتیب، داده و مسیر شکست را نه. متن use case (سناریوی اصلی و شاخه‌ها)، user story با معیار پذیرش و نمودار sequence برای جریان‌ها را به کار ببرید. ببینید Use case.

۱۰ — کی نمودار container در C4 را به نمودار deployment در UML ترجیح می‌دهید و کی برعکس؟ مهم ​

پاسخ

پاسخ: container در C4 برای نمای کلی سیستم (برنامه‌ها، انبارهای داده، فناوری‌ها) برای مخاطب گسترده؛ deployment (UML یا C4) برای nodeها، replicaها و مسیرهای شبکهٔ یک محیط، برای عملیات و کار روی حادثه. ببینید UML و C4.

۱۱ — چطور می‌شود جلوی پوسیدن یک نمودار state دستی را گرفت؟ مهم ​

پاسخ

پاسخ: آن را به‌صورت متن در مخزن نگه دارید و تستی اضافه کنید که transitionهای نمودار را parse و در هر دو جهت با جدول گذار کد مقایسه کند. ببینید آزمایشگاه، گام ۴.

واژه‌نامه ​

اصطلاحمعنا
UMLزبان مدل‌سازی یکپارچه (Unified Modeling Language)، استاندارد OMG؛ نسخهٔ جاری 2.5.1 (formal/2017-12-05)
OMGObject Management Group، نهاد استانداردی که مالک UML، OCL، XMI و SysML است
Booch، OMT، OOSEسه روشی که UML یکی‌شان کرد (Booch؛ Object Modeling Technique از Rumbaugh؛ Object-Oriented Software Engineering از Jacobson)
مدل در برابر نمودار (Model vs diagram)مدل عنصرها را نگه می‌دارد؛ نمودار یک نمای گرافیکی از بخشی از آن است
نمودار ساختاری (Structure diagram)عنصرها را "irrespective of time" نشان می‌دهد: class، object، package، component، composite structure، deployment، profile
نمودار رفتاری (Behavior diagram)رفتار پویا را نشان می‌دهد: use case، activity، state machine، نمودارهای تعامل
نمودار تعامل (Interaction diagram)sequence، communication، interaction overview، timing
قاب / سرعنوان (Frame / heading)حاشیهٔ اختیاری با sd، stm، act، cmp، dep، pkg، uc + نام
Classifiermetaclass انتزاعی برای چیزهای دارای feature: class، interface، component، use case…
دیدپذیری (Visibility)+ public، - private، # protected، ~ package
چندی (Multiplicity)تعداد مجاز مقدارها یا شیءهای پیوندخورده، lower..upper
مشتق (Derived، /)محاسبه‌شده از مقدارهای دیگر، مثل /total
انجمن (Association)رابطهٔ ساختاری بین classifierها؛ سرها multiplicity و navigability دارند
پیمایش‌پذیری (Navigability)پیکان باز روی سر association: می‌شود به آن سر به‌طور کارا رسید
تجمیع (Aggregation، shared)لوزی توخالی؛ کل–جزء با معنای نامشخص
ترکیب (Composition، composite)لوزی توپر؛ جزء حداکثر در یک کل، همراه آن حذف می‌شود
وابستگی (Dependency)پیکان خط‌چین؛ client از supplier استفاده می‌کند؛ کلیدواژه‌های «use»، «create»، «import»
تعمیم (Generalization)مثلث توخالی؛ رابطهٔ زیرنوع
تحقق (Realization / interface realization)خط‌چین با مثلث توخالی؛ یک مشخصه را پیاده می‌کند
کلاس انجمنی (Association class)associationی که خودش کلاس است و attribute دارد
مقیدکننده (Qualifier / qualified association)کلید روی سر association که مجموعهٔ پیوندخورده را افراز می‌کند
کلاس انتزاعی (Abstract class)نمونه‌سازی‌نشدنی؛ نام مورب یا {abstract}
Interface«interface»: مجموعه‌ای از operationها که classifier قول عرضه‌شان را می‌دهد
Enumeration«enumeration»: data type با مجموعهٔ ثابتی از literalها
Stereotype / keyword / profileبرچسب‌های داخل گیومه که UML را گسترش می‌دهند (stereotype، از طریق profile) یا درون آن تعریف شده‌اند (keyword)
قید (Constraint)قاعده داخل آکولاد، مثل {qty > 0}، {ordered}
OCLObject Constraint Language (OMG، نسخهٔ 2.4): invariant، پیش‌شرط و پس‌شرط
Instance specificationیک شیء روی نمودار شیء: name : Type زیرخط‌دار، با slotها
Package / «import» / «access» / «merge»فضای نام؛ import عمومی؛ import خصوصی؛ ادغام package
مؤلفه (Component)واحد ماژولار و قابل‌تعویض با interfaceهای عرضه‌شده و موردنیاز
interface عرضه‌شده / موردنیاز (Provided / required)lollipop (توپ) / socket؛ توپ در سوکت = assembly connector
Portنقطهٔ تعامل نام‌دار روی مرز یک classifier
Composite structurepartها، portها و connectorهای درون یک classifier
Node / device / execution environmentمنبع محاسباتی روی نمودار deployment (جعبهٔ سه‌بعدی)
Artifact / «manifest» / communication pathمحصول فیزیکی (binary، image، فایل)؛ artifact یک component را تجسم می‌کند؛ پیوند بین nodeها
Actor / use case / «include» / «extend»نقش بیرونی؛ هدف کاربر؛ استفادهٔ دوبارهٔ اجباری؛ گسترش شرطی در extension point
Action / control flow / object flow / object nodeگام activity؛ یال ترتیب؛ یالی که داده حمل می‌کند؛ نگه‌دارندهٔ داده مثل o : Order [paid]
Initial / activity final / flow finalنقطهٔ شروع؛ هدف تیراندازی که کل activity را تمام می‌کند؛ دایرهٔ ضربدری که یک جریان را تمام می‌کند
Fork / join / decision / mergeشکستن به جریان‌های هم‌زمان / انتظار برای همه / انتخاب با guard / یکی‌کردن بدون انتظار
Activity partition (swimlane)گروهی از nodeها با مالک یا مکان مشترک
State / composite state / region / orthogonal stateوضعیت یک شیء؛ حالت با زیرحالت؛ ظرف زیرحالت‌ها؛ حالت با چند region هم‌زمان
Transition / trigger / guard / effectپیکان بین حالت‌ها؛ رویداد؛ شرط بولی داخل [ ]؛ رفتار بعد از /
entry / do / exitرفتارهای هنگام ورود، در طول ماندن و هنگام خروج از حالت
Pseudostateinitial، choice، junction، fork، join، entry/exit point، terminate، history
Shallow / deep history (H، H*)ورود دوباره به آخرین زیرحالت سطح بالا / به پیکربندی کامل قبلی
Time event / change eventafter(15 min) / when(condition)
Lifelineشرکت‌کننده در تعامل (خط‌چین عمودی)
Execution specification (activation)مستطیل باریک روی lifeline در زمان اجرا
پیام هم‌گام / ناهم‌گام / پاسخسر توپر / سر باز / خط‌چین
Create / destroy (destruction occurrence)پیام خط‌چین با سر باز به lifeline تازه؛ X که lifeline را تمام می‌کند
Lost / found messageارسال معلوم، دریافت نامعلوم / دریافت معلوم، ارسال نامعلوم
Gateسر پیام روی مرز یک interaction یا fragment
Combined fragment / interaction operatorجعبه با alt، opt، loop، par، break، critical، neg، assert، seq، strict، ignore، consider
Interaction use (ref)ارجاع به تعامل دیگر
Communication diagramتعامل کشیده‌شده روی پیوندها با پیام‌های شماره‌دار (در UML 1: collaboration diagram)
Interaction overview / timing diagramactivity از تعامل‌ها / حالت‌ها روی محور زمان
Sketch / blueprint / programming languageسه حالت استفاده از UML از نگاه Fowler
مهندسی رو به جلو / معکوس / رفت‌وبرگشتی (Forward / reverse / round-trip)نمودار → کد / کد → نمودار / هر دو هم‌گام
MDAModel Driven Architecture، رویکرد OMG برای تولید کد از مدل
XMI / UML DIقالب تبادل XML برای مدل‌ها / metamodel تبادل نمودار (Annex B)
PlantUMLابزار متن‌به‌نمودار که بیشتر نمودارهای UML را پوشش می‌دهد (@startuml … @enduml)
Mermaidابزار متن‌به‌نمودار الهام‌گرفته از Markdown که GitHub رندرش می‌کند؛ class، sequence، state، flowchart، C4
نمودار به‌مثابهٔ کد (Diagrams as code)نگه‌داشتن منبع نمودار به‌صورت متن در مخزن و رندر هنگام نیاز
مدل C4نمودارهای context، container، component و code از Simon Brown (+ landscape، dynamic، deployment)
تایپ ساختاری / برآوردن ضمنی interface (Structural typing)در Go، type با داشتن متدهای interface آن را پیاده می‌کند، بدون اعلام
Struct embeddingcomposition در Go که متدهای type جاسازی‌شده را ارتقا می‌دهد؛ subtyping نیست
رابطهٔ EloquenthasOne، hasMany، belongsTo، belongsToMany، morph* در Laravel: association با multiplicity
Pivot / withPivotassociation class در Laravel برای چند-به-چند
ISO/IEC 19501 / 19505انتشار ISO از UML 1.4.x (۲۰۰۵) و UML 2 (۲۰۱۲)

منابع ​

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