<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Андрей Собченюк on Medium]]></title>
        <description><![CDATA[Stories by Андрей Собченюк on Medium]]></description>
        <link>https://medium.com/@cobchenyuk?source=rss-3d6f8818545a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EMKqjOYlyxuRN5GypIDx1Q.png</url>
            <title>Stories by Андрей Собченюк on Medium</title>
            <link>https://medium.com/@cobchenyuk?source=rss-3d6f8818545a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:21:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cobchenyuk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built a Music Product Inside Telegram, Not Just a Player]]></title>
            <link>https://medium.com/@cobchenyuk/i-built-a-music-product-inside-telegram-not-just-a-player-c7251cb479ce?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7251cb479ce</guid>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[min-app]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 12:10:19 GMT</pubDate>
            <atom:updated>2026-10-17T12:10:19.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3De_W4fPQ0nlbZmLFY0kw.png" /></figure><p><em>*One Mini App for several music channels: the catalogue, the player, playlists, the admin workspace, and the boundaries that shaped every part of it.*</em></p><p>The product is built for <a href="https://t.me/triphop_channel"><strong>https://t.me/triphop_channel</strong></a>, a real Telegram music channel.</p><p>The original idea sounded small: a listener opens a music channel in Telegram, taps a button, picks an album, and starts a track.</p><p>That is the visible surface. Behind it is a complete, smaller-scale music product: a catalogue that belongs to several channels, an audio player, personal playlists, an administrative workspace for releases, user presence, and listening statistics. It runs as a Telegram Mini App, which means it inherits Telegram WebView and mobile-OS behaviour whether the product design likes it or not.</p><p>This article is a detailed look at what the product does, how its parts connect, and why some of its most important decisions come from platform limits rather than from the framework choice.</p><h3><strong>The product starts with a channel, not a homepage</strong></h3><p>A conventional music site opens at a neutral URL and asks the visitor where to go. A Telegram Mini App can do better: it starts from a channel, and that channel already carries intent.</p><p>The application supports a network of channels. Each can represent an artist or an editorial selection of releases. Creating a custom frontend for every channel would make the system harder to operate immediately: every player improvement, bug fix, analytics change, or admin update would need to be deployed repeatedly.</p><p>Instead, the channel is mapped to an `artistAlias` in a small configuration file:</p><pre>{<br>  &quot;channels&quot;: {<br>    &quot;-1001234567890&quot;: &quot;artist-alias&quot;,<br>    &quot;channel_username&quot;: &quot;artist-alias&quot;<br>  }<br>}</pre><p>When the Mini App is opened from Telegram, it receives the channel context, resolves the matching artist, and opens the relevant catalogue. The same alias becomes the product’s connective tissue: it appears in routes, API calls, client state, and file paths.</p><p>This gives the listener a focused entry point — open a channel, arrive at the appropriate music — while keeping a single codebase, deployment, and admin workspace for the team.</p><h3><strong>The public catalogue: releases are simple objects with a deliberate lifecycle</strong></h3><p>The listener-facing side contains artists, albums, album art, and tracks. It is intentionally closer to a curated catalogue than an infinite feed.</p><p>Its data is file-based:</p><pre>artists/{artist}/<br>  meta.json<br>  albums/{album}/<br>    meta.json<br>    index.json<br>    cover.jpg<br>    tracks/{track}.mp3<br>    tracks/{track}.meta.json</pre><p>An artist has a name and description. An album has a name, visibility flag, and order. A track has a title, order, visibility flag, duration, and file extension. The separation between media and metadata is important: it lets the catalogue control what is published without renaming or deleting audio files.</p><p>An administrator can prepare a release, upload its cover and tracks, set the desired order, and keep it hidden until it is ready. The public application only exposes content marked visible. That is a basic release workflow, but it is exactly the kind of workflow a music product needs before it needs a heavyweight CMS.</p><p>Routes are also part of the product contract. An album URL stays addressable, so refreshing the page returns the listener to the same album instead of sending them back to a generic home screen.</p><h3><strong>The player: preserving listening context matters more than reproducing a native client</strong></h3><p>The player manages a current track, album, playlist, track list, repeat mode, and play state. It supports the expected music flow: play, pause, previous and next track, seeking, queue navigation, and repeat. Where supported, it also sets Media Session metadata and actions so the surrounding operating system can present the current track correctly.</p><p>There is one important product decision in its persistence model. The selected track and queue are stored in `localStorage`. If a listener reopens the Mini App, they see the same track in a paused state rather than having to find the album and track again.</p><p>This is intentionally persistence of context, not a claim of uninterrupted listening. Telegram Mini Apps run in WebView. On Android and iOS, hiding the app pauses the active track; returning can continue through the same audio element. Telegram Desktop and Telegram for macOS generally behave differently. Screen locking, WebView eviction, and Telegram-client policies can still interrupt audio.</p><p>The player uses Howler on top of HTML5 Audio, which handles the normal web-audio workflow well. But it cannot override the lifecycle of Telegram or a mobile OS. The correct UX response is to make returning easy — not to promise native background playback that the environment cannot guarantee.</p><p>MP3 files are not cached, so the current product does not offer offline playback either. That is a deliberate boundary: audio caches grow quickly, and WebView storage is not a dependable primary storage layer for an offline music promise.</p><h3><strong>Playlists: personal data gets stronger storage guarantees</strong></h3><p>A curated catalogue is mostly editorial. A playlist is personal and mutable.</p><p>Listeners can create playlists, add tracks, reorder them, and remove them. These data live in MongoDB rather than beside the catalogue files, because concurrent updates need more robust guarantees than an edited album index.</p><p>Each successful playlist change also produces a JSON backup for that Telegram user. If the backend starts and MongoDB is missing a user’s playlists, it can restore them from the backup. This is not an attempt to build a universal disaster-recovery platform. It is a useful, inspectable safeguard for a small product: a user’s collection is not opaque or trapped in a single database volume.</p><p>The product also contains donation, contacts, and author pages. Those are separate routes, but the player state remains centralised, so moving through the application does not rebuild the listening context from scratch.</p><h3><strong>The admin panel is part of the product, not maintenance scaffolding</strong></h3><p>A public music app without a workable publishing interface eventually becomes a task for someone with server access. That is not sustainable for a living catalogue.</p><p>The admin workspace provides separate areas for artists and albums, channel configuration, users, playlists, and listening statistics. It supports everyday catalogue work:</p><p>- creating, editing, hiding, reordering, and deleting artists and albums;</p><p>- uploading artist avatars, album covers, and audio tracks;</p><p>- changing a track’s title, visibility, and position in an album;</p><p>- configuring channels and their visual material;</p><p>- viewing users, their approximate presence, playlists, and listening statistics.</p><p>Destructive operations are confirmed in the interface. Release visibility is controlled through metadata rather than by moving files in and out of the public tree. This makes unpublished work possible without adding a separate staging catalogue.</p><p>The server keeps admin and listener boundaries distinct. Administrative routes sit under `/admin/*` and require HTTP Basic Auth with `ADMIN_PASSWORD`. Listener routes use Telegram authentication instead. A public `/health` endpoint remains available for deployment health checks.</p><h3><strong>Trust starts on the server</strong></h3><p>A client browser can claim any user ID. For user-facing routes, the API accepts Telegram WebApp `initData`, validates its signature, and only then extracts the Telegram user identity.</p><p>The validation follows Telegram’s HMAC-SHA256 flow: remove `hash`, sort the remaining parameters, derive a key from `WebAppData` and the bot token, calculate the signature, and compare it with the received hash. Once it succeeds, the Hono request context receives the Telegram user ID and user object.</p><p>Local development has a bypass: `SKIP_TG_AUTH=true` accepts `X-Dev-User-Id`, making it possible to develop outside a real Telegram session. It is intentionally a development-only tool. Enabling it in production would make the user-facing API unsafe.</p><p>The admin panel uses a much smaller security model: Basic Auth, a password in the environment, and a localStorage value so the route guard can make a synchronous decision during reload. It is not enterprise identity management. It is a deliberately constrained administration surface.</p><h3><strong>The analytics describe what the product knows, not what it wishes it knew</strong></h3><p>The project records sessions, online presence, track starts, and aggregated statistics. Their names matter.</p><p>When the Mini App opens, it starts a session. It sends a ping every 30 seconds and attempts a `fetch` request with `keepalive` when the listener leaves. Someone is considered online when their last ping is less than 90 seconds old.</p><p>This is a useful operational approximation. It is not proof that the person is looking at a screen at this moment. A WebView can disappear without a final close request, so exact presence is not available.</p><p>Track analytics have the same boundary. A play is recorded at the first `play`, not at every resume. The dashboard can therefore show starts, unique listeners, popular artists, albums, and tracks. It should not call that data verified listening time or completed listens. Those metrics would need additional information about playback position, active duration, stops, and background state.</p><p>Clear metric definitions are a product feature. They prevent the admin panel from giving an editor more confidence than the underlying events deserve.</p><h3><strong>File storage is transparent — and has a known ceiling</strong></h3><p>The media catalogue is intentionally stored as files. It can be inspected, transferred, and backed up without specialised tooling. That transparency is useful at this scale.</p><p>User sessions and aggregate statistics also use JSON files in `backup/users/`. The statistics store serialises writes within one backend process, protecting `stats.json` from simultaneous play-event writes.</p><p>That qualifier matters: it is a one-process protection, not a distributed locking strategy. Adding multiple backend instances or a significantly larger stream of events means sessions and statistics should move to shared transactional storage. The project treats that as a future architectural boundary, not as a problem to paper over with increasingly clever file writes.</p><h3><strong>The upload limit users see is set by the narrowest layer</strong></h3><p>The backend allows request bodies up to 2 GiB. Nginx, which sits in front of it, sets `client_max_body_size 200m`.</p><p>The product’s real upload limit is therefore 200 MiB. A larger track does not reach the backend at all.</p><p>This is an easy discrepancy to miss when frontend and backend run locally. For media products, upload behaviour belongs to the complete route: reverse proxy, CDN if present, timeouts, application server, processing code, and disk space. A backend limit is not a user-facing capability until the layers before it agree.</p><h3><strong>A smaller product with explicit edges</strong></h3><p>The finished system is not a clone of a large streaming service. It is a focused music product built for a Telegram-native entry point:</p><p>- one application for multiple channel-specific catalogues;</p><p>- artists, albums, covers, tracks, ordering, and staged visibility;</p><p>- a player with queue persistence and standard playback controls;</p><p>- personal playlists with database storage and file backups;</p><p>- a practical admin workspace for running the catalogue;</p><p>- session and listening analytics with explicitly bounded meaning.</p><p>Its limits are equally explicit: Telegram owns launch context, WebView and the OS own part of the audio lifecycle, file-backed data has a scaling ceiling, and infrastructure configuration can constrain product features.</p><p>Those limits did not make the product less useful. Naming them early made it easier to build a product that behaves predictably for both listeners and administrators.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7251cb479ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Cross-Platform Clipboard Sync with E2E Encryption and $0 Server Costs]]></title>
            <link>https://medium.com/@cobchenyuk/how-i-built-a-cross-platform-clipboard-sync-with-e2e-encryption-and-0-server-costs-60cc39d75659?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/60cc39d75659</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Tue, 26 May 2026 23:33:24 GMT</pubDate>
            <atom:updated>2026-05-26T23:33:24.292Z</atom:updated>
            <content:encoded><![CDATA[<p>Disrupting the cloud clipboard market by utilizing the user’s own Firebase instance as a secure backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXXRpLPvsG28s2pn9PKRmQ.png" /><figcaption>How I Built a Cross-Platform Clipboard Sync with E2E Encryption and $0 Server Costs</figcaption></figure><p>Every software engineer working with multiple machines knows the frustration. You have a long terminal log, a complex token, or a secure link on your PC, and you need it on your phone or your second laptop. What do most of us do? We paste it into our personal messenger chats, creating a chaotic trail of temporary data.</p><p>Existing dedicated cloud clipboards either suffer from massive privacy issues (hosting your sensitive clipboard data on their centralized servers) or require rigid local network configurations that completely break outside of your home Wi-Fi.</p><p>To solve this, I engineered <strong>ClipFlow</strong> — a production-ready, cross-platform clipboard synchronization ecosystem with total data sovereignty.</p><p>And the best part? As a solo developer, <strong>my server infrastructure bill is exactly $0</strong>.</p><h3>The Architecture Challenge: Scaling Without Infrastructure</h3><p>Usually, launching a real-time data sync app means configuring WebSockets, maintaining server clusters, and scaling database instances. It’s a financial trap for independent developers.</p><p>I bypassed this completely by utilizing a <strong>Zero-Knowledge Decentralized Infrastructure</strong>.</p><p>Instead of connecting to a centralized backend, ClipFlow prompts users to connect their <strong>own Google Firebase instance</strong>. By deploying a shared Firebase configuration across all their devices simultaneously, the system creates a single, highly isolated personal network.</p><pre>[Device 1: PC] --(Encrypted Payload)--&gt; [User&#39;s Firebase] &lt;-- (Encrypted Payload)-- [Device 2: Mobile]<br>                                              |<br>                                    (Zero Server Load on Us)</pre><p>This model provides two massive advantages:</p><ol><li><strong>Infinite Scaling:</strong> We have zero infrastructure overhead. The user’s network handles its own real-time database state.</li><li><strong>Device Independence:</strong> Users can connect an unlimited number of devices without triggering performance or server-side resource constraints.</li></ol><h3>Security Model: True End-to-End Encryption</h3><p>Using a personal cloud instance doesn’t mean trusting Google blindly. Security is embedded deep into the client-side app layer.</p><p>ClipFlow implements a strict client-side end-to-end encryption system. The entire personal network operates on a single shared password entered manually inside the native apps.</p><ul><li><strong>No Password Transmissions:</strong> The password is physically managed inside the app runtime. It is never stored as an external file and never transmitted over the network.</li><li><strong>Absolute Zero-Knowledge:</strong> Data is encrypted <em>before</em> it leaves the source device. If the passwords on the receiving devices do not match, decryption is physically impossible.</li></ul><p>Even if someone intercepts the database stream, they only see a blob of high-entropy encrypted noise.</p><h3>Tech Stack &amp; Current Roadmap</h3><p>The core application wrapper relies on modern performance tools:</p><ul><li><strong>Landing &amp; Docs:</strong> Built on <strong>Next.js</strong>, fully optimized for multi-language SEO, and deployed on <strong>Vercel</strong>.</li><li><strong>Native Integration:</strong> Low-level OS clipboard listeners that manage local system hooks cleanly in the background.</li></ul><p>Right now, ClipFlow is completely live and <strong>100% free</strong> for unlimited text and link clipboard mirroring.</p><p>Our monetization strategy focuses on a future premium <strong>Paid Pro Subscription</strong> that introduces <strong>seamless, cross-platform file transfers directly through the clipboard</strong> (e.g., copying a photo on your MacBook and instantly pasting it into your Windows PC or Google Pixel). Because our operational server cost is zero, this model scales into pure net profit margin while ensuring free-tier text users never experience service disruption or data limits.</p><h3>Final Thoughts</h3><p>We are launching on Product Hunt today to collect feedback, edge cases, and architectural review from fellow developers.</p><p>If you are tired of centralized apps harvesting your data, you can read our setup documentation and spin up your own instance in less than 5 minutes.</p><ul><li><strong>Live Project &amp; Docs:</strong> <a href="https://webclipflow.vercel.app/">webclipflow.vercel.app</a></li><li><strong>Support the Launch:</strong> Check out our Product Hunt page to see what we are building next!</li></ul><h3>🏷 Tags</h3><p>Software Engineering, Self Hosted, Productivity, Firebase, Web Development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60cc39d75659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Flow: Complete Guide to Development Workflow]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cobchenyuk/git-flow-complete-guide-to-development-workflow-b732bf896a31?source=rss-3d6f8818545a------2"><img src="https://cdn-images-1.medium.com/max/1024/1*4CpKTZ-JNAWknTeqJ8X1ng.png" width="1024"></a></p><p class="medium-feed-snippet">What is Git Flow and Why You Need It</p><p class="medium-feed-link"><a href="https://medium.com/@cobchenyuk/git-flow-complete-guide-to-development-workflow-b732bf896a31?source=rss-3d6f8818545a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cobchenyuk/git-flow-complete-guide-to-development-workflow-b732bf896a31?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b732bf896a31</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[team-development]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 08:14:30 GMT</pubDate>
            <atom:updated>2025-06-27T08:14:30.901Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Git Flow: Повний гайд з робочого процесу розробки]]></title>
            <link>https://medium.com/@cobchenyuk/git-flow-%D0%BF%D0%BE%D0%B2%D0%BD%D0%B8%D0%B9-%D0%B3%D0%B0%D0%B9%D0%B4-%D0%B7-%D1%80%D0%BE%D0%B1%D0%BE%D1%87%D0%BE%D0%B3%D0%BE-%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D1%81%D1%83-%D1%80%D0%BE%D0%B7%D1%80%D0%BE%D0%B1%D0%BA%D0%B8-6aaaf35c04a1?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aaaf35c04a1</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[team-development]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 08:06:47 GMT</pubDate>
            <atom:updated>2025-06-27T08:06:47.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Git Flow: Повний гайд з робочого процесу розробки" src="https://cdn-images-1.medium.com/max/1024/1*uKovWW9SiSdMjIm_Q9qwsA.png" /><figcaption>Git Flow: Повний гайд з робочого процесу розробки</figcaption></figure><h3>Що таке Git Flow і навіщо він потрібен</h3><p>Git Flow — це модель розгалуження Git, яка визначає чіткий процес управління гілками для команд розробки. Створена Вінсентом Дрісеном у 2010 році, ця методологія стала стандартом для проєктів з регулярними релізами та командною розробкою.</p><p><strong>Основні переваги Git Flow:</strong></p><ul><li>Чітке розділення типів гілок за призначенням</li><li>Контрольований процес релізів</li><li>Можливість паралельної розробки різних функцій</li><li>Стабільність головної гілки</li><li>Простота інтеграції з CI/CD</li></ul><p><strong>Коли використовувати Git Flow:</strong></p><ul><li>Команди від 3+ розробників</li><li>Проєкти з регулярними релізами</li><li>Потреба в стабільній production-гілці</li><li>Складні функції, що розробляються паралельно</li></ul><h3>Архітектура гілок у Git Flow</h3><pre>main          ──●────●────●────●────   (production releases)<br>               /      \    \    \<br>develop   ────●────────●────●────●───   (integration branch)<br>             /|        |\   |\   |\<br>feature/    ● |        | ●──● |  | ●   (new features)<br>           /  |        |      |  |  \<br>release/      |        ●──────●  |   <br>             |        /          |   <br>hotfix/      |       ●───────────●   (urgent fixes)<br>             |      /</pre><h3>Типи гілок та їх призначення</h3><p>Тип гілки Призначення Створюється з Зливається в Час життя main Production код - - Постійна develop Інтеграція функцій main - Постійна feature/* Нові функції develop develop Тимчасова release/* Підготовка релізу develop main + develop Тимчасова hotfix/* Критичні виправлення main main + develop Тимчасова</p><h3>Початкове налаштування Git Flow</h3><h3>Установка git-flow</h3><pre># macOS<br>brew install git-flow</pre><pre># Ubuntu/Debian<br>sudo apt-get install git-flow</pre><pre># Windows (через Git Bash)<br>wget -q -O - --no-check-certificate <a href="https://github.com/nvie/gitflow/raw/develop/contrib/gitflow-installer.sh">https://github.com/nvie/gitflow/raw/develop/contrib/gitflow-installer.sh</a> | bash</pre><h3>Ініціалізація в проєкті</h3><pre>git flow init</pre><p>При ініціалізації Git Flow запитає налаштування:</p><pre>Branch name for production releases: [main] <br>Branch name for &quot;next release&quot; development: [develop]</pre><pre>How to name your supporting branch prefixes?<br>Feature branches? [feature/]<br>Release branches? [release/]<br>Hotfix branches? [hotfix/]<br>Support branches? [support/]<br>Version tag prefix? []</pre><h3>Гілка розробки та головна гілка</h3><p>У цьому робочому процесі для реєстрації історії проекту замість однієї гілки main використовуються дві гілки. У головній гілці <strong>main</strong> зберігається офіційна історія релізу, а гілка розробки <strong>develop</strong> призначена для об’єднання всіх функцій. Крім того, для зручності рекомендується присвоювати всім комітам у гілці <strong>main</strong> номер версії.</p><h3>Створення develop гілки</h3><p>Перший крок робочого процесу полягає у створенні гілки <strong>develop</strong> від стандартної гілки <strong>main</strong>:</p><pre>git branch develop<br>git push -u origin develop</pre><h3>З git-flow розширенням</h3><pre>git flow init</pre><p>Після ініціалізації:</p><pre>$ git branch<br>* develop<br>  main</pre><p>У цій гілці зберігатиметься повна історія проєкту, а в гілці <strong>main</strong> — скорочена. Тепер іншим розробникам слід клонувати центральний репозиторій і створити гілку відстеження для гілки <strong>develop</strong>.</p><h3>Функціональні гілки (feature)</h3><p>З гілки develop створюються гілки feature. Коли робота над гілкою feature завершується, вона зливається в гілку develop.</p><h3>Життєвий цикл feature гілки</h3><pre>graph LR<br>    A[develop] --&gt; B[feature/user-auth]<br>    B --&gt; C[Розробка функції]<br>    C --&gt; D[Тестування]<br>    D --&gt; E[Code Review]<br>    E --&gt; F[Merge в develop]<br>    F --&gt; G[Видалення feature гілки]</pre><h3>Команди для роботи з feature</h3><p><strong>Створення функціональної (feature) гілки</strong></p><pre>git flow feature start feature_branch</pre><p><strong>Робота над функцією</strong></p><pre># Додавання змін<br>git add .<br>git commit -m &quot;feat: implement user authentication&quot;</pre><pre># Періодичне оновлення з develop<br>git flow feature rebase feature_branch</pre><p><strong>Закінчення роботи з функціональною (feature) гілкою</strong></p><pre>git flow feature finish feature_branch</pre><p><strong>Публікація (feature)</strong></p><pre>git flow feature publish feature_branch</pre><p><strong>Отримання опублікованої (feature)</strong></p><pre>git flow feature pull origin MYFEATURE</pre><p><strong>Відстежувати (feature) в репозиторії origin</strong></p><pre>git flow feature track MYFEATURE</pre><h3>Практичний приклад</h3><pre># Початок роботи над новою функцією<br>git flow feature start user-profile</pre><pre># Розробка...<br>echo &quot;User profile component&quot; &gt; user-profile.js<br>git add user-profile.js<br>git commit -m &quot;feat: add user profile component&quot;</pre><pre>echo &quot;User profile styles&quot; &gt; user-profile.css<br>git add user-profile.css<br>git commit -m &quot;style: add user profile styling&quot;</pre><pre># Завершення роботи (автоматично зливається в develop)<br>git flow feature finish user-profile</pre><h3>Гілки випуску (release)</h3><p>З гілки develop створюється гілка release. Коли робота над гілкою release завершується, вона зливається з гілками develop і main.</p><h3>Правила роботи з release гілками</h3><ol><li><strong>Нові функції додати більше не можна</strong> — допускається лише виправлення багів, створення документації та вирішення інших завдань, пов’язаних із релізом</li><li><strong>Коли підготовка до постачання завершується</strong>, гілка release зливається з main і їй присвоюється номер версії</li><li><strong>Бажано одразу публікувати гілку релізу</strong> після створення, щоб дозволити іншим розробникам виконувати коміти в гілку релізу</li></ol><h3>Команди для роботи з release</h3><p><strong>Створення випуску (release) гілки</strong></p><pre>git flow release start &#39;0.1.0&#39;</pre><p><strong>Робота над релізом</strong></p><pre># Виправлення багів<br>git add .<br>git commit -m &quot;fix: resolve login issue&quot;</pre><pre># Оновлення документації<br>git commit -m &quot;docs: update changelog for v0.1.0&quot;</pre><pre># Оновлення версії<br>git commit -m &quot;bump: version 0.1.0&quot;</pre><p><strong>Закінчення роботи з випуском (release) гілкою</strong></p><pre>git flow release finish &#39;0.1.0&#39;</pre><p><strong>Публікація випуску (release)</strong></p><pre>git flow release publish &#39;0.1.0&#39;</pre><p><strong>Відстежувати віддалений випуску (release)</strong></p><pre>git flow release track &#39;0.1.0&#39;</pre><p><strong>❗️ Не забудьте відправити зміни в тегах</strong></p><pre>git push --tags</pre><h3>Checklist для release</h3><ul><li>[ ] Всі функції з develop інтегровані</li><li>[ ] Пройдені всі тести</li><li>[ ] Оновлена документація</li><li>[ ] Оновлений CHANGELOG.md</li><li>[ ] Версія оновлена в package.json</li><li>[ ] Проведене QA тестування</li></ul><h3>Гілки виправлення (hotfix)</h3><p>Якщо в гілці main виявляється критична проблема, з main створюється гілка hotfix. Коли робота над гілкою hotfix завершується, вона зливається з гілками develop і main.</p><h3>Коли використовувати hotfix</h3><ul><li>Критичні баги в production</li><li>Проблеми безпеки</li><li>Невідкладні виправлення</li><li>Помилки, що впливають на роботу користувачів</li></ul><h3>Команди для роботи з hotfix</h3><p><strong>Створення виправлення (hotfix) гілки</strong></p><pre>git flow hotfix start hotfix_branch</pre><p><strong>Приклад роботи з hotfix</strong></p><pre># Створення hotfix для критичної помилки<br>git flow hotfix start security-patch</pre><pre># Виправлення проблеми<br>git add .<br>git commit -m &quot;fix: resolve security vulnerability&quot;</pre><pre># Завершення hotfix (зливається в main і develop)<br>git flow hotfix finish security-patch</pre><pre># Відправлення тегів<br>git push --tags</pre><p><strong>Закінчення роботи з виправленням (hotfix) гілкою</strong></p><pre>git flow hotfix finish hotfix_branch</pre><h3>Альтернативи і порівняння</h3><h3>GitHub Flow vs Git Flow</h3><p>Аспект Git Flow GitHub Flow Складність Висока Низька Кількість гілок 5 типів 2 типи Релізний цикл Заплановані релізи Continuous deployment Команда Великі команди Малі/середні команди</p><h3>Коли НЕ використовувати Git Flow</h3><ul><li>Continuous deployment</li><li>Малі команди (1–2 розробники)</li><li>Проєкти без регулярних релізів</li><li>Проста структура проєкту</li></ul><h3>Практичні поради та найкращі практики</h3><h3>Конвенції іменування гілок</h3><pre># Feature гілки<br>feature/user-authentication<br>feature/payment-integration<br>feature/admin-dashboard</pre><pre># Release гілки  <br>release/1.2.0<br>release/2.0.0-beta</pre><pre># Hotfix гілки<br>hotfix/critical-security-fix<br>hotfix/payment-bug-fix</pre><h3>Автоматизація з Git Hooks</h3><pre># pre-commit hook для перевірки стилю коду<br>#!/bin/sh<br>npm run lint<br>npm run test</pre><h3>Інтеграція з CI/CD</h3><pre># .github/workflows/gitflow.yml<br>name: Git Flow CI<br>on:<br>  push:<br>    branches: [main, develop]<br>  pull_request:<br>    branches: [develop]</pre><pre>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v2<br>      - name: Run tests<br>        run: npm test</pre><h3>Командні угоди</h3><ol><li><strong>Завжди створювати PR/MR</strong> для feature гілок</li><li><strong>Code review обов’язковий</strong> перед злиттям</li><li><strong>Тестування в release гілці</strong> перед production</li><li><strong>Документувати зміни</strong> в CHANGELOG.md</li><li><strong>Використовувати semantic versioning</strong> для тегів</li></ol><h3>Поширені помилки та як їх уникнути</h3><h3>❌ Пряме комітування в main/develop</h3><pre># Неправильно<br>git checkout main<br>git commit -m &quot;fix: urgent fix&quot;</pre><pre># Правильно<br>git flow hotfix start urgent-fix<br># зробити зміни<br>git flow hotfix finish urgent-fix</pre><h3>❌ Забування про оновлення develop з main після hotfix</h3><pre># Після hotfix завжди перевіряйте<br>git checkout develop<br>git pull origin develop</pre><h3>❌ Занадто великі feature гілки</h3><pre># Розбивайте великі функції на менші<br>feature/user-system -&gt; feature/user-auth + feature/user-profile</pre><h3>Інструменти та розширення</h3><h3>GUI інструменти з підтримкою Git Flow</h3><ul><li><strong>GitKraken</strong> — візуальний Git клієнт</li><li><strong>SourceTree</strong> — безкоштовний Git GUI</li><li><strong>Git Tower</strong> — професійний Git клієнт</li></ul><h3>VS Code розширення</h3><ul><li><strong>GitLens</strong> — розширені можливості Git</li><li><strong>Git Graph</strong> — візуалізація гілок</li><li><strong>Git Flow Extension</strong> — інтеграція Git Flow</li></ul><h3>Команди для відлагодження</h3><pre># Перегляд поточного стану Git Flow<br>git flow version</pre><pre># Перегляд активних гілок<br>git branch -a</pre><pre># Історія комітів з графіком<br>git log --oneline --graph --all</pre><pre># Статус всіх гілок<br>git show-branch --all</pre><h3>Заключення</h3><p>Git Flow — потужний інструмент для організації командної розробки, який забезпечує стабільність і контрольованість процесу розробки. Хоча він може здатися складним на початку, правильне використання Git Flow значно покращує якість коду та ефективність команди.</p><p><strong>Ключові моменти для запам’ятовування:</strong></p><ul><li><strong>main</strong> — завжди стабільний production код</li><li><strong>develop</strong> — інтеграційна гілка для нових функцій</li><li><strong>feature</strong> — окремі функції розробляються ізольовано</li><li><strong>release</strong> — підготовка до випуску з фіксацією функцій</li><li><strong>hotfix</strong> — швидкі критичні виправлення</li></ul><p>Починайте поступово, дотримуйтесь конвенцій та адаптуйте процес під потреби вашої команди. Git Flow — це не догма, а інструмент, який повинен допомагати, а не ускладнювати розробку.</p><h3>Корисні ресурси</h3><p><strong>Матеріал для цієї статті використовувався з кількох джерел:</strong></p><ol><li><a href="https://www.atlassian.com/ru/git/tutorials/comparing-workflows/gitflow-workflow">Atlassian Git Flow Tutorial</a></li><li><a href="https://danielkummer.github.io/git-flow-cheatsheet/index.ru_RU.html">Git Flow Cheatsheet</a></li><li><a href="https://nvie.com/posts/a-successful-git-branching-model/">A successful Git branching model</a></li><li><a href="https://lucamezzalira.com/2014/03/10/git-flow-vs-github-flow/">Git Flow vs GitHub Flow</a></li></ol><p><strong>Додаткові ресурси:</strong></p><ul><li><a href="https://semver.org/">Semantic Versioning</a></li><li><a href="https://www.conventionalcommits.org/">Conventional Commits</a></li><li><a href="https://git-scm.com/book/en/v2">Git Best Practices</a></li><li><a href="https://medium.com/p/f6cd82636fbb">Software Versioning: A Comprehensive Guide Версіювання ПЗ: Комплексний Посібник</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aaaf35c04a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Повний гайд з угод про імена у веб-розробці]]></title>
            <link>https://medium.com/@cobchenyuk/%D0%BF%D0%BE%D0%B2%D0%BD%D0%B8%D0%B9-%D0%B3%D0%B0%D0%B9%D0%B4-%D0%B7-%D1%83%D0%B3%D0%BE%D0%B4-%D0%BF%D1%80%D0%BE-%D1%96%D0%BC%D0%B5%D0%BD%D0%B0-%D1%83-%D0%B2%D0%B5%D0%B1-%D1%80%D0%BE%D0%B7%D1%80%D0%BE%D0%B1%D1%86%D1%96-ac5795442d46?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac5795442d46</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 07:53:05 GMT</pubDate>
            <atom:updated>2025-06-27T07:53:05.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsMGSNfP-YgWddsAkZ5now.png" /></figure><h3>Чому іменування — це не просто дрібниці</h3><p>Уявіть, що ви відкриваєте чужий код і бачите змінну d, функцію f() та клас usrMgr. Чи зрозуміло вам, що відбувається? Напевно, ні. А тепер уявіть currentDate, validateEmail() та UserManager. Різниця очевидна.</p><p>Правильне іменування — це не педантизм, а інвестиція в майбутнє вашого проєкту. Коли через півроку ви або ваші колеги читатимете код, хороші імена заощадять години розбирань та відлагодження.</p><h3>Чотири золоті правила іменування</h3><p>Перш ніж заглиблюватися в специфіку мов та технологій, запам’ятайте ці принципи:</p><p><strong>1. Консистентність понад усе</strong> Оберіть одну конвенцію та дотримуйтесь її у всьому проєкті. Краще посередня, але послідовна система, ніж ідеальна, але застосовувана від випадку до випадку.</p><p><strong>2. Читабельність важливіша за стислість</strong> getUserAuthenticationToken() краще, ніж getUsrAuthTkn(). Сучасні редактори коду мають автодоповнення — користуйтеся цим.</p><p><strong>3. Імена повинні пояснювати призначення</strong> Якщо вам потрібен коментар, щоб пояснити, що робить змінна або функція, то, ймовірно, ім’я обрано невдало.</p><p><strong>4. Контекст має значення</strong> У класі User метод getName() зрозумілий. У глобальній області краще використовувати getUserName().</p><h3>Основні стилі іменування та де їх застосовувати</h3><h3>camelCase</h3><p><strong>Коли використовувати:</strong> JavaScript змінні, функції, методи</p><pre>const firstName = &#39;John&#39;;<br>const isUserActive = true;<br>function calculateTotalPrice() { /* ... */ }</pre><h3>PascalCase</h3><p><strong>Коли використовувати:</strong> Класи, компоненти, типи, інтерфейси</p><pre>class UserManager { /* ... */ }<br>interface UserData { /* ... */ }</pre><h3>kebab-case</h3><p><strong>Коли використовувати:</strong> Файли, папки, CSS класи, HTML атрибути</p><pre>.user-profile { /* ... */ }</pre><pre>&lt;div data-user-id=&quot;123&quot;&gt;</pre><h3>snake_case</h3><p><strong>Коли використовувати:</strong> Бази даних, деякі константи</p><pre>CREATE TABLE user_profiles (<br>    user_id INTEGER,<br>    created_at TIMESTAMP<br>);</pre><h3>SCREAMING_SNAKE_CASE</h3><p><strong>Коли використовувати:</strong> Глобальні константи, змінні оточення</p><pre>const API_BASE_URL = &#39;https://api.example.com&#39;;<br>const MAX_RETRY_COUNT = 3;</pre><h3>JavaScript та Node.js: деталі, що мають значення</h3><h3>Булеві змінні — говоріть прямо</h3><p>Використовуйте префікси, які роблять логічне значення очевидним:</p><pre>// ✅ Відмінно<br>const isEnabled = true;<br>const hasPermission = false;<br>const canEdit = true;<br>const shouldUpdate = false;</pre><pre>// ❌ Уникайте<br>const enabled = true;  // Незрозуміло, що це boolean<br>const permission = false;  // Що саме false?</pre><h3>Функції — починайте з дієслова</h3><p>Функція виконує дію, тому ім’я повинно це відображати:</p><pre>// ✅ Зрозуміло, що відбувається<br>function getUser() { /* отримати */ }<br>function validateEmail() { /* перевірити */ }<br>function calculateTotal() { /* обчислити */ }<br>function fetchUserData() { /* завантажити */ }<br>function toggleVisibility() { /* перемкнути */ }</pre><pre>// ❌ Незрозумілі наміри<br>function user() { /* що робимо з користувачем? */ }<br>function email() { /* відправляємо? перевіряємо? */ }</pre><h3>Приватні методи — підкресліть приватність</h3><pre>class UserService {<br>    constructor() {<br>        this._privateProperty = &#39;secret&#39;;<br>    }<br>    <br>    _privateMethod() {<br>        // Старий стиль — префікс підкреслення<br>    }<br>    <br>    // Сучасний синтаксис<br>    #reallyPrivate = &#39;very secret&#39;;<br>    <br>    #privateMethod() {<br>        // Справжня приватність<br>    }<br>}</pre><h3>Організація файлів та проєктів</h3><h3>Структура Node.js проєкту</h3><p>Добре організована структура проєкту — це половина успіху:</p><pre>my-project/<br>├── src/<br>│   ├── controllers/<br>│   │   ├── user-controller.js<br>│   │   └── auth-controller.js<br>│   ├── services/<br>│   │   ├── user-service.js<br>│   │   └── email-service.js<br>│   ├── models/<br>│   │   ├── user-model.js<br>│   │   └── product-model.js<br>│   ├── utils/<br>│   │   ├── validation-utils.js<br>│   │   └── date-utils.js<br>│   └── config/<br>│       ├── database-config.js<br>│       └── app-config.js<br>├── tests/<br>├── docs/<br>├── package.json<br>└── README.md</pre><h3>Спеціальні файли — дотримуйтесь конвенцій</h3><p>Деякі файли мають усталені імена. Не винаходьте велосипед:</p><pre>README.md<br>LICENSE<br>CHANGELOG.md<br>CONTRIBUTING.md<br>package.json<br>.gitignore<br>.env</pre><h3>CSS та HTML: краса у простоті</h3><h3>CSS класи — завжди kebab-case</h3><pre>/* ✅ Правильно */<br>.user-profile {<br>    background: white;<br>}</pre><pre>.navigation-menu {<br>    display: flex;<br>}</pre><pre>/* ✅ BEM методологія */<br>.card { /* блок */ }<br>.card__header { /* елемент */ }<br>.card--featured { /* модифікатор */ }</pre><pre>/* ❌ Уникайте */<br>.userProfile { /* camelCase не прийнятий у CSS */ }<br>.user_profile { /* snake_case не прийнятий у CSS */ }</pre><h3>CSS змінні — організуйте систематично</h3><pre>:root {<br>    /* ✅ Логічне групування */<br>    --color-primary: #007bff;<br>    --color-secondary: #6c757d;<br>    --font-size-large: 1.5rem;<br>    --spacing-medium: 16px;<br>    --border-radius-small: 4px;<br>}</pre><h3>HTML атрибути — все малими літерами</h3><pre>&lt;!-- ✅ Стандартно --&gt;<br>&lt;div class=&quot;user-card&quot; data-user-id=&quot;123&quot;&gt;<br>    &lt;img src=&quot;avatar.jpg&quot; alt=&quot;User avatar&quot; loading=&quot;lazy&quot;&gt;<br>    &lt;button type=&quot;submit&quot; aria-label=&quot;Submit form&quot;&gt;Submit&lt;/button&gt;<br>&lt;/div&gt;</pre><pre>&lt;!-- ❌ Проблематично --&gt;<br>&lt;div class=&quot;userCard&quot; data-userId=&quot;123&quot;&gt;<br>&lt;Button Type=&quot;Submit&quot;&gt;</pre><h3>TypeScript: типи та інтерфейси</h3><p>TypeScript додає додатковий шар іменування через типи:</p><pre>// ✅ PascalCase для типів та інтерфейсів<br>interface UserData {<br>    id: number;<br>    firstName: string;<br>    lastName: string;<br>    isActive: boolean;<br>}</pre><pre>type ApiResponse&lt;T&gt; = {<br>    data: T;<br>    status: number;<br>    message: string;<br>};</pre><pre>// ✅ Enum теж у PascalCase<br>enum UserRole {<br>    Admin = &#39;admin&#39;,<br>    User = &#39;user&#39;,<br>    Guest = &#39;guest&#39;<br>}</pre><pre>// ✅ Дженерик типи<br>interface Repository&lt;T&gt; {<br>    findById(id: string): Promise&lt;T&gt;;<br>    save(entity: T): Promise&lt;T&gt;;<br>}</pre><h3>API та Backend: RESTful угоди</h3><h3>Ендпоінти — дотримуйтесь REST</h3><pre>✅ Правильні REST ендпоінти:<br>GET /api/users<br>GET /api/users/:id<br>POST /api/users<br>PUT /api/users/:id<br>DELETE /api/users/:id</pre><pre>✅ Для складних ресурсів:<br>GET /api/user-profiles<br>GET /api/order-items<br>POST /api/password-reset</pre><h3>Query параметри — оберіть стиль і дотримуйтесь його</h3><pre>✅ camelCase (якщо JSON API):<br>GET /api/users?firstName=John&amp;isActive=true</pre><pre>✅ snake_case (якщо дотримуєтесь цієї конвенції):<br>GET /api/users?first_name=John&amp;is_active=true</pre><h3>Бази даних: snake_case править</h3><p>У світі SQL snake_case — король:</p><pre>-- ✅ Послідовно використовуйте snake_case<br>CREATE TABLE users (<br>    id SERIAL PRIMARY KEY,<br>    first_name VARCHAR(100),<br>    last_name VARCHAR(100),<br>    email VARCHAR(255) UNIQUE,<br>    is_active BOOLEAN DEFAULT true,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><pre>-- ✅ Зв&#39;язуючі таблиці<br>CREATE TABLE user_roles (<br>    user_id INTEGER REFERENCES users(id),<br>    role_id INTEGER REFERENCES roles(id)<br>);</pre><h3>Змінні оточення та Git</h3><h3>.env файли — SCREAMING_SNAKE_CASE</h3><pre># ✅ Все у верхньому регістрі<br>DATABASE_URL=postgresql://localhost:5432/mydb<br>API_BASE_URL=https://api.example.com<br>JWT_SECRET=your-secret-key<br>NODE_ENV=production<br>PORT=3000</pre><h3>Git коміти — Conventional Commits</h3><pre># ✅ Використовуйте стандартні префікси<br>feat: add user authentication<br>fix: resolve login validation bug<br>docs: update API documentation<br>style: fix code formatting<br>refactor: simplify user service logic<br>test: add unit tests for user model<br>chore: update dependencies</pre><h3>Гілки — описові імена</h3><pre>git checkout -b feature/user-authentication<br>git checkout -b fix/login-validation<br>git checkout -b hotfix/security-patch</pre><h3>Інструменти для автоматизації</h3><h3>ESLint конфігурація для TypeScript</h3><pre>{<br>    &quot;extends&quot;: [<br>        &quot;eslint:recommended&quot;,<br>        &quot;@typescript-eslint/recommended&quot;<br>    ],<br>    &quot;parser&quot;: &quot;@typescript-eslint/parser&quot;,<br>    &quot;rules&quot;: {<br>        &quot;camelcase&quot;: [&quot;error&quot;, { &quot;properties&quot;: &quot;always&quot; }],<br>        &quot;@typescript-eslint/naming-convention&quot;: [<br>            &quot;error&quot;,<br>            {<br>                &quot;selector&quot;: &quot;variableLike&quot;,<br>                &quot;format&quot;: [&quot;camelCase&quot;]<br>            },<br>            {<br>                &quot;selector&quot;: &quot;typeLike&quot;,<br>                &quot;format&quot;: [&quot;PascalCase&quot;]<br>            }<br>        ]<br>    }<br>}</pre><h3>package.json скрипти</h3><pre>{<br>    &quot;scripts&quot;: {<br>        &quot;lint&quot;: &quot;eslint src/&quot;,<br>        &quot;format&quot;: &quot;prettier --write src/&quot;,<br>        &quot;lint:css&quot;: &quot;stylelint src/**/*.css&quot;<br>    }<br>}</pre><h3>Поширені помилки та як їх уникати</h3><h3>❌ Змішування стилів</h3><pre>// Погано — різні стилі в одному проєкті<br>const user_name = &#39;John&#39;;      // snake_case<br>const userAge = 25;            // camelCase<br>const UserEmail = &#39;john@example.com&#39;; // PascalCase</pre><h3>❌ Неописові імена</h3><pre>// Погано<br>const d = new Date();<br>const u = getUser();<br>const f = () =&gt; {};</pre><pre>// Добре<br>const currentDate = new Date();<br>const currentUser = getUser();<br>const validateEmail = () =&gt; {};</pre><h3>❌ Угорська нотація</h3><pre>// Погано — не використовуйте префікси типів<br>const strUserName = &#39;John&#39;;<br>const intUserAge = 25;<br>const boolIsActive = true;</pre><pre>// Добре — типи зрозумілі з контексту<br>const userName = &#39;John&#39;;<br>const userAge = 25;<br>const isActive = true;</pre><h3>Практичні рекомендації для команди</h3><ol><li><strong>Створіть style guide</strong> для вашої команди та задокументуйте прийняті рішення</li><li><strong>Використовуйте лінтери</strong> — ESLint, Prettier, StyleLint автоматизують перевірку стилю</li><li><strong>Документуйте винятки</strong> — якщо порушуєте загальні правила, поясніть чому</li><li><strong>Code review</strong> — зверніть увагу на іменування під час ревʼю коду</li><li><strong>Поступове впровадження</strong> — не намагайтеся перейменувати все відразу, робіть це ітеративно</li></ol><h3>Висновок</h3><p>Хороші угоди про іменування — це інвестиція в довгострокову підтримуваність проєкту. Вони роблять код більш читабельним, зменшують кількість помилок та прискорюють роботу команди.</p><p>Пам’ятайте: найкращі угоди — ті, яких дотримуються всі учасники проєкту. Почніть з малого, будьте послідовними та не бійтеся адаптувати правила під потреби вашої команди.</p><p>Які угоди про іменування використовуєте ви? Поділіться своїм досвідом у коментарях!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac5795442d46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Naming Conventions in Web Development]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cobchenyuk/the-complete-guide-to-naming-conventions-in-web-development-25fb6d2f07f5?source=rss-3d6f8818545a------2"><img src="https://cdn-images-1.medium.com/max/1024/1*FqfiK2mtoVVSBj61PI-BjA.png" width="1024"></a></p><p class="medium-feed-snippet">Why Naming Isn&#x2019;t Just About Details</p><p class="medium-feed-link"><a href="https://medium.com/@cobchenyuk/the-complete-guide-to-naming-conventions-in-web-development-25fb6d2f07f5?source=rss-3d6f8818545a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cobchenyuk/the-complete-guide-to-naming-conventions-in-web-development-25fb6d2f07f5?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fb6d2f07f5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-dev-101]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 07:50:14 GMT</pubDate>
            <atom:updated>2025-06-27T07:50:14.159Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Патерн Модульних Компонентів: Альтернативний Підхід до Архітектури Vue.js]]></title>
            <link>https://medium.com/@cobchenyuk/%D0%BF%D0%B0%D1%82%D0%B5%D1%80%D0%BD-%D0%BC%D0%BE%D0%B4%D1%83%D0%BB%D1%8C%D0%BD%D0%B8%D1%85-%D0%BA%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D1%96%D0%B2-%D0%B0%D0%BB%D1%8C%D1%82%D0%B5%D1%80%D0%BD%D0%B0%D1%82%D0%B8%D0%B2%D0%BD%D0%B8%D0%B9-%D0%BF%D1%96%D0%B4%D1%85%D1%96%D0%B4-%D0%B4%D0%BE-%D0%B0%D1%80%D1%85%D1%96%D1%82%D0%B5%D0%BA%D1%82%D1%83%D1%80%D0%B8-vue-js-dc97fffc55ff?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc97fffc55ff</guid>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 00:56:39 GMT</pubDate>
            <atom:updated>2025-06-11T22:11:01.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ot376DmwHTx_65FexfpSg.png" /></figure><p><em>Як я вирішив проблеми управління станом та організації компонентів у великомасштабних Vue.js додатках, йдучи проти конвенцій фреймворку</em></p><h3>Проблема</h3><p>Після 4,5 років роботи з Vue.js на великих enterprise проектах, я постійно стикався з одними й тими ж архітектурними проблемами:</p><ul><li><strong>Пекло prop drilling</strong>: передача даних через множинні рівні компонентів лише для досягнення глибоко вкладених дітей</li><li><strong>Хаос управління станом</strong>: змішування глобальних сторів, локального стану та provide/inject призводило до непередбачуваної поведінки</li><li><strong>Зв’язаність компонентів</strong>: компоненти ставали тісно пов’язаними через спільний стан та складні залежності</li><li><strong>Когнітивне навантаження</strong>: “магія” Vue ускладнювала відлагодження, коли щось йшло не так</li></ul><p>Традиційні Vue паттерни як provide/inject, глобальні стори (Pinia/Vuex) та надмірне покладання на Composition API здавалися занадто &quot;магічними&quot; для складної бізнес-логіки. Мені потрібно було більше контролю та передбачуваності.</p><h3>Рішення: Патерн Модульних Компонентів</h3><p>Протягом двох років я розробив те, що називаю <strong>Патерн Модульних Компонентів</strong> — архітектуру, яка розглядає кожен батьківський компонент як самодостатній модуль з власною екосистемою.</p><h3>Основна Філософія</h3><ol><li><strong>Явність над Магією</strong>: перевага ванільного JavaScript над фреймворковими абстракціями</li><li><strong>Ізоляція над Спільністю</strong>: компоненти повинні бути самодостатніми модулями</li><li><strong>Розділення Логіки-Шаблону</strong>: вся бізнес-логіка в JavaScript, шаблони лише для відображення</li><li><strong>Багаторівнева Архітектура</strong>: чітке розділення між глобальними, загальними та локальними концернами</li></ol><h3>Огляд Архітектури</h3><pre>src/<br>├── store/              # Глобальний стан<br>├── types/              # Глобальні інтерфейси  <br>├── constants/          # Глобальні константи<br>├── utils/              # Глобальні утиліти<br>├── composables/        # Утилітарні хуки (useApi, useModal)<br>├── components/<br>│   └── common/         # Багаторазові UI компоненти (лише пропси)<br>└── features/<br>    └── UserProfile/    # Модуль компонента<br>        ├── UserProfile.vue<br>        ├── components/ # Дочірні компоненти (в межах цього модуля)<br>        ├── store.ts    # Локальний стан<br>        ├── run.ts      # API функції<br>        ├── types.ts    # Локальні типи<br>        └── utils.ts    # Локальні утиліти</pre><h3>Деталі Реалізації</h3><h3>1. Управління Локальним Станом</h3><p>Замість глобальних сторів або provide/inject, кожен модуль керує власним станом:</p><pre>// UserProfile/store.ts<br>import { reactive, ref } from &#39;vue&#39;</pre><pre>export const state = reactive({<br>  user: null,<br>  loading: false,<br>  error: null<br>})</pre><pre>export const selectedTab = ref(&#39;profile&#39;)</pre><pre>// Групове скидання коли потрібно<br>export const resetStore = () =&gt; {<br>  state.user = null<br>  state.loading = false<br>  state.error = null<br>  selectedTab.value = &#39;profile&#39;<br>}</pre><h3>2. API Рівень з Чистими Функціями</h3><p>Я використовую два підходи для API функцій, віддаючи перевагу чистим функціям:</p><p><strong>Пріоритетний: Чисті функції</strong></p><pre>// UserProfile/run.ts<br>export const fetchUser = async (id: string) =&gt; {<br>  const response = await api.get(`/users/${id}`)<br>  return response.data<br>}</pre><pre>// У компоненті<br>const userData = await fetchUser(userId)<br>state.user = userData</pre><p><strong>Прагматичний: Сайд-ефекти (коли зручно)</strong></p><pre>// UserProfile/run.ts<br>import { state } from &#39;./store&#39;</pre><pre>export const fetchUser = async (id: string) =&gt; {<br>  state.loading = true<br>  try {<br>    const response = await api.get(`/users/${id}`)<br>    state.user = response.data<br>  } finally {<br>    state.loading = false<br>  }<br>}</pre><h3>3. Common Компоненти через Слоти</h3><p>Багаторазові UI компоненти ніколи не керують станом — лише пропси та слоти:</p><pre>&lt;!-- components/common/Table/Table.vue --&gt;<br>&lt;template&gt;<br>  &lt;table :class=&quot;tableClass&quot;&gt;<br>    &lt;slot name=&quot;header&quot; /&gt;<br>    &lt;slot /&gt;<br>    &lt;slot name=&quot;footer&quot; /&gt;<br>  &lt;/table&gt;<br>&lt;/template&gt;</pre><pre>&lt;!-- Використання --&gt;<br>&lt;Table bordered&gt;<br>  &lt;template #header&gt;<br>    &lt;TableRow&gt;<br>      &lt;TableCell&gt;Ім&#39;я&lt;/TableCell&gt;<br>      &lt;TableCell&gt;Email&lt;/TableCell&gt;<br>    &lt;/TableRow&gt;<br>  &lt;/template&gt;<br>  <br>  &lt;TableRow v-for=&quot;user in users&quot; :key=&quot;user.id&quot;&gt;<br>    &lt;TableCell&gt;{{ user.name }}&lt;/TableCell&gt;<br>    &lt;TableCell&gt;{{ user.email }}&lt;/TableCell&gt;<br>  &lt;/TableRow&gt;<br>&lt;/Table&gt;</pre><h3>4. Розділення Логіки-Шаблону</h3><p>Вся бізнес-логіка залишається в JavaScript, шаблони лише обробляють відображення:</p><pre>// У script setup<br>const showNextButton = computed(() =&gt; {<br>  return currentStep.value &lt; totalSteps.value &amp;&amp; <br>         !loading.value &amp;&amp; <br>         isFormValid.value<br>})</pre><pre>const showSubmitButton = computed(() =&gt; {<br>  return currentStep.value === totalSteps.value &amp;&amp; <br>         !hasErrors.value<br>})</pre><pre>&lt;!-- У template --&gt;<br>&lt;Button v-if=&quot;showNextButton&quot; @click=&quot;nextStep&quot;&gt;<br>  Далі<br>&lt;/Button&gt;<br>&lt;Button v-if=&quot;showSubmitButton&quot; @click=&quot;submit&quot;&gt;<br>  Відправити<br>&lt;/Button&gt;</pre><h3>5. Очищення Стану</h3><p>Ручне управління станом вимагає дисциплінованого очищення:</p><pre>import { onUnmounted } from &#39;vue&#39;<br>import { resetStore } from &#39;./store&#39;</pre><pre>onUnmounted(() =&gt; {<br>  resetStore()<br>})</pre><h3>6. Рідкісна Міжкомпонентна Комунікація</h3><p>Для рідкісних випадків, що потребують комунікації між віддаленими компонентами:</p><pre>// composables/useButtonState.ts<br>const isBlocked = ref(true)</pre><pre>export const useButtonState = () =&gt; {<br>  const unblock = () =&gt; isBlocked.value = false<br>  const block = () =&gt; isBlocked.value = true<br>  <br>  return { isBlocked, unblock, block }<br>}</pre><h3>Стейт Машини для Складної Логіки</h3><p>Для складних багатоетапних процесів я інтегрую стейт машини (XState) замість ручного управління умовами:</p><pre>// composables/useStepperMachine.ts<br>import { createMachine, interpret } from &#39;xstate&#39;</pre><pre>const stepperMachine = createMachine({<br>  id: &#39;stepper&#39;,<br>  initial: &#39;step1&#39;,<br>  states: {<br>    step1: {<br>      on: { NEXT: { target: &#39;step2&#39;, cond: &#39;isStep1Valid&#39; } }<br>    },<br>    step2: {<br>      on: { <br>        NEXT: { target: &#39;step3&#39;, cond: &#39;isStep2Valid&#39; },<br>        PREV: &#39;step1&#39;<br>      }<br>    },<br>    // ... більше станів<br>  }<br>})</pre><h3>Застосування в Реальному Світі</h3><p>Я застосовую цей патерн двома способами:</p><ol><li><strong>Нові проекти</strong>: почати з цієї архітектури з самого початку</li><li><strong>Існуючі проекти</strong>: створювати нові фічі, використовуючи цей патерн локально, не порушуючи існуючий код</li></ol><p>Я успішно впровадив цей підхід у кількох enterprise проектах. Патерн добре масштабується та робить код більш підтримуваним.</p><h3>Компроміси та Критика</h3><p><strong>Недоліки:</strong></p><ul><li>Вища крива навчання для Vue розробників</li><li>Більше boilerplate коду</li><li>Йде проти філософії Vue “конвенція над конфігурацією”</li><li>Ризик витоків пам’яті, якщо забути очищення</li><li>Складніше використовувати бібліотеки Vue екосистеми</li><li>Потенційне дублювання коду між модулями</li></ul><p><strong>Коли НЕ використовувати:</strong></p><ul><li>Малі додатки</li><li>Команди, нові для Vue</li><li>Проекти, що потребують швидкого прототипування</li><li>Сильна залежність від плагінів Vue екосистеми</li></ul><h3>Переваги</h3><p><strong>Плюси:</strong></p><ul><li>Передбачувана поведінка та легше відлагодження</li><li>Краще розділення обов’язків</li><li>Легший onboarding для React розробників</li><li>Самодостатні модулі зменшують зв’язаність</li><li>Явні залежності роблять код легшим для розуміння</li><li>Добре масштабується для великих команд та складної бізнес-логіки</li></ul><h3>Висновок</h3><p>Патерн Модульних Компонентів жертвує зручністю Vue заради контролю та передбачуваності. Він не для всіх, але для великомасштабних додатків, де підтримуваність та явна поведінка важливіші за швидкість розробки, він забезпечує міцну основу.</p><p>Цей підхід виник з реальних болючих точок у enterprise розробці. Хоча він йде проти зерна Vue, він пропонує альтернативу для команд, які цінують явний контроль над магією фреймворку.</p><p><strong>Що ви думаєте? Чи стикалися ви з подібними архітектурними викликами у Vue.js? Мені цікаво почути ваші думки та критику цього підходу.</strong></p><p><em>Я розробляв та вдосконалював цей патерн протягом 2+ років у кількох великомасштабних проектах.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc97fffc55ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Component Module Pattern: A Different Approach to Vue.js Architecture]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cobchenyuk/component-module-pattern-a-different-approach-to-vue-js-architecture-086a33d2a9f3?source=rss-3d6f8818545a------2"><img src="https://cdn-images-1.medium.com/max/1536/1*6ot376DmwHTx_65FexfpSg.png" width="1536"></a></p><p class="medium-feed-snippet">How I solved state management and component organization in large-scale Vue.js applications by going against the framework&#x2019;s conventions</p><p class="medium-feed-link"><a href="https://medium.com/@cobchenyuk/component-module-pattern-a-different-approach-to-vue-js-architecture-086a33d2a9f3?source=rss-3d6f8818545a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cobchenyuk/component-module-pattern-a-different-approach-to-vue-js-architecture-086a33d2a9f3?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/086a33d2a9f3</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vue-3]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 00:53:30 GMT</pubDate>
            <atom:updated>2025-06-11T22:10:13.026Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Software Versioning: A Comprehensive Guide Версіювання ПЗ: Комплексний Посібник]]></title>
            <link>https://medium.com/@cobchenyuk/software-versioning-a-comprehensive-guide-%D0%B2%D0%B5%D1%80%D1%81%D1%96%D1%8E%D0%B2%D0%B0%D0%BD%D0%BD%D1%8F-%D0%BF%D0%B7-%D0%BA%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D0%B8%D0%B9-%D0%BF%D0%BE%D1%81%D1%96%D0%B1%D0%BD%D0%B8%D0%BA-f6cd82636fbb?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6cd82636fbb</guid>
            <category><![CDATA[code-version]]></category>
            <category><![CDATA[semver]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 22:42:43 GMT</pubDate>
            <atom:updated>2025-02-14T22:44:47.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Software Versioning: A Comprehensive Guide Версіонування ПЗ: Комплексний Посібник" src="https://cdn-images-1.medium.com/max/1024/1*RL3JNIxWzsqE8w6h6-9WIw.png" /></figure><h3>Зміст</h3><ol><li>#Вступ-та-основні-принципи</li><li>#Структура-версіонування</li><li>#Життєвий-цикл-версій</li><li>#Спеціальні-позначення</li><li>#Документування-змін</li><li>#Висновки</li></ol><h3>Вступ та основні принципи</h3><blockquote>Семантичне версіонування (SemVer) є стандартизованою системою нумерації версій, що забезпечує чітке розуміння змін у програмному забезпеченні. Версіонування є ключовим елементом у розробці, що допомагає ефективно відстежувати зміни та керувати оновленнями продукту.</blockquote><h3>Структура версіювання</h3><p>Версія програмного забезпечення складається з трьох основних чисел у форматі MAJOR.MINOR.PATCH, кожне з яких має конкретне призначення та відображає характер внесених змін.</p><p><strong>Перше число (MAJOR)</strong> визначає масштабні зміни, які можуть порушити зворотну сумісність:</p><ul><li>Впровадження значних архітектурних змін</li><li>Модифікація основних інтерфейсів системи</li><li>Зміна API чи основних принципів роботи</li><li>Приклад: <strong>v1.9.4 → v2.0.0 (повна зміна системи автентифікації)</strong></li></ul><p><strong>Друге число (MINOR)</strong> вказує на впровадження нової функціональності:</p><ul><li>Додавання нових можливостей без порушення сумісності</li><li>Розширення чинного API</li><li>Додавання нових модулів</li><li>Приклад: <strong>v1.2.3 → v1.3.0 (додано новий модуль експорту)</strong></li></ul><p><strong>Третє число (PATCH)</strong> використовується для виправлень:</p><ul><li>Усунення виявлених помилок</li><li>Оптимізація продуктивності</li><li>Доопрацювання документації</li><li>Приклад: <strong>v1.2.3 → v1.2.4 (виправлено помилку валідації)</strong></li></ul><h3>Життєвий цикл версій</h3><h4>Етап розробки (0.x.x)</h4><p><strong>Фаза ініціалізації (0.1.x)</strong></p><ul><li><strong>v0.1.0 </strong>— перший функціональний реліз з базовими можливостями</li><li><strong>v0.1.1</strong> — виправлення критичних помилок</li><li><strong>v0.1.2 </strong>— оптимізація продуктивності</li></ul><p><strong>Фаза активної розробки (0.2.x — 0.9.x)</strong></p><ul><li><strong>v0.2.0 </strong>— додавання нового функціоналу</li><li><strong>v0.2.1</strong> — доопрацювання доданого функціоналу</li><li><strong>v0.3.0</strong> — впровадження наступного значного компонента</li></ul><h3>Стабільні версії (1.x.x+)</h3><p><strong>Перший стабільний реліз (1.0.0)</strong></p><pre>Для випуску версії 1.0.0 необхідно забезпечити:<br>* Повну реалізацію запланованого функціоналу<br>* Відсутність критичних помилок<br>* Наявність повної документації<br>* Успішне тестування всіх ключових сценаріїв</pre><p><strong>Подальший розвиток</strong></p><ul><li><strong>v1.1.0</strong> — нові функції без порушення сумісності</li><li><strong>v1.1.1</strong> — виправлення помилок</li><li><strong>v2.0.0 </strong>— значні зміни з можливим порушенням сумісності</li></ul><h3>Спеціальні позначення</h3><p>У деяких проєктах використовуються додаткові позначення для тестових версій:</p><p><strong>Alpha-версії (v1.0.0-alpha)</strong></p><ul><li>Рання стадія тестування</li><li>Можливі значні зміни функціоналу</li><li>Призначені для внутрішньої розробки</li></ul><p><strong>Beta-версії (v1.0.0-beta)</strong></p><ul><li>Завершена основна функціональність</li><li>Активне публічне тестування</li><li>Збір відгуків від користувачів</li></ul><p><strong>Release Candidate (v1.0.0-rc)</strong></p><ul><li>Фінальне тестування перед релізом</li><li>Виправлення останніх помилок</li><li>Підготовка документації</li></ul><h3>Документування змін</h3><p>Кожна нова версія повинна супроводжуватися детальним описом змін у форматі:</p><pre># Журнал змін<br><br>## [2.1.0] - 2024-02-14<br><br>### Додано<br>- Інтеграція з новою платіжною системою<br>- Розширений функціонал звітності<br><br>### Змінено<br>- Оптимізовано процес автентифікації<br>- Оновлено інтерфейс користувача<br><br>### Виправлено<br>- Усунено помилку при обробці великих файлів<br>- Виправлено проблеми з кодуванням символів</pre><h3>Висновки</h3><p>Ефективне версіювання є критичним елементом успішної розробки програмного забезпечення. Дотримання описаних принципів забезпечує:</p><ul><li>Прозорість процесу розробки</li><li>Ефективне керування залежностями</li><li>Зрозумілу комунікацію між усіма учасниками проєкту</li><li>Стабільний розвиток продукту</li></ul><blockquote>Для подальшого вивчення рекомендується ознайомитися з офіційною документацією SemVer та практичними прикладами впровадження версіювання в реальних проєктах.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6cd82636fbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ефективне управління станом у Vue 3: підхід із зовнішнім сховищем для пов’язаних компонентів]]></title>
            <link>https://medium.com/@cobchenyuk/%D0%B5%D1%84%D0%B5%D0%BA%D1%82%D0%B8%D0%B2%D0%BD%D0%B5-%D1%83%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D1%96%D0%BD%D0%BD%D1%8F-%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%BC-%D1%83-vue-3-%D0%BF%D1%96%D0%B4%D1%85%D1%96%D0%B4-%D1%96%D0%B7-%D0%B7%D0%BE%D0%B2%D0%BD%D1%96%D1%88%D0%BD%D1%96%D0%BC-%D1%81%D1%85%D0%BE%D0%B2%D0%B8%D1%89%D0%B5%D0%BC-%D0%B4%D0%BB%D1%8F-%D0%BF%D0%BE%D0%B2%D1%8F%D0%B7%D0%B0%D0%BD%D0%B8%D1%85-%D0%BA%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D1%96%D0%B2-cf90f97e675f?source=rss-3d6f8818545a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf90f97e675f</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Андрей Собченюк]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 22:55:00 GMT</pubDate>
            <atom:updated>2025-02-12T22:55:00.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Ефективне управління станом у Vue 3: підхід із зовнішнім сховищем для пов’язаних компонентів" src="https://cdn-images-1.medium.com/max/666/1*Cd-gl_mbYD13FElKDm-yfg.png" /><figcaption>Лише одиниці можуть розгледіти на цій картинці другу тварину: а ви бачите?</figcaption></figure><p>Я розробник використовую <strong>Vue.js</strong> у повсякденні, хочу поділитися з вами важливим патерном проєктування, який може значно покращити архітектуру ваших <strong>Vue 3</strong> додатків. Сьогодні ми розглянемо особливий випадок управління станом для тісно пов’язаних компонентів.</p><h4>Проблематика</h4><p>При розробці <strong>Vue</strong> додатків ми часто стикаємося з ситуацією, коли необхідно декомпозувати великий компонент на менші частини. Традиційний підхід із використанням <strong>props</strong> може створювати зайву складність, особливо коли компоненти тісно пов’язані та не потребують повторного використання.</p><h4>Рішення</h4><p>Замість стандартного підходу з <strong>props</strong>, я рекомендую використовувати зовнішнє сховище стану для компонентів, які:<br>- Є частиною єдиної функціональної області<br>- Використовуються виключно в межах одного батьківського компонента<br>- Мають інтенсивний обмін даними між собою</p><h4>Практична реалізація</h4><pre>// userState.ts<br>import { ref, reactive, readonly } from &#39;vue&#39;<br><br>export interface IUser {<br>  name: string<br>  age: number<br>  city: string<br>  lastUpdated?: Date<br>}<br><br>export const user = reactive&lt;IUser&gt;({<br>  name: &#39;Андрій&#39;,<br>  age: 25,<br>  city: &#39;Київ&#39;,<br>  lastUpdated: new Date()<br>})<br><br>export const viewsCount = ref(0)<br><br>export const useUserState = () =&gt; {<br>  const updateCity = (newCity: string) =&gt; {<br>    user.city = newCity<br>    user.lastUpdated = new Date()<br>  }<br><br>  const incrementViews = () =&gt; {<br>    viewsCount.value++<br>  }<br><br>  return {<br>    user: readonly(user),<br>    viewsCount: readonly(viewsCount),<br>    updateCity,<br>    incrementViews<br>  }<br>}<br><br>// MainProfile.vue<br>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { useUserState } from &#39;./userState&#39;<br>import UserInfo from &#39;./UserInfo.vue&#39;<br>import ViewsStatistics from &#39;./ViewsStatistics.vue&#39;<br><br>const { updateCity } = useUserState()<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;div class=&quot;profile-container&quot;&gt;<br>    &lt;UserInfo /&gt;<br>    &lt;ViewsStatistics /&gt;<br>    &lt;button @click=&quot;updateCity(&#39;Львів&#39;)&quot; class=&quot;update-btn&quot;&gt;<br>      Змінити місто<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>// UserInfo.vue<br>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { useUserState } from &#39;./userState&#39;<br><br>const { user } = useUserState()<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;div class=&quot;user-info&quot;&gt;<br>    &lt;h2&gt;Профіль користувача&lt;/h2&gt;<br>    &lt;p&gt;Ім&#39;я: {{ user.name }}&lt;/p&gt;<br>    &lt;p&gt;Вік: {{ user.age }}&lt;/p&gt;<br>    &lt;p&gt;Місто: {{ user.city }}&lt;/p&gt;<br>    &lt;p v-if=&quot;user.lastUpdated&quot;&gt;<br>      Оновлено: {{ user.lastUpdated.toLocaleString() }}<br>    &lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>// ViewsStatistics.vue<br>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { useUserState } from &#39;./userState&#39;<br><br>const { viewsCount, incrementViews } = useUserState()<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;div class=&quot;statistics&quot;&gt;<br>    &lt;p&gt;Кількість переглядів: {{ viewsCount }}&lt;/p&gt;<br>    &lt;button @click=&quot;incrementViews&quot; class=&quot;increment-btn&quot;&gt;<br>      Додати перегляд<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><h4>Переваги підходу</h4><p>1. <strong>Спрощена розробка</strong>: Відсутність необхідності описувати складні ланцюжки <strong>props</strong> та <strong>emits</strong>.</p><p>2. <strong>Типова безпека</strong>: Централізоване визначення типів у файлі стану спрощує підтримку типізації.</p><p>3. <strong>Інкапсуляція</strong>: Логіка управління станом ізольована в окремому модулі.</p><p>4. <strong>Продуктивність</strong>: Зменшення кількості перерендерів завдяки прямому доступу до стану.</p><h4>Застереження</h4><p>Цей підхід найкраще працює для тісно пов’язаних компонентів в межах однієї функціональної області. Для компонентів, які потребують повторного використання в різних частинах додатка, краще дотримуватися стандартного підходу з props.</p><h4>Висновок</h4><p>При розробці Vue 3 додатків важливо обирати правильні інструменти для конкретних випадків. Використання зовнішнього сховища стану для пов’язаних компонентів — це потужний патерн, який може значно покращити якість вашого коду та пришвидшити розробку.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf90f97e675f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>