Telegram Group & Telegram Channel
Анти-функциональные опции в Go

Часто в Go можно встретить такую конструкцию:


type Options struct {
Timeout time.Duration
Retries int
Logger *log.Logger
}

func DoSomething(ctx context.Context, opts Options) error {
if opts.Timeout == 0 {
opts.Timeout = 5 * time.Second
}
if opts.Retries == 0 {
opts.Retries = 3
}
if opts.Logger == nil {
opts.Logger = log.Default()
}

// дальше используем opts
}


На первый взгляд — удобно. Но на практике это ведёт к скрытым багам и неочевидному поведению. Почему?

🔸 Проблема 1: нулевое значение может быть валидным

Допустим, я хочу отключить ретраи и передаю Retries: 0. Но функция решает, что "ноль — это дефолт", и перезаписывает его на 3. В итоге получается поведение, которого явно не хотел.

🔸 Проблема 2: смешение ответственности

Функция DoSomething теперь делает больше, чем нужно: она и бизнес-логику выполняет, и значения инициализирует. Это противоречит принципу единственной ответственности и усложняет тестирование.

🔸 Проблема 3: дублирование

Если в коде много таких функций, каждая будет по-своему инициализировать Options. Это ведёт к дублированию и рассыпанной логике дефолтов.


💡 Что делать?

Вынеси дефолтные значения в отдельную функцию:


func DefaultOptions() Options {
return Options{
Timeout: 5 * time.Second,
Retries: 3,
Logger: log.Default(),
}
}


Теперь клиентский код выглядит явно:


opts := DefaultOptions()
opts.Retries = 0 // без ретраев

DoSomething(ctx, opts)


https://rednafi.com/go/dysfunctional_options_pattern/

👉 @golang_lib



tg-me.com/golang_lib/492
Create:
Last Update:

Анти-функциональные опции в Go

Часто в Go можно встретить такую конструкцию:


type Options struct {
Timeout time.Duration
Retries int
Logger *log.Logger
}

func DoSomething(ctx context.Context, opts Options) error {
if opts.Timeout == 0 {
opts.Timeout = 5 * time.Second
}
if opts.Retries == 0 {
opts.Retries = 3
}
if opts.Logger == nil {
opts.Logger = log.Default()
}

// дальше используем opts
}


На первый взгляд — удобно. Но на практике это ведёт к скрытым багам и неочевидному поведению. Почему?

🔸 Проблема 1: нулевое значение может быть валидным

Допустим, я хочу отключить ретраи и передаю Retries: 0. Но функция решает, что "ноль — это дефолт", и перезаписывает его на 3. В итоге получается поведение, которого явно не хотел.

🔸 Проблема 2: смешение ответственности

Функция DoSomething теперь делает больше, чем нужно: она и бизнес-логику выполняет, и значения инициализирует. Это противоречит принципу единственной ответственности и усложняет тестирование.

🔸 Проблема 3: дублирование

Если в коде много таких функций, каждая будет по-своему инициализировать Options. Это ведёт к дублированию и рассыпанной логике дефолтов.


💡 Что делать?

Вынеси дефолтные значения в отдельную функцию:


func DefaultOptions() Options {
return Options{
Timeout: 5 * time.Second,
Retries: 3,
Logger: log.Default(),
}
}


Теперь клиентский код выглядит явно:


opts := DefaultOptions()
opts.Retries = 0 // без ретраев

DoSomething(ctx, opts)


https://rednafi.com/go/dysfunctional_options_pattern/

👉 @golang_lib

BY Библиотека Go (Golang) разработчика




Share with your friend now:
tg-me.com/golang_lib/492

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Telegram Gives Up On Crypto Blockchain Project

Durov said on his Telegram channel today that the two and a half year blockchain and crypto project has been put to sleep. Ironically, after leaving Russia because the government wanted his encryption keys to his social media firm, Durov’s cryptocurrency idea lost steam because of a U.S. court. “The technology we created allowed for an open, free, decentralized exchange of value and ideas. TON had the potential to revolutionize how people store and transfer funds and information,” he wrote on his channel. “Unfortunately, a U.S. court stopped TON from happening.”

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

telegram from ye


Telegram Библиотека Go (Golang) разработчика
FROM USA