„Vždy se zavřít.“ The hard-nosed sales mantra from Ve stejném duchu (ale s mnohem menším přísahou) by měl dobrý inženýr . Here’s why. Glengarry Glen Rossová always be refactoring Čistit nebo nečistit It’s generally agreed that clean code is easier to understand, cheaper to maintain, and much more extensible. At its core, refactoring is cleaning up existing code without altering its perceived functionality. Společnou námitkou vůči refaktoringu je, že není čas to skutečně udělat. Týmy to vnímají jako luxus. Neúnavná touha po nových funkcích jednoduše neumožňuje refaktoring, zejména proto, že refaktoring nemění nic z vnějšího hlediska. But clean code makes your life easier. Clean code pays for itself and slows the accumulation of technical debt. Tak se do toho sneak. To je pravda. Navrhuji trochu subterfuge. Trochu nesprávný směr dokonce. Proč ne vyčistit několik věcí v každé žádosti o stažení? Buďte ostražití Může to trvat nějakou dobu, než se tam dostanete, ale znáte nepořádné části, zpětnou vazbu, plán, technický dluh, bezpečnostní díry a mezery v dokumentaci. As you go about your regular feature development, be on the lookout for refactorings that can advance your larger agenda. Like one of those hyper-observant TV show detectives surveying a crime scene, pay close attention to all the code you stumble across. When you notice a code smell or something slightly off near your current focus, alarm bells should go off: Udělejte si pár minut a opravte to teď, než se inspirace vytratí. “Don’t let this opportunity pass!” Don’t say it’s not your problem. Don’t pretend you can unsee it. Just roll up your sleeves and get it done. A Simple Example Refactoring nemusí nutně znamenat změnu tisíců řádků kódu. Může to být jen malý kousek kódu tady a tam. Tyto malé mikro-refactoring se časem shromažďují. Pro ilustraci mikro-refaktorování se podívejme na příklad „metody extrakce“ Golanga. Let’s say you are tackling a feature that requires knowing how many days it has been since a user last logged in. You notice an existing method that determines if a user is dormant by using that same information: func IsDormant(user User, asOf time.Time) bool { days := int(asOf.Sub(user.LastLogin).Hours() / 24) return days >= 8 } You want to re-use the last login calculation instead of copying and pasting it, so you take the internal variable, , a extrahovat ji do samostatné metody, : days DaysSinceLastLogin func IsDormant(user User, asOf time.Time) bool { return DaysSinceLastLogin(user, asOf) >= 8 } func DaysSinceLastLogin(user User, asOf time.Time) int { return int(asOf.Sub(user.LastLogin).Hours() / 24) } This allows the last login logic to be tested and reused. If you write a unit test, you’ll spot an edge case that should be handled (a potential panic if a user has never logged in). To také usnadňuje budoucí vylepšení. Například může mít smysl vytvořit a methods on the struct instead of being standalone. Likewise, consider replacing the hard-coded value with something more descriptive like . IsDormant DaysSinceLastLogin User 8 DormantDaysThreshold To je jednoduchý příklad, jen pár řádků kódu. Ale to je krása. To ukazuje, že malé refaktoring může přidat hodnotu tím, že odhalí potenciální chybu a poukazuje na budoucí zlepšení. Chcete-li se dozvědět více o řemesle refaktoringu a vidět všechny malé způsoby, jak zlepšit svůj kód, podívejte se na online zdroje, jako je katalog refaktoringu z knihy Martina Fowlera nebo Refactoring Guru. refactoring catalog Refactoring Guru Reakční myšlení Mít vizi pro vaši kódovou základnu je snadné. Vědět, jak se tam dostat, je obtížnější. Zjištění příležitostí k refaktorování vyžaduje praxi. Jedním ze způsobů, jak začít, je zvážit, které kategorie refaktorování jsou nezbytné pro transformaci vašeho kódu. Zde jsou některé společné refaktoring témata přemýšlet o: — Collapse copy and pasted logic into a single function. 🧹 Remove Duplication ↓↓ — Move common logic out of per-service implementations. Normalize integrations (e.g., all services use the same auth client). Extract Shared Utility or Library ↓↓ — Introduce observability (logging, tracing, metrics). Centralize error handling or retries. Add Common Infrastructure ⚙️ - Roztrhněte těsně propojenou logiku. Extrahujte rozhraní tak, aby závislosti mohly být posměšněny nebo zkrouceny. Make Code More Testable 🔄 — Flatten complex conditionals or nested logic. Reorganize files or classes to fit new responsibilities. Prepare for a Feature Change 🏗️ — Rozbít monolit. Představí se vzory založené na událostech, injekce závislosti nebo asynchronní zpracování. Support a New Architecture ↓↓ Rozdělení obřích souborů nebo tříd na logické, zaměřené jednotky. Reduce Cognitive Load 🔐 — Centralize access control logic. Refactor insecure patterns (e.g., manual SQL concatenation → parameterized queries). Improve Security or Compliance ↓↓ — Replace naive algorithms with optimized ones. Reduce memory churn or unnecessary computation in hot paths. Improve Performance 👥 — Refactor code that only “Pat” understands into something team-readable. Introduce docs/comments/test coverage as part of structural cleanup. Ease Onboarding or Handoff Až 20 % Some might object that surely not all refactorings can be snuck in. I’ll grant you that. Let’s apply the 80–20 rule and stipulate that 20% of refactorings need to be done on the up-and-up. These should be an easier sell, however, because when you get to the point where you need a full, honest-to-goodness refactor, it is most definitely going to be in service of some larger goal. Například předtím, než začnete pracovat na lístku na zlepšení výkonu, musíte nejprve přidat sledování a metriky, abyste mohli vytvořit lepší obraz o aktuálním výkonu a identifikovat hotspoty. Rekonstrukce začíná testováním Je to pravděpodobně samozřejmé, ale musím poukázat na to, že refaktorování je mnohem jednodušší (a méně nervové), pokud má vaše kódová základna doprovodnou sadu testů, které projdou před a po refaktorování. Pokud váš projekt nemá silné testování, nejprve přidejte některé testy, abyste odemkli budoucí refaktory. bunch of other reasons Code Review Considerations My advice in this article runs counter to the standard guideline to not mix refactoring work and regular feature development. The objection is that it makes it harder for the team to do code reviews if unrelated changes are included. That’s a fair point. When refactoring during feature work, keep it small and (ideally) related to the main thrust of the change. Dobrým pravidlem pro každou žádost o stažení je omezit ji na 500 řádků změn kódu.Druhým pravidlem je, že pomocné změny refaktoringu by neměly být více než 20% PR. Někdy musí být PR větší než 500 řádků kódu, zejména při práci na repo-širokém refaktoru. V těchto případech dobře koordinujte se svými kolegy, aby je připravili na změnu a minimalizovali konflikty spojené. Make Every Commit Count Every time you touch the codebase, you have a choice: leave it a little better, or leave it a little worse. Refactoring doesn’t have to be a grand event. Small improvements (extracting methods, renaming confusing variables, breaking apart long methods, etc.) add up over time. They prevent technical debt from piling up and make future changes easier and safer. If you see something, fix something. Always be refactoring!