Похожие чаты

Hey! Is there any advantages of having repeated lines extracted

to a method, when they are only repeating once?·

11 ответов

14 просмотров
s0m31-🇷🇺 Автор вопроса
s0m31 🇷🇺
screenshot

I dont follow you. are you trying to say that both code examples are similar in code quality?

s0m31-🇷🇺 Автор вопроса

Is the quality of second code really better when it comes to launching method only twice?

Read about DRY pattern

s0m31 🇷🇺
Is the quality of second code really better when i...

Here are a few scenarios: - A future developer wants to do the same thing as you. They dont find a method to do it, so they reimplement it. You now have three versions of the problem - Your system has a bug. You fix the bug in the first loop but forget that you have a copy of it somewhere else. Suddenly the two versions drift appart, they do the same thing, but one has a bug the other one doesnt - A developer wants to quickly understand what you do. Instead of reading a simple method name, they need to understand your loop. And they need to understand it twice! Your first code is absolutely not good and would not pass a code review. Keep in mind that your software might run 20-30-40 years. And people will need to update or bugfix it

+1 to every point that @BinaryByter posted, each one is very-very true. And two another arguments to extract them into a method. - Only you know that these two fragments are identical. But not your colleagues. When they will read it, I bet they will spend quite a time to understand whether it's duplicated or has a tiny difference. Because first thought that comes to mind when you see those two pieces - they got to be slightly different, otherwise the author would have extracted it into a method. - What will you win if you won't extract it? Absolutely nothing. Well, maybe 30s-1min of time (in GOOD code of course). But you will get that 1m back and even more, when "future you" will read it later and instead of spending 5-10s to grasp what those pieces are doing, will read a nice clean extracted private method name like "findReportsWithCloseDates" (point N3 from @BinaryByter ). Your code has other significant style (actually "construction", in McConnell's terms) problems, and extracting that piece into a method may become a pain and take much more compared to those mentioned 5-10s in good code. This leads me to another point, not strictly related to your question. Your code style/construction has much bigger issues than few duplicated lines. Even though it's hard to say much without seeing the full class, but I recognize intellij IDE and the way how it uses italic font for *STATIC* fields. Not only you have the HUGE problem that @sanderkoenders mentioned that your methods are non-pure, you also have some global state in those static fields which you modify from instance methods. I can't even express how ugly it looks for experienced eye. It's the same as in C you would declare global variables, which old code is plagued by. Just google for something like "programming why global state is bad". So I highly recommend you two things: - get rid of global state, don't use static fields for anything else than compile-time or initialization time *constants*; and also use static methods only for pure functions (google for something like "programming what is pure function") - make your levelDates to be pure function, don't modify outer state inside of it, and instead receive all the necessary data as parameters, don't modify parameters and create new/copy objects/collections for output. Just like @sanderkoenders suggested you, that's extremely valuable recommendation. I can't even express how important this is to do. Right now your code is hard to maintain, it's very tightly coupled, it's like a web where if you pull one string, it touches all the other. Just like Sander mentioned - somebody changes order/number of execution of your method, and it all may break. Or somebody calls some other method that changes that global static state, and your method may break. You should instead organize your code as Lego pieces - independent, self-contained, loosely-coupled, easily reusable, and easily modifiable. These two recommendations will help you to achieve it.

PS: generic method names like "walk" is terrible.

s0m31-🇷🇺 Автор вопроса
Dmytro Buryak
+1 to every point that @BinaryByter posted, each ...

Both removing static keywords and making levelDates a pure function is a bad idea in this class. It is used to store data that every other class may access

s0m31 🇷🇺
Both removing static keywords and making levelDate...

What kind of app is this? Is it server/backend app? Or is it CLI, frontend, etc.?

s0m31-🇷🇺 Автор вопроса

Backend. I was planning to send you a diagram of how this class works bit later and ask if you have any better options than this static variable

s0m31 🇷🇺
Backend. I was planning to send you a diagram of h...

Then 99.99% you're doing it wrong. If you store data like that, you're making your application stateful and non-scalable. You won't be able to run 2+ instances if load increases. Which practically means your app can't do the job properly

Похожие вопросы

Обсуждают сегодня

А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Подскажите, где смотреть результат выполнения программы? Код: ;.686 ;Система команд процессора 686 ;.MODEL FLAT,stdcall ;Модель памяти плоская, станда...
Егор Анелькин
4
I arrived here after a Chico Crypto show highlighted the project & the Team - the fact that the Team had a long history of successfully working with household names gave me e...
Banter is Bullish
1
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
Привет всем. появился вопрос. Разрабатываю сайт, в данный момент он запущен. Хостинг beget. Добавляю на сайт яндекс метрику с помощью полей client-settings (взято отсюда http...
Andrew
2
;.686 ;Система команд процессора 686 ;.MODEL FLAT,stdcall ;Модель памяти плоская, стандартный ;вызов процедуры ;option casemap:no...
Егор Анелькин
1
Почему у макбука экран не сенсорный?
✨ Anatolii Cherednichenko
28
It's unfortunate that the "Then why are you here" or "lol you must've bought high" mantras always come up. I already tried bringing up this subject in the price channel but si...
Leroy Gerrits
4
Так а кто может спарсить всех участников чата? Идишники
Magic
17
Есть вопрос: допустим есть железка с каким-то интерфейсом(допустим usb), но как по этому интерфейсу железкой управлять неизвестно, прог нету, а управлять очень хочется надо. К...
Mixail Frolov
15
Карта сайта