Menu

Post image 1
Post image 2
1 / 2
0

Functions vs Methods in Go: 6 Decision Criteria With Code Examples

DEV Community·Bala Paranj·28 days ago
#zw5nWQBL
#before#after#go#programming#function#method
Reading 0:00
15s threshold

When to use a method (owns the data, needs state, is the domain question), when to use a function (operates across types, is a utility, was incorrectly coupled), and when to move code in both directions. Go gives you two ways to attach behavior to logic: methods (with a receiver) and functions (without). Most languages make this decision for you — if it touches a class, it's a method. In Go, you have to choose. The wrong choice shows up as code issues: a free function that takes a type as its first argument (should be a method), a method that doesn't use its receiver (should be a function), or a method on the wrong type (should be on the type it operates on). Here are 6 decision criteria, each with a real before/after refactoring that moved code in the right direction — including two cases where methods became functions. 1.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More