724 mga pagbabasa
724 mga pagbabasa

Good Programmers Always Be Refactoring

sa pamamagitan ng Doug Donohoe6m2025/05/11
Read on Terminal Reader

Masyadong mahaba; Upang basahin

Great engineers refactor constantly, kahit na sila ay dapat i-slip ito sa kanilang normal na workflow.
featured image - Good Programmers Always Be Refactoring
Doug Donohoe HackerNoon profile picture
0-item


“Alam mo lang ang closing.”


The hard-nosed sales mantra from Glengarry Glen RossAng maliliit na negosyo sa mga sumusunod na sektor ay kinakailangan: pagproseso ng produktong agrikultural (always be refactoring. Here’s why.

To Clean or Not to Clean

Ito ay karaniwang nakikipag-ugnay na clean code ay mas madaling malaman, mas madaling magtatrabaho, at higit pa sa mas extendable. Sa kanyang pangkalahatan, refactoring ay pagtatrabaho ng kasalukuyang code nang hindi maiwasan ang kanyang nakikita na functionality.


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.


But clean code makes your life easier. Clean code pays for itself at mabawasan ang pag-akumulasyon ng technical debt.


So sneak it in.


That’s right. I’m suggesting a slight bit of subterfuge. A little misdirection even. Why not clean up a few things in every pull request?

Huwag mag-alala

Ang isang mahusay na engineer ay may isang visyon ng kung saan ang code base ay dapat pumunta. Maaari itong kumuha ng isang oras upang makakuha ng ito, ngunit alam mo ang mga bagay na mabuti, ang backlog, ang roadmap, ang mga teknolohiya na utang, ang seguridad na mga hulog, at ang mga dokumento na hulog.


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.


Kapag nakikita mo ang isang code odor o isang bagay na malaki off malapit sa iyong kasalukuyang focus, ang alarm bells ay dapat i-shut down:“Huwag kang mag-save ang pagkakataon!”Gawin ang ilang minuto at i-fix ito ngayon, bago ang inspirasyon ay umalis.


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

Hindi kailangan ng "common sense" kundi "sense of humor" para maintindihan ito at matawa.


Upang ilarawan ang micro-refactoring, tingnan natin ang isang "extract method" Golang halimbawa.


Tingnan mo na ikaw ay nagtatrabaho sa isang tampok na kailangan mong malaman kung ano ang ilang araw na ito ay nagsimula mula sa isang user last logged in. Ipakita mo ang isang kasalukuyang pamamaraan na magtatagumpay kung ang isang user ay dormant gamit ang parehong impormasyon:


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, daysat i-extract ito sa isang partikular na paraan,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 DaysSinceLastLoginAng mga metriko para saUserat malapit na ding maging isang trahedya, malapit na ang isang trahedya8Sa isang mas simpleng bagay, tulad ngDormantDaysThreshold.


Ito ay isang simpleng halimbawa, lamang ang ilang mga linya ng code. Ngunit ito ay ang beauty. Ito ay nagpapakita ng isang maliit na refactoring ay maaaring magbigay ng halaga sa pamamagitan ng ipakita ng isang potensyal na bug at nagpapakita sa mga future improvements.


Upang malaman ang higit pa tungkol sa pakikipagtulungan ng refactoring at makita ang lahat ng mga maliit na paraan upang mapabuti ang iyong code, tingnan ang mga online resource tulad ng refactoring catalog mula sa libro ni Martin Fowler o ang Refactoring Guru.

Paglalarawan ng CatalogueRefactoring Guru

A Refactoring Mindset

Magkaroon ng isang visyon para sa iyong codebase ay madali. Malaman kung paano makakuha ng ito ay mas malaki. Pagpapatakbo ng mga pagkakataon sa refactoring ay nangangailangan ng pagsasanay. Isang paraan upang magsimula ay upang i-consider kung ano ang mga kategorya ng refactoring ay kinakailangan upang i-transform ang iyong code.


Narito ang ilang mga pangkalahatang refactoring mga tema upang mahanap:


🧹 Remove Duplication— I-collapse ang kopya at ipasok ang logic sa isang single function.

🧰 Extract Shared Utility or Library— I-move common logic out ng per-service implementations. Normalize integrations (e.g., ang lahat ng mga serbisyo ay gumagamit ng parehong auth client).

🧱 Add Common Infrastructure— Ipasok ang observability (logging, tracing, metrics). Centralize ang paghahatid ng error o retries.

⚙️ Make Code More TestableI-extract ang mga interfaces para sa dependencies ay maaaring maging mocked o stubbed.

angPrepare for a Feature Change— Flatten complex conditionals o nested logic. Reorganize mga file o mga klase upang matatagpuan ang mga bagong responsibilidad.

Support a New Architecture — Break apart a monolith. Introduce event-driven patterns, dependency injection, or async processing.

angReduce Cognitive Load- Split giant na mga file o mga klase sa logical, focused mga unit.

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

angImprove Performance— Substitute naive algorithms sa mga optimized. Reduce memory churn o unnecessary computing sa hot paths.

angEase Onboarding or Handoff— Refactor code na lamang "Pat" ay makikita sa isang bagay na makikita ng team. I-introduce docs/comments/test coverage bilang bahagi ng structural cleanup.

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.


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.


Halimbawa, bago magtrabaho sa isang performance improvement ticket, kailangan mo upang sumali ng tracking at mga metric upang makukuha ng mas mahusay na picture ng kasalukuyang pagganap at i-identify ang mga hotspots.

Refactoring nagsimula sa pagsubok

Ito ay mahirap, ngunit dapat kong ipakita na ang refactoring ay mas madaling mas madaling (at mas madaling nerve-racking) kung ang iyong codebase ay may isang kumpanya na suite ng mga pagsusuri na pumapasok bago at pagkatapos ng refactoring.isang bundok ng iba pang mga dahilan. If your project doesn’t have strong testing, then add some tests first to unlock future refactorings.

Mga review ng Code

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.


A good rule of thumb for any pull request is to limit it to 500 lines of code changes. A second rule of thumb is that ancillary refactoring changes should be no more than 20% of the PR.


Pero kapag nalaman niyang nakilala mo siya dahil binasa mo ang diary... get ready for the consequences.

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.


Kapag nakikita mo ang isang bagay, ayusin ang isang bagay.


Always ang refactoring!

Trending Topics

blockchaincryptocurrencyhackernoon-top-storyprogrammingsoftware-developmenttechnologystartuphackernoon-booksBitcoinbooks