724 lasījumi
724 lasījumi

Labie programmētāji vienmēr ir pārveidojoši

autors Doug Donohoe6m2025/05/11
Read on Terminal Reader

Pārāk ilgi; Lasīt

Lieli inženieri pastāvīgi refaktoru, pat ja tie ir slīdēt to savā parastajā darba plūsmā.
featured image - Labie programmētāji vienmēr ir pārveidojoši
Doug Donohoe HackerNoon profile picture
0-item


“Vienmēr jābūt slēgtam.”


Pārdošanas mantra noGlengarrijs Glen RossTādā pašā garā (bet ar daudz mazāk zvērestu), labam inženierim vajadzētuVienmēr jāatjaunoŠeit ir kāpēc.

Attīrīt vai neattīrīt

Parasti tiek pieņemts, ka tīru kodu ir vieglāk saprast, lētāk uzturēt un daudz paplašināt.


A common objection to refactoring is that there isn’t time to actually do it. Teams see it as a luxury. The relentless drive for new features simply doesn’t allow for refactoring, especially because refactoring changes nothing from an external point of view. That can be a hard sell to your product owner.


Tīrs kods samaksā pats par sevi un palēnina tehnisko parādu uzkrāšanos.


Tātad sneak to iekšā.


Tas ir pareizi. es ieteiktu nedaudz subterfuge. nedaudz maldi pat. Kāpēc ne notīrīt dažas lietas katrā vilkšanas pieprasījumā?

Esiet uzmanīgs

A good engineer has a vision of where the codebase should be heading. It might take a while to get there, but you know the messy parts, the backlog, the roadmap, the technical debt, the security holes, and the documentation gaps.


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: “Don’t let this opportunity pass!”Paņemiet dažas minūtes un izlabojiet to tagad, pirms iedvesma izzūd.


Neticiet, ka tā nav jūsu problēma, nedomājiet, ka to nevarat pamanīt, vienkārši ielieciet rokas un dariet to.

Vienkāršs piemērs

Refactoring doesn’t necessarily mean changing thousands of lines of code. It can be just a small chunk of code here and there. These little micro-refactorings add up over time. In fact, the more you get into the habit of constant cleanup, the less you will need to do major refactorings in the future.


Lai ilustrētu mikro-refaktorēšanu, aplūkosim Golanga “ekstrakcijas metodi” piemēru.


Pieņemsim, ka jūs risināt funkciju, kas prasa zināt, cik dienas ir pagājušas kopš lietotāja pēdējā pieteikšanās. Jūs pamanāt esošu metodi, kas nosaka, vai lietotājs ir miegains, izmantojot to pašu informāciju:


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, daysun izņemot to atsevišķā metodē,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).


It also makes future enhancements easier. For example, it might make sense to make IsDormant and DaysSinceLastLogin methods on the User struct instead of being standalone. Likewise, consider replacing the hard-coded value 8ar kaut ko vairāk aprakstošu kāDormantDaysThreshold.


Tas ir vienkāršs piemērs, tikai dažas koda līnijas. bet tas ir skaistums. tas parāda, ka neliels pārveidojums var pievienot vērtību, atklājot potenciālo kļūdu un norādot uz turpmākiem uzlabojumiem.


To learn more about the craft of refactoring and see all the small ways to improve your code, check out online resources such as the refactoring catalog from Martin Fowler’s book or the Refactoring Guru.

Atjaunojiet kataloguRefactoring Guru

A Refactoring Mindset

Ir viegli iegūt redzējumu par jūsu koda bāzi. Zinot, kā to iegūt, ir grūtāk. Refactoring iespēju atklāšana prasa praksi. Viens veids, kā sākt, ir apsvērt, kuras kategorijas refactoring ir nepieciešamas, lai pārveidotu savu kodu.


Šeit ir dažas kopīgas refaktorēšanas tēmas, par kurām jādomā:


🧹 Remove DuplicationKopēt un ielīmēt loģiku vienā funkcijā.

Extract Shared Utility or LibraryNormalizējiet integrācijas (piemēram, visi pakalpojumi izmanto to pašu auth klientu).

Add Common Infrastructure — Introduce observability (logging, tracing, metrics). Centralize error handling or retries.

Make Code More Testable — Break apart tightly coupled logic. Extract interfaces so dependencies can be mocked or stubbed.

Prepare for a Feature Change — Flatten complex conditionals or nested logic. Reorganize files or classes to fit new responsibilities.

Support a New ArchitectureIevadiet notikumu virzītus modeļus, atkarības injekciju vai async apstrādi.

Reduce Cognitive Load — Split giant files or classes into logical, focused units.

🔐 Improve Security or Compliance — Centralize access control logic. Refactor insecure patterns (e.g., manual SQL concatenation → parameterized queries).

🚀 Improve Performance— Aizstāt naivus algoritmus ar optimizētiem. samazināt atmiņas trūkumu vai nevajadzīgu aprēķinu karstajos ceļos.

👥 Ease Onboarding or Handoff— Refactor kods, ko tikai “Pat” saprot kaut ko komandas lasāmu. Ievadiet docs/comments/test coverage kā daļu no strukturālā tīrīšanas.

The 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.


Tomēr tiem vajadzētu būt vieglākai pārdošanai, jo, kad jūs sasniedzat punktu, kur jums ir nepieciešams pilnīgs, godīgs un labs refaktors, tas noteikti kalpos kādam lielākam mērķim.


For example, before working on a performance improvement ticket, you first need to add tracing and metrics so you can develop a finer picture of current performance and identify hotspots.

Atjaunošana sākas ar pārbaudi

It is probably self-evident, but I must point out that refactoring is much easier (and less nerve-racking) if your codebase has an accompanying suite of tests that pass before and after the refactoring. Having tests is also valuable for a bunch of other reasons. If your project doesn’t have strong testing, then add some tests first to unlock future refactorings.

Kodeksa pārskatīšanas apsvērumi

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.


Labs īkšķa noteikums jebkuram vilkšanas pieprasījumam ir ierobežot to līdz 500 koda līnijām.


When you do have dedicated refactoring PRs, keep it focused and around this size. Sometimes a PR has to be greater than 500 lines of code, especially when working on a repo-wide refactor. In those cases, coordinate well with your colleagues to prepare them for the change and to minimize merge conflicts.

Padarīt katru apņemšanos skaitīt

Katru reizi, kad pieskaraties koda bāzei, jums ir izvēle: atstāt to mazliet labāk, vai atstāt to mazliet sliktāk. Refactoring nav jābūt lielam notikumam. Mazie uzlabojumi (izņemot metodes, pārdēvējot neskaidras mainīgās, izjaucot garās metodes utt.) laika gaitā palielinās.


If you see something, fix something.


Vienmēr esiet atjaunojoši!

Trending Topics

blockchaincryptocurrencyhackernoon-top-storyprogrammingsoftware-developmenttechnologystartuphackernoon-booksBitcoinbooks