Forwarded from Архитектура ИТ-решений
📆 29 июня 10:30 MSK
Решил продолжить в формате вебинаров. Послезавтра расскажу историю о том, как раньше проектирование помогало сбалансировать потребности и возможности заказчика и что случилось с этой деятельностью в наши дни.
Регистрироваться не надо. Просто подключайтесь по ссылке: https://youtu.be/4P5DLoaGPks
Решил продолжить в формате вебинаров. Послезавтра расскажу историю о том, как раньше проектирование помогало сбалансировать потребности и возможности заказчика и что случилось с этой деятельностью в наши дни.
Регистрироваться не надо. Просто подключайтесь по ссылке: https://youtu.be/4P5DLoaGPks
Forwarded from Архитектура ИТ-решений
Кстати, еще один SaaS про модель C4: https://carbide.dev/ Сервис называет C4RBIDE. Пока все бесплатно
carbide.dev
Carbide · C4 Model Software Architecture Tool
Stop diagramming and start modelling. Model your C4 software architecture with Carbide and share your vision with your team and colleagues today.
Russian Association of Software Architects
Сегодня Big Design Up Front (BDUF) даже в проектах средней величины практически не применяется. Обрабатывать неопределенность заблаговременно (Prediction), путем логического вывода - это очень дорогая задача, стоимость которой может достигать экспоненциального…
Каким же образом распространение эмпирического способа разрешения неопределенности отразилось на архитектуру?
Если раньше основным фокусом архитектуры считалось предвидение развития системы (Prediction):
💬 "Architecture is the decisions that you wish you could get right early in a project, but that you are not necessarily more likely to get them right than any other." — Ralph Johnson
То теперь её фокусом стала изменяемость (Adaptation), т.е. максимизация открытых решений, где их открытость определяется стоимостью их изменения:
💬 "A good architect pretends that the decision has not been made, and shapes the system such that those decisions can still be deferred or changed for as long as possible. A good architect maximizes the number of decisions not made."
—"Clean Architecture: A Craftsman's Guide to Software Structure and Design" by Robert C. Martin
Если вдруг кто не помнит - именно Robert C. Martin организовал Snowbird встречу 2001 года по Agile Manifesto.
Про смену фокуса говорится и в стандарте:
💬 "The incremental and iterative nature of Agile development can facilitate efficient technical and management processes and practices to reduce the cost associated with change. In comparison, projects managed at the waterfall end of the continuum seek to reduce total rework cost by minimizing the number of changes, limiting the number of control points, and baselining detailed specifications which are reviewed and traced throughout the project."
—"ISO/IEC/IEEE 12207:2017 Systems and software engineering - Software life cycle processes"
Забегая наперед, скажем, что не все так просто, и:
💬 "Agile Architecture shall seek a balance between intentional and emerging."
—"Open Agile Architecture™" by The Open Group, Chapter "9.14. Axiom 14. Bias for Change"
#SoftwareArchitecture #Agile #SDLC
Если раньше основным фокусом архитектуры считалось предвидение развития системы (Prediction):
💬 "Architecture is the decisions that you wish you could get right early in a project, but that you are not necessarily more likely to get them right than any other." — Ralph Johnson
То теперь её фокусом стала изменяемость (Adaptation), т.е. максимизация открытых решений, где их открытость определяется стоимостью их изменения:
💬 "A good architect pretends that the decision has not been made, and shapes the system such that those decisions can still be deferred or changed for as long as possible. A good architect maximizes the number of decisions not made."
—"Clean Architecture: A Craftsman's Guide to Software Structure and Design" by Robert C. Martin
Если вдруг кто не помнит - именно Robert C. Martin организовал Snowbird встречу 2001 года по Agile Manifesto.
Про смену фокуса говорится и в стандарте:
💬 "The incremental and iterative nature of Agile development can facilitate efficient technical and management processes and practices to reduce the cost associated with change. In comparison, projects managed at the waterfall end of the continuum seek to reduce total rework cost by minimizing the number of changes, limiting the number of control points, and baselining detailed specifications which are reviewed and traced throughout the project."
—"ISO/IEC/IEEE 12207:2017 Systems and software engineering - Software life cycle processes"
Забегая наперед, скажем, что не все так просто, и:
💬 "Agile Architecture shall seek a balance between intentional and emerging."
—"Open Agile Architecture™" by The Open Group, Chapter "9.14. Axiom 14. Bias for Change"
#SoftwareArchitecture #Agile #SDLC
martinfowler.com
Writing The Agile Manifesto
A long-form article entitled: "Writing The Agile Manifesto"
🔥4👍1
Russian Association of Software Architects
Каким же образом распространение эмпирического способа разрешения неопределенности отразилось на архитектуру? Если раньше основным фокусом архитектуры считалось предвидение развития системы (Prediction): 💬 "Architecture is the decisions that you wish you…
В предыдущем посте проскочил термин Agile. Да и в чате канала тоже этот термин не был обделен вниманием. Вероятно, теперь самое время разобраться с тем, что это такое. Удивительно, но будучи одним из самых обсуждаемых терминов, он остается одним из самых непонятных для многих.
💬 "Agile development - software development approach based on iterative development, frequent inspection and adaptation, and incremental deliveries, in which requirements and solutions evolve through collaboration in cross‐functional teams and through continual stakeholder feedback."
—"ISO/IEC/IEEE 12207:2017 Systems and software engineering - Software life cycle processes"
А вот, что говорит сам Jeff Sutherland - сооснователь Scrum:
💬 "Scrum is, as the reader supposedly knows, an agile method. The agile family of development methods evolved from the old and well-known iterative and incremental life-cycle approaches. They were born out of a belief that an approach more grounded in human reality – and the product development reality of learning, innovation, and change – would yield better results."
—"Jeff Sutherland's Scrum Handbook" by Jeff Sutherland
Agile модель разработки расширяет итеративно-инкрементальную модель и привносит в нее еще ряд психологически-философских принципов с целю устранения напряжения между представителями бизнеса и техническими специалистами. Но основное назначение остается прежним - разрешение неопределенности опытным путем (Adaptation):
💬 "No crystal balls. Humans are not able to predict the future. For example, your competition makes an announcement that was not expected. Unanticipated technical problems crop up that force a change in direction. Furthermore, people are particularly bad at planning uncertain things far into the future – guessing today how you will be spending your week eight months from now is something of a fantasy. It has been the downfall of many a carefully constructed Gantt chart."
—"Jeff Sutherland's Scrum Handbook" by Jeff Sutherland
Ладно, Jeff Sutherland - заинтересованное лицо. Он может быть субъективен, да и не все архитекторы его жалуют, а некоторые даже считают его угрозой для архитектуры. Послушаем лучше Gregor Hohpe:
💬 "Agile methods are most valuable when we're dealing with high levels of uncertainty."
—"Agile and Architecture: Friend, not Foe" by Gregor Hohpe
Ну и нельзя обойти в вопросе "Предвидеть" vs "Адаптировать" известную статью на эту тему:
"The New Methodology :: Predictive versus Adaptive" by Martin Fowler
#Agile #SDLC
💬 "Agile development - software development approach based on iterative development, frequent inspection and adaptation, and incremental deliveries, in which requirements and solutions evolve through collaboration in cross‐functional teams and through continual stakeholder feedback."
—"ISO/IEC/IEEE 12207:2017 Systems and software engineering - Software life cycle processes"
А вот, что говорит сам Jeff Sutherland - сооснователь Scrum:
💬 "Scrum is, as the reader supposedly knows, an agile method. The agile family of development methods evolved from the old and well-known iterative and incremental life-cycle approaches. They were born out of a belief that an approach more grounded in human reality – and the product development reality of learning, innovation, and change – would yield better results."
—"Jeff Sutherland's Scrum Handbook" by Jeff Sutherland
Agile модель разработки расширяет итеративно-инкрементальную модель и привносит в нее еще ряд психологически-философских принципов с целю устранения напряжения между представителями бизнеса и техническими специалистами. Но основное назначение остается прежним - разрешение неопределенности опытным путем (Adaptation):
💬 "No crystal balls. Humans are not able to predict the future. For example, your competition makes an announcement that was not expected. Unanticipated technical problems crop up that force a change in direction. Furthermore, people are particularly bad at planning uncertain things far into the future – guessing today how you will be spending your week eight months from now is something of a fantasy. It has been the downfall of many a carefully constructed Gantt chart."
—"Jeff Sutherland's Scrum Handbook" by Jeff Sutherland
Ладно, Jeff Sutherland - заинтересованное лицо. Он может быть субъективен, да и не все архитекторы его жалуют, а некоторые даже считают его угрозой для архитектуры. Послушаем лучше Gregor Hohpe:
💬 "Agile methods are most valuable when we're dealing with high levels of uncertainty."
—"Agile and Architecture: Friend, not Foe" by Gregor Hohpe
Ну и нельзя обойти в вопросе "Предвидеть" vs "Адаптировать" известную статью на эту тему:
"The New Methodology :: Predictive versus Adaptive" by Martin Fowler
#Agile #SDLC
Telegram
RASA Chat
Группа тг-канала объединения ИТ-архитекторов (@ru_arc)
Правила группы: https://t.me/ru_arc_chat/2036
По бизнес-вопросам (ИП, ООО, ВЭД):
@rasa_business
Практические кейсы:
@archicases
Предложить доклад для митапа: @ru_arc_meetup_bot
Правила группы: https://t.me/ru_arc_chat/2036
По бизнес-вопросам (ИП, ООО, ВЭД):
@rasa_business
Практические кейсы:
@archicases
Предложить доклад для митапа: @ru_arc_meetup_bot
🔥5👍4🤯2🤔1
"Забудьте САР теорему как более не актуальную" - перевод бомбовой статьи Martin Kleppmann от @kwiscakh
Уже не ново, но как никогда актуально.
#DistributedSystems
Уже не ново, но как никогда актуально.
#DistributedSystems
Хабр
Забудьте САР теорему как более не актуальную
или «Прекратите характеризовать хранилища данных как CP или AP» Джеф Ходжес в своем прекрасном посте « Заметки о распределенных системах для новичков » рекомендует использовать САР теорему для критики...
🔥6👍2
Russian Association of Software Architects
В предыдущем посте проскочил термин Agile. Да и в чате канала тоже этот термин не был обделен вниманием. Вероятно, теперь самое время разобраться с тем, что это такое. Удивительно, но будучи одним из самых обсуждаемых терминов, он остается одним из самых непонятных…
Ладно, Robert C. Martin - лицо тоже заинтересованное. Все-таки Agile - его детище, и все его призывы к гибкой архитектуре можно списать на то, что ему нужно пропагандировать новое, отрицая старое. Да и в архитектурных кругах отношение к нему неоднозначное. А вот Grady Booch к нему на встречу Agile Manifesto в 2001-м не приехал, хотя был приглашен. Говорит, что был занят. Да и Len Bass в пропаганде Agile особо замечен не был. Посмотрим, что они говорят:
💬 "Grady Booch has also provided a set of guidelines for an agile architecture (which in turn imply some duties for the agile architect). Booch claims that all good software-intensive architectures are agile. What does he mean by this? He means that a successful architecture is resilient and loosely coupled. It is composed of a core set of well-reasoned design decisions but still contains some "wiggle room" that allows modifications to be made and refactorings to be done, without ruining the original structure.
Booch also notes that an effective agile process will allow the architecture to grow incrementally as the system is developed and matures. The key to success is to have decomposability, separation of concerns, and near-independence of the parts. (Sound familiar? These are all modifiability tactics.)
Finally, Booch notes that to be agile, the architecture should be visible and self-evident in the code; this means making the design patterns, cross-cutting concerns, and other important decisions obvious, well communicated, and defended. This may, in turn, require documentation. But whatever architectural decisions are made, the architect must make an effort to "socialize" the architecture."
—"Software Architecture in Practice" 3d edition by Len Bass, Paul Clements, Rick Kazman
P.S.: Кстати, этот график можно встретить у Len Bass в 3-м издании книги "Software Architecture in Practice" by Len Bass, Paul Clements, Rick Kazman, в главе "15 Architecture in Agile Project :: 15.1 How Much Architecture?".
Уже, правда, существует 4-е издание. Там в главе "24.3 Architecture and Agile Development" он приводит уже немного другие графики для понимания. Лично мне 3-е издание нравилось больше.
#SoftwareArchitecture #Agile
💬 "Grady Booch has also provided a set of guidelines for an agile architecture (which in turn imply some duties for the agile architect). Booch claims that all good software-intensive architectures are agile. What does he mean by this? He means that a successful architecture is resilient and loosely coupled. It is composed of a core set of well-reasoned design decisions but still contains some "wiggle room" that allows modifications to be made and refactorings to be done, without ruining the original structure.
Booch also notes that an effective agile process will allow the architecture to grow incrementally as the system is developed and matures. The key to success is to have decomposability, separation of concerns, and near-independence of the parts. (Sound familiar? These are all modifiability tactics.)
Finally, Booch notes that to be agile, the architecture should be visible and self-evident in the code; this means making the design patterns, cross-cutting concerns, and other important decisions obvious, well communicated, and defended. This may, in turn, require documentation. But whatever architectural decisions are made, the architect must make an effort to "socialize" the architecture."
—"Software Architecture in Practice" 3d edition by Len Bass, Paul Clements, Rick Kazman
P.S.: Кстати, этот график можно встретить у Len Bass в 3-м издании книги "Software Architecture in Practice" by Len Bass, Paul Clements, Rick Kazman, в главе "15 Architecture in Agile Project :: 15.1 How Much Architecture?".
Уже, правда, существует 4-е издание. Там в главе "24.3 Architecture and Agile Development" он приводит уже немного другие графики для понимания. Лично мне 3-е издание нравилось больше.
#SoftwareArchitecture #Agile
Telegram
Igor Bespalchuk in RASA Chat
👍4🔥3
Russian Association of Software Architects
Ладно, Robert C. Martin - лицо тоже заинтересованное. Все-таки Agile - его детище, и все его призывы к гибкой архитектуре можно списать на то, что ему нужно пропагандировать новое, отрицая старое. Да и в архитектурных кругах отношение к нему неоднозначное.…
💬 "One trade-off that’s often overlooked is between the number of options you have and the resulting complexity. More options are desirable, but wanting to have all options all the time will result in unnecessary complexity, as is often the case with overly elaborate abstraction layers or massive configuration frameworks. I captured this effect into Gregor’s Law:
Excessive complexity is nature’s punishment for organizations that are unable to make decisions."
-- "Gregor's Law. Excessive complexity is nature’s punishment for organizations that are unable to make decisions" by Gregor Hohpe
💬 "If you pick any one aspect of software then you can make it easy to change, but we don’t know how to make everything easy to change. Making something easy to change makes the overall system a little more complex, and making everything easy to change makes the entire system very complex. Complexity is what makes software hard to change. That, and duplication."
-- Ralf Johnson at "Who Needs an Architect?" by Martin Fowler
Изменяемость тоже имеет свою стоимость. Нельзя создавать бесконечно гибкое решение. Важен баланс.
#SDLC #SoftwareArchitecture
Excessive complexity is nature’s punishment for organizations that are unable to make decisions."
-- "Gregor's Law. Excessive complexity is nature’s punishment for organizations that are unable to make decisions" by Gregor Hohpe
💬 "If you pick any one aspect of software then you can make it easy to change, but we don’t know how to make everything easy to change. Making something easy to change makes the overall system a little more complex, and making everything easy to change makes the entire system very complex. Complexity is what makes software hard to change. That, and duplication."
-- Ralf Johnson at "Who Needs an Architect?" by Martin Fowler
Изменяемость тоже имеет свою стоимость. Нельзя создавать бесконечно гибкое решение. Важен баланс.
#SDLC #SoftwareArchitecture
The Architect Elevator
Gregor’s Law
Excessive complexity is nature’s punishment for organizations that are unable to make decisions.
🔥3👍1🤯1
Russian Association of Software Architects
💬 "One trade-off that’s often overlooked is between the number of options you have and the resulting complexity. More options are desirable, but wanting to have all options all the time will result in unnecessary complexity, as is often the case with overly…
FIGURE 3.6 Make decisions at the last responsible moment. The image source is "Essential Scrum: A Practical Guide to the Most Popular Agile Process" by Kenneth Rubin, "Chapter 3 Agile Principles :: Prediction and Adaptation".
👍2🔥2
Russian Association of Software Architects
FIGURE 3.6 Make decisions at the last responsible moment. The image source is "Essential Scrum: A Practical Guide to the Most Popular Agile Process" by Kenneth Rubin, "Chapter 3 Agile Principles :: Prediction and Adaptation".
💬 "Most of us would prefer to wait until we have more information so that we can make a more informed decision. When dealing with important or irreversible decisions, if we decide too early and are wrong, we will be on the exponential part of the cost-of-deciding curve in Figure 3.6. As we acquire a better understanding regarding the decision, the cost of deciding declines (the likelihood of making a bad decision declines because of increasing market or technical certainty). That's why we should wait until we have better information before committing to a decision."
—"Essential Scrum: A Practical Guide to the Most Popular Agile Process" by Kenneth Rubin, "Chapter 3 Agile Principles :: Prediction and Adaptation"
Более того, этот баланс Prediction/Adaptation зависит от конкретных условий проекта и исторического контекста. В конце 90-х снижалась стоимость адаптации, а системы были простыми. Сегодня средняя система на рынке стала на порядки сложней, стоимость адаптации диспропорционально возросла, но зато удешевляется Prediction, за счет появления Event Storming и других легковесных методик.
Стоимость Prediction не константна по отношению к жизненному циклу системы, и имеет тенденцию к понижению по мере реализации проекта.
Тот же Len Bass в вопросах поиска этого баланса ссылается на книгу "Balancing Agility and Discipline: A Guide for the Perplexed" by Barry Boehm, Richard Turner, которая вышла в свет через 2 года после Agile Manifesto.
Но это уже вопрос организации процессов разработки, в то время как этот месяц у нас посвящен (по результатам опроса) вопросам качества кода. Т.е. в данном контексте нас интересует не поиск оптимального баланса Prediction/Adaptation (хотя этот вопрос тоже важен, и можно продолжить его обсуждение в чате канала), а способ достижения экономической целесообразности Adaptation, как эмпирического способа разрешения неопределенности требований.
#Agile #SDLC
—"Essential Scrum: A Practical Guide to the Most Popular Agile Process" by Kenneth Rubin, "Chapter 3 Agile Principles :: Prediction and Adaptation"
Более того, этот баланс Prediction/Adaptation зависит от конкретных условий проекта и исторического контекста. В конце 90-х снижалась стоимость адаптации, а системы были простыми. Сегодня средняя система на рынке стала на порядки сложней, стоимость адаптации диспропорционально возросла, но зато удешевляется Prediction, за счет появления Event Storming и других легковесных методик.
Стоимость Prediction не константна по отношению к жизненному циклу системы, и имеет тенденцию к понижению по мере реализации проекта.
Тот же Len Bass в вопросах поиска этого баланса ссылается на книгу "Balancing Agility and Discipline: A Guide for the Perplexed" by Barry Boehm, Richard Turner, которая вышла в свет через 2 года после Agile Manifesto.
Но это уже вопрос организации процессов разработки, в то время как этот месяц у нас посвящен (по результатам опроса) вопросам качества кода. Т.е. в данном контексте нас интересует не поиск оптимального баланса Prediction/Adaptation (хотя этот вопрос тоже важен, и можно продолжить его обсуждение в чате канала), а способ достижения экономической целесообразности Adaptation, как эмпирического способа разрешения неопределенности требований.
#Agile #SDLC
🔥4👍3❤1
Chat Digest
💬 "Классическая статья Пэта Хэлланда "Data on the Outside vs. Data on the Inside"
- https://t.me/ru_arc_chat/1136
💬 "Mindmap по рискам и таксономии целей"
- https://t.me/ru_arc_chat/1147
💬 "Три опоры архитектора"
- https://t.me/ru_arc_chat/1168
💬 Что такое Система?
- https://t.me/ru_arc_chat/1194
- https://t.me/ru_arc_chat/1195
💬 ISO/IEC/IEEE 15288:2015 Systems and software engineering — System life cycle processes
- https://t.me/ru_arc_chat/1190
💬 Про умственное жонглирование на почве недостаточного качества кода:
- https://t.me/ru_arc_chat/1222
💬 Нельзя поддерживать бесконечную гибкость архитектуры - она тоже имеет свою цену:
- https://t.me/ru_arc_chat/1248
💬 Пара статей о балансе Prediction/Adaptation в SDLC-моделях:
- https://t.me/ru_arc_chat/1253
- https://t.me/ru_arc_chat/1254
💬 Причины отскока маятника от Adaptation к Prediction:
- https://t.me/ru_arc_chat/1263
💬 О гибридизации Agile и проектных практик:
- https://t.me/ru_arc_chat/1265
💬 Is Design Dead (for Agile)?
- https://t.me/ru_arc_chat/1272
💬 Два вида неопределенности требований:
- https://t.me/ru_arc_chat/1274
💬 CAP-theorem уже устарела. Что изучать?
- https://t.me/ru_arc_chat/1283
💬 О генерации кода микросервисов по диаграммам Event Storming:
- https://t.me/ru_arc_chat/1291
💬 Хорошее и простое руководство по Open Agile Architecture, которое отличается хорошим балансом лаконичности и информационной ценности, сопровождаемое демонстрационной моделью в Archi. Если не знаете с чего начать документирование архитектуры в Agile, то это самое оно:
- https://t.me/ru_arc_chat/1309
#ChatDigest
💬 "Классическая статья Пэта Хэлланда "Data on the Outside vs. Data on the Inside"
- https://t.me/ru_arc_chat/1136
💬 "Mindmap по рискам и таксономии целей"
- https://t.me/ru_arc_chat/1147
💬 "Три опоры архитектора"
- https://t.me/ru_arc_chat/1168
💬 Что такое Система?
- https://t.me/ru_arc_chat/1194
- https://t.me/ru_arc_chat/1195
💬 ISO/IEC/IEEE 15288:2015 Systems and software engineering — System life cycle processes
- https://t.me/ru_arc_chat/1190
💬 Про умственное жонглирование на почве недостаточного качества кода:
- https://t.me/ru_arc_chat/1222
💬 Нельзя поддерживать бесконечную гибкость архитектуры - она тоже имеет свою цену:
- https://t.me/ru_arc_chat/1248
💬 Пара статей о балансе Prediction/Adaptation в SDLC-моделях:
- https://t.me/ru_arc_chat/1253
- https://t.me/ru_arc_chat/1254
💬 Причины отскока маятника от Adaptation к Prediction:
- https://t.me/ru_arc_chat/1263
💬 О гибридизации Agile и проектных практик:
- https://t.me/ru_arc_chat/1265
💬 Is Design Dead (for Agile)?
- https://t.me/ru_arc_chat/1272
💬 Два вида неопределенности требований:
- https://t.me/ru_arc_chat/1274
💬 CAP-theorem уже устарела. Что изучать?
- https://t.me/ru_arc_chat/1283
💬 О генерации кода микросервисов по диаграммам Event Storming:
- https://t.me/ru_arc_chat/1291
💬 Хорошее и простое руководство по Open Agile Architecture, которое отличается хорошим балансом лаконичности и информационной ценности, сопровождаемое демонстрационной моделью в Archi. Если не знаете с чего начать документирование архитектуры в Agile, то это самое оно:
- https://t.me/ru_arc_chat/1309
#ChatDigest
Telegram
Andrei Gordienkov in RASA Chat
кстати, мы тут вчера обсуждали всякое и затронули немного события, и в этой связи хотелось бы вам напомнить о классической статье Пэта Хэлланда
https://queue.acm.org/detail.cfm?id=3415014
Если еще не читали, то горячо советую ознакомиться, поскольку отсылок…
https://queue.acm.org/detail.cfm?id=3415014
Если еще не читали, то горячо советую ознакомиться, поскольку отсылок…
👍6🔥3
Forwarded from Архитектура ИТ-решений
📆12 июля 10:30 MSK Новая YouTube-трансляция. В этот раз обсуждаем вопросы, связанные с модернизацией унаследованных приложений.
Задать вопросы, поделиться своим опытом и зарегистрироваться можно по ссылке: https://mxsmirnov.timepad.ru/event/2099600/
Задать вопросы, поделиться своим опытом и зарегистрироваться можно по ссылке: https://mxsmirnov.timepad.ru/event/2099600/
mxsmirnov.timepad.ru
Модернизация унаследованных приложений / События на TimePad.ru
Russian Association of Software Architects
💬 "Most of us would prefer to wait until we have more information so that we can make a more informed decision. When dealing with important or irreversible decisions, if we decide too early and are wrong, we will be on the exponential part of the cost-of-deciding…
💬 "Кто-то спросит: так ли уж часто читается наш код? Разве большая часть времени не уходит на его написание?
Вам когда-нибудь доводилось воспроизводить запись сеанса редактирования? В 80-х и 90-х годах существовали редакторы, записывавшие все нажатия клавиш (например, Emacs). Вы могли проработать целый час, а потом воспроизвести весь сеанс, словно ускоренное кино. Когда я это делал, результаты оказывались просто потрясающими.
Большинство операций относилось к прокрутке и переходу к другим модулям!
- Боб открывает модуль.
- Он находит функцию, которую необходимо изменить.
- Задумывается о последствиях.
- Ой, теперь он переходит в начало модуля, чтобы проверить инициализацию переменной.
- Снова возвращается вниз и начинает вводить код.
- Стирает то, что только что ввел.
- Вводит заново.
- Еще раз стирает!
- Вводит половину чего-то другого, но стирает и это!
- Прокручивает модуль к другой функции, которая вызывает изменяемую функцию, чтобы посмотреть, как она вызывается.
- Возвращается обратно и восстанавливает только что стертый код.
- Задумывается.
- Снова стирает!
- Открывает другое окно и просматривает код субкласса. Переопределяется ли в нем эта функция?
<...>
В общем, вы поняли. На самом деле соотношение времени чтения и написания кода превышает 10:1. Мы постоянно читаем свой старый код, поскольку это необходимо для написания нового кода.
Из-за столь высокого соотношения наш код должен легко читаться, даже если это затрудняет его написание. Конечно, написать код, не прочитав его, невозможно, так что упрощение чтения в действительности упрощает и написание кода. Уйти от этой логики невозможно. Невозможно написать код без предварительного чтения окружающего кода. Код, который вы собираетесь написать сегодня, будет легко или тяжело писаться в зависимости от того, насколько легко или тяжело читается окружающий код. Если вы хотите быстро справиться со своей задачей, если вы хотите, чтобы ваш код было легко писать — позаботьтесь о том, чтобы он легко читался.
You might ask: How much is code really read? Doesn't most of the effort go into writing it?
Have you ever played back an edit session? In the 80s and 90s we had editors like Emacs that kept track of every keystroke. You could work for an hour and then play back your whole edit session like a high-speed movie. When I did this, the results were fascinating.
The vast majority of the playback was scrolling and navigating to other modules!
- Bob enters the module.
- He scrolls down to the function needing change.
- He pauses, considering his options.
- Oh, he's scrolling up to the top of the module to check the initialization of a variable.
- Now he scrolls back down and begins to type.
- Ooops, he's erasing what he typed!
- He types it again.
- He erases it again!
- He types half of something else but then erases that!
- He scrolls down to another function that calls the function he's changing to see how it is called.
- He scrolls back up and types the same code he just erased.
- He pauses.
- He erases that code again!
- He pops up another window and looks at a subclass. Is that function overridden?
<...>
You get the drift. Indeed, the ratio of time spent reading vs. writing is well over 10:1. We are constantly reading old code as part of the effort to write new code.
Because this ratio is so high, we want the reading of code to be easy, even if it makes the writing harder. Of course there's no way to write code without reading it, so making it easy to read actually makes it easier to write.
There is no escape from this logic. You cannot write code if you cannot read the surrounding code. The code you are trying to write today will be hard or easy to write depending on how hard or easy the surrounding code is to read. So if you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read."
—"Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin, перевод: Е.Матвеев, ООО Издательство "Питер"
#SoftwareDesign
Вам когда-нибудь доводилось воспроизводить запись сеанса редактирования? В 80-х и 90-х годах существовали редакторы, записывавшие все нажатия клавиш (например, Emacs). Вы могли проработать целый час, а потом воспроизвести весь сеанс, словно ускоренное кино. Когда я это делал, результаты оказывались просто потрясающими.
Большинство операций относилось к прокрутке и переходу к другим модулям!
- Боб открывает модуль.
- Он находит функцию, которую необходимо изменить.
- Задумывается о последствиях.
- Ой, теперь он переходит в начало модуля, чтобы проверить инициализацию переменной.
- Снова возвращается вниз и начинает вводить код.
- Стирает то, что только что ввел.
- Вводит заново.
- Еще раз стирает!
- Вводит половину чего-то другого, но стирает и это!
- Прокручивает модуль к другой функции, которая вызывает изменяемую функцию, чтобы посмотреть, как она вызывается.
- Возвращается обратно и восстанавливает только что стертый код.
- Задумывается.
- Снова стирает!
- Открывает другое окно и просматривает код субкласса. Переопределяется ли в нем эта функция?
<...>
В общем, вы поняли. На самом деле соотношение времени чтения и написания кода превышает 10:1. Мы постоянно читаем свой старый код, поскольку это необходимо для написания нового кода.
Из-за столь высокого соотношения наш код должен легко читаться, даже если это затрудняет его написание. Конечно, написать код, не прочитав его, невозможно, так что упрощение чтения в действительности упрощает и написание кода. Уйти от этой логики невозможно. Невозможно написать код без предварительного чтения окружающего кода. Код, который вы собираетесь написать сегодня, будет легко или тяжело писаться в зависимости от того, насколько легко или тяжело читается окружающий код. Если вы хотите быстро справиться со своей задачей, если вы хотите, чтобы ваш код было легко писать — позаботьтесь о том, чтобы он легко читался.
You might ask: How much is code really read? Doesn't most of the effort go into writing it?
Have you ever played back an edit session? In the 80s and 90s we had editors like Emacs that kept track of every keystroke. You could work for an hour and then play back your whole edit session like a high-speed movie. When I did this, the results were fascinating.
The vast majority of the playback was scrolling and navigating to other modules!
- Bob enters the module.
- He scrolls down to the function needing change.
- He pauses, considering his options.
- Oh, he's scrolling up to the top of the module to check the initialization of a variable.
- Now he scrolls back down and begins to type.
- Ooops, he's erasing what he typed!
- He types it again.
- He erases it again!
- He types half of something else but then erases that!
- He scrolls down to another function that calls the function he's changing to see how it is called.
- He scrolls back up and types the same code he just erased.
- He pauses.
- He erases that code again!
- He pops up another window and looks at a subclass. Is that function overridden?
<...>
You get the drift. Indeed, the ratio of time spent reading vs. writing is well over 10:1. We are constantly reading old code as part of the effort to write new code.
Because this ratio is so high, we want the reading of code to be easy, even if it makes the writing harder. Of course there's no way to write code without reading it, so making it easy to read actually makes it easier to write.
There is no escape from this logic. You cannot write code if you cannot read the surrounding code. The code you are trying to write today will be hard or easy to write depending on how hard or easy the surrounding code is to read. So if you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read."
—"Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin, перевод: Е.Матвеев, ООО Издательство "Питер"
#SoftwareDesign
👍15
Russian Association of Software Architects
💬 "Most of us would prefer to wait until we have more information so that we can make a more informed decision. When dealing with important or irreversible decisions, if we decide too early and are wrong, we will be on the exponential part of the cost-of-deciding…
Можно добавить, что 10:1 - это еще оптимистическое соотношение для кода с приемлемым качеством.
Подведем итог: в процессе конструирования кода, 91% времени (в лучшем случае) занимает именно чтение кода и борьба со сложностью (каждым разработчиком регулярно), и только 9% времени (1:10) занимает ввод символов с клавиатуры (одним разработчиком единократно).
#SoftwareDesign
Подведем итог: в процессе конструирования кода, 91% времени (в лучшем случае) занимает именно чтение кода и борьба со сложностью (каждым разработчиком регулярно), и только 9% времени (1:10) занимает ввод символов с клавиатуры (одним разработчиком единократно).
#SoftwareDesign
👍6
Сегодня в одном из чатов мне напомнили о том, что существует "Overengeneering", и это, в общем-то, как бы плохо. Отсюда напрашивается вывод, что, мол, не нужно развиваться, чтобы не стать оверинженерным и квазинаучным.
Не берусь судить о том, плохо это, или хорошо, но это неизбежно в процессе профессионального становления специалиста, а раз так, то польза от этого явления, по всей видимости, все-таки перевешивает наносимый урон, поскольку урон этот является однократным явлением, а польза от достигнутого профессионального уровня носит систематический характер.
В индустрии это явление известно как "Синдром второй системы", который гласит, что вторая создаваемая система в практике специалиста обычно обладает переусложненностью.
По этому поводу хорошо выразился И.Е.Репин:
💬 "Сначала художник рисует плохо и просто.
Потом сложно и плохо.
Потом сложно и хорошо.
И только потом - просто и хорошо."
Ладно, И.Е.Репин - не IT-шник:
💬 "Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better."
—Edsger W. Dijkstra, 1984 On the nature of Computing Science (EWD896)
Что можно в этом случае предпринять? Варианта два:
1. Уравновешивать когнитивные искажения технического специалиста, чем, собственно, и должна заниматься организация процессов разработки. По понятным причинам, сейчас мы в неё погружаться не будем. Главное - знать, что эта проблема решаема.
2. Чем большей полнотой знаний обладает специалист, тем большим моментом инерции обладает его устойчивость, тем меньшее воздействие на неё оказывает каждый новый инкремент знаний, и тем лучше достигается сбалансированность решений. Иными словами, лечится это увеличением охвата знаний. Нужно просто не зацикливаться и поскорее пройти этот этап профессионального становления.
Можно ли стать "переусложненным" постоянно развиваясь? Нет, не можно, и это хорошо видно на примере Kent Beck - невероятно эрудированного человека, обладающего редкой способностью объяснять сложные вещи простым языком. Объем списка использованной литературы его книг вызывает состояние легкого удивления, как и простота и ясность его формулировок. Другим таким ярким примером является @vladik_kh .
Объясняется это просто - возможности человеческого мозга ограничены, и, чтобы не потонуть в океане информации, и сохранить какую-то способность ориентироваться в ней, он начинает кристаллизировать её. Постоянно обобщая и систематизируя, он выводит наименее противоречивую форму этой информации. Количество переходит в качество.
Ну а самое главное - overengeneering является как раз следствием недостатка знаний о контексте и моменте своевременности применения тех или иных подходов. Излечить это незнание с помощью информационного голода технически невозможно, т.к. между YAGNI и Spaghetti-code имеется огромная разница, которая заключается именно в полноте знаний.
#SoftSkills #Simplicity
Не берусь судить о том, плохо это, или хорошо, но это неизбежно в процессе профессионального становления специалиста, а раз так, то польза от этого явления, по всей видимости, все-таки перевешивает наносимый урон, поскольку урон этот является однократным явлением, а польза от достигнутого профессионального уровня носит систематический характер.
В индустрии это явление известно как "Синдром второй системы", который гласит, что вторая создаваемая система в практике специалиста обычно обладает переусложненностью.
По этому поводу хорошо выразился И.Е.Репин:
💬 "Сначала художник рисует плохо и просто.
Потом сложно и плохо.
Потом сложно и хорошо.
И только потом - просто и хорошо."
Ладно, И.Е.Репин - не IT-шник:
💬 "Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better."
—Edsger W. Dijkstra, 1984 On the nature of Computing Science (EWD896)
Что можно в этом случае предпринять? Варианта два:
1. Уравновешивать когнитивные искажения технического специалиста, чем, собственно, и должна заниматься организация процессов разработки. По понятным причинам, сейчас мы в неё погружаться не будем. Главное - знать, что эта проблема решаема.
2. Чем большей полнотой знаний обладает специалист, тем большим моментом инерции обладает его устойчивость, тем меньшее воздействие на неё оказывает каждый новый инкремент знаний, и тем лучше достигается сбалансированность решений. Иными словами, лечится это увеличением охвата знаний. Нужно просто не зацикливаться и поскорее пройти этот этап профессионального становления.
Можно ли стать "переусложненным" постоянно развиваясь? Нет, не можно, и это хорошо видно на примере Kent Beck - невероятно эрудированного человека, обладающего редкой способностью объяснять сложные вещи простым языком. Объем списка использованной литературы его книг вызывает состояние легкого удивления, как и простота и ясность его формулировок. Другим таким ярким примером является @vladik_kh .
Объясняется это просто - возможности человеческого мозга ограничены, и, чтобы не потонуть в океане информации, и сохранить какую-то способность ориентироваться в ней, он начинает кристаллизировать её. Постоянно обобщая и систематизируя, он выводит наименее противоречивую форму этой информации. Количество переходит в качество.
Ну а самое главное - overengeneering является как раз следствием недостатка знаний о контексте и моменте своевременности применения тех или иных подходов. Излечить это незнание с помощью информационного голода технически невозможно, т.к. между YAGNI и Spaghetti-code имеется огромная разница, которая заключается именно в полноте знаний.
#SoftSkills #Simplicity
Wikipedia
Эффект второй системы
Эффект второй системы (также синдром второй системы) — тенденция того, что на смену маленьким, элегантным и успешным системам приходят раздутые системы с овер-инжинирингом, вследствие завышенных ожиданий и чрезмерной уверенности в необходимости изменений.
🔥6👍4👏1
Forwarded from Блог Сергея Баранова
Привет!
Приглашаем на очную встречу ArchDays Recap 27 июля (ср) в Москве.
🧚ArchDays Recap — новый для нас формат, на котором приглашенные спикеры предыдущих конференций:
— расскажут о дальнейшем развитии истории из выступления;
— раскроют некоторые аспекты выступлений, важность которых была осознана уже после;
— ответят на вопросы из зала или из формы на сайте.
📍Программа и регистрация: https://archconf.ru/recap-27-07-22
Приглашаем на очную встречу ArchDays Recap 27 июля (ср) в Москве.
🧚ArchDays Recap — новый для нас формат, на котором приглашенные спикеры предыдущих конференций:
— расскажут о дальнейшем развитии истории из выступления;
— раскроют некоторые аспекты выступлений, важность которых была осознана уже после;
— ответят на вопросы из зала или из формы на сайте.
📍Программа и регистрация: https://archconf.ru/recap-27-07-22
👍4👎1😢1
Продолжим разговор о целях нашего объединения. Мы уже о говорили о том, что существует проблема захламленности информационного пространства. Но и без учета этого хлама современная область знаний слишком переусложнена. Требуются годы на ее освоение. А производить информационные системы нужно уже сегодня. Возникает противоречие, влекущее за собой морально-психологическое напряжение.
Лишь немногим удается эффективно спланировать самообучение и снять психологическое напряжение.
Без планирования самообразования огромный наукоемкий горизонт требуемых знаний перегружает психику - вся тяжесть требуемых знаний фокусируется в текущий момент времени, и формирует чувство многократного их превосходства над ресурсами мозга. Это вызывает беспокойство. Вопрос влияния планирования на беспокойство хорошо рассматривается в "Planning Extreme Programming" by Kent Beck, Martin Fowler.
Напряжение морально-психологическое приводит к напряжению реальному, физическому, в виде спазма мышц. Самыми незащищенными оказываются самые маленькие мышцы - хрусталика глаза. Напряжение приводит к спазму аккомодации, который затем переходит в миопию. Неслучайно большинство популярных методик восстановления зрения начинаются со снятия психологического напряжения.
В погоне за количеством специалисты нередко надрываются, осознают невыполнимость желаемого, впадают в депрессию, подавляют Когнитивный Диссонанс и входят в состояние Психологической Защиты (мол, "академичность" неуместна на практике), и прекращают развиваться. Это порождает еще одну проблему - высокую токстичность коллективов в ИТ-индустрии, которая нередко приводит к расколам или потере ценных кадров.
С целью решения этой проблемы, мы видим перед собой следующие задачи:
1. создание объединенного архитектурного руководства;
2. создание интерактивных графов принятия решений или СППР;
3. создание эталонно-демонстрационных архитектур (Reference Architectures);
4. создание эталонно-демонстрационных приложений (Reference Applications);
5. проведение цикла архитектурных практикумов (workshops);
6. проведение ряда мероприятий с целью популяризации эффективных форм самообучения.
Кому интересно разделить наши цели и сплотить усилия для их достижения - обращайтесь в @ru_arc_bot .
#Goal
Лишь немногим удается эффективно спланировать самообучение и снять психологическое напряжение.
Без планирования самообразования огромный наукоемкий горизонт требуемых знаний перегружает психику - вся тяжесть требуемых знаний фокусируется в текущий момент времени, и формирует чувство многократного их превосходства над ресурсами мозга. Это вызывает беспокойство. Вопрос влияния планирования на беспокойство хорошо рассматривается в "Planning Extreme Programming" by Kent Beck, Martin Fowler.
Напряжение морально-психологическое приводит к напряжению реальному, физическому, в виде спазма мышц. Самыми незащищенными оказываются самые маленькие мышцы - хрусталика глаза. Напряжение приводит к спазму аккомодации, который затем переходит в миопию. Неслучайно большинство популярных методик восстановления зрения начинаются со снятия психологического напряжения.
В погоне за количеством специалисты нередко надрываются, осознают невыполнимость желаемого, впадают в депрессию, подавляют Когнитивный Диссонанс и входят в состояние Психологической Защиты (мол, "академичность" неуместна на практике), и прекращают развиваться. Это порождает еще одну проблему - высокую токстичность коллективов в ИТ-индустрии, которая нередко приводит к расколам или потере ценных кадров.
С целью решения этой проблемы, мы видим перед собой следующие задачи:
1. создание объединенного архитектурного руководства;
2. создание интерактивных графов принятия решений или СППР;
3. создание эталонно-демонстрационных архитектур (Reference Architectures);
4. создание эталонно-демонстрационных приложений (Reference Applications);
5. проведение цикла архитектурных практикумов (workshops);
6. проведение ряда мероприятий с целью популяризации эффективных форм самообучения.
Кому интересно разделить наши цели и сплотить усилия для их достижения - обращайтесь в @ru_arc_bot .
#Goal
Telegram
Russian Association of Software Architects
Мы продолжаем информировать вас о целях нашего объединения, поскольку, как говорится, важно не объединение само по себе, а те принципы, на которых оно основано. Сообщения о наших целях мы будем помечать тегом #Goal .
Как говорил Gregor Hohpe:
"There's a…
Как говорил Gregor Hohpe:
"There's a…
👍9🔥8
💬 "Дейкстра пишет, что ни один человек не обладает интеллектом, способным вместить все детали современной компьютерной программы (Dijkstra, 1972), поэтому нам - разработчикам ПО — не следует пытаться охватить всю программу сразу. Вместо этого мы должны попытаться организовать программы так, чтобы можно было безопасно работать с их отдельными фрагментами по очереди. Целью этого является минимизация объема программы, о котором нужно думать в конкретный момент времени. Можете считать это своеобразным умственным жонглированием: чем больше умственных шаров программа заставляет поддерживать в воздухе, тем выше вероятность того, что вы уроните один из них и допустите ошибку при проектировании или кодировании.
На уровне архитектуры ПО сложность проблемы можно снизить, разделив систему на подсистемы. Несколько несложных фрагментов информации понять проще, чем один сложный. В разбиении сложной проблемы на простые фрагменты и заключается цель всех методик проектирования ПО. Чем более независимы подсистемы, тем безопаснее сосредоточиться на одном аспекте сложности в конкретный момент времени. Грамотно определенные объекты разделяют аспекты проблемы так, чтобы вы могли решать их по очереди. Пакеты обеспечивают такое же преимущество на более высоком уровне агрегации.
Стремление к краткости методов программы помогает снизить нагрузку на интеллект. Этому же способствует написание программы в терминах проблемной области, а не низкоуровневых деталей реализации, а также работа на самом высоком уровне абстракции.
Суть сказанного в том, что программисты, компенсирующие изначальные ограничения человеческого ума, пишут более понятный и содержащий меньшее число ошибок код.
Dijkstra pointed out that no one's skull is really big enough to contain a modern computer program (Dijkstra 1972), which means that we as software developers shouldn't try to cram whole programs into our skulls at once; we should try to organize our programs in such a way that we can safely focus on one part of it at a time. The goal is to minimize the amount of a program you have to think about at any one time. You might think of this as mental juggling—the more mental balls the program requires you to keep in the air at once, the more likely you'll drop one of the balls, leading to a design or coding error.
At the software-architecture level, the complexity of a problem is reduced by dividing the system into subsystems. Humans have an easier time comprehending several simple pieces of information than one complicated piece. The goal of all software-design techniques is to break a complicated problem into simple pieces. The more independent the subsystems are, the more you make it safe to focus on one bit of complexity at a time. Carefully defined objects separate concerns so that you can focus on one thing at a time. Packages provide the same benefit at a higher level of aggregation.
Keeping routines short helps reduce your mental workload. Writing programs in terms of the problem domain, rather than in terms of low-level implementation details, and working at the highest level of abstraction reduce the load on your brain.
The bottom line is that programmers who compensate for inherent human limitations write code that's easier for themselves and others to understand and that has fewer errors."
—"Code Complete" 2nd edition by Steve McConnell, перевод: Издательско-торговый дом "Русская Редакция"
#SoftwareDesign
На уровне архитектуры ПО сложность проблемы можно снизить, разделив систему на подсистемы. Несколько несложных фрагментов информации понять проще, чем один сложный. В разбиении сложной проблемы на простые фрагменты и заключается цель всех методик проектирования ПО. Чем более независимы подсистемы, тем безопаснее сосредоточиться на одном аспекте сложности в конкретный момент времени. Грамотно определенные объекты разделяют аспекты проблемы так, чтобы вы могли решать их по очереди. Пакеты обеспечивают такое же преимущество на более высоком уровне агрегации.
Стремление к краткости методов программы помогает снизить нагрузку на интеллект. Этому же способствует написание программы в терминах проблемной области, а не низкоуровневых деталей реализации, а также работа на самом высоком уровне абстракции.
Суть сказанного в том, что программисты, компенсирующие изначальные ограничения человеческого ума, пишут более понятный и содержащий меньшее число ошибок код.
Dijkstra pointed out that no one's skull is really big enough to contain a modern computer program (Dijkstra 1972), which means that we as software developers shouldn't try to cram whole programs into our skulls at once; we should try to organize our programs in such a way that we can safely focus on one part of it at a time. The goal is to minimize the amount of a program you have to think about at any one time. You might think of this as mental juggling—the more mental balls the program requires you to keep in the air at once, the more likely you'll drop one of the balls, leading to a design or coding error.
At the software-architecture level, the complexity of a problem is reduced by dividing the system into subsystems. Humans have an easier time comprehending several simple pieces of information than one complicated piece. The goal of all software-design techniques is to break a complicated problem into simple pieces. The more independent the subsystems are, the more you make it safe to focus on one bit of complexity at a time. Carefully defined objects separate concerns so that you can focus on one thing at a time. Packages provide the same benefit at a higher level of aggregation.
Keeping routines short helps reduce your mental workload. Writing programs in terms of the problem domain, rather than in terms of low-level implementation details, and working at the highest level of abstraction reduce the load on your brain.
The bottom line is that programmers who compensate for inherent human limitations write code that's easier for themselves and others to understand and that has fewer errors."
—"Code Complete" 2nd edition by Steve McConnell, перевод: Издательско-торговый дом "Русская Редакция"
#SoftwareDesign
👍13🔥8❤2
Russian Association of Software Architects
💬 "Дейкстра пишет, что ни один человек не обладает интеллектом, способным вместить все детали современной компьютерной программы (Dijkstra, 1972), поэтому нам - разработчикам ПО — не следует пытаться охватить всю программу сразу. Вместо этого мы должны попытаться…
Пришло время разобраться с термином "Refactoring", значение которого часто понимается неверно в значении "переработать".
По основной версии, слово "refactoring" происходит от математического термина "factoring", и дословно переводится как "факторизация" или "декомпозиция", о чем говорит на своем сайте ключевой автор известной книги "Refactoring: Improving the Design of Existing Code" by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts (благодаря которой, рефакторинг и обрел популярность):
💬 "The obvious answer comes from the notion of factoring in mathematics. You can take an expressions such as x^2 + 5x + 6 and factor it into (x+2)(x+3). By factoring it you can make a number of mathematical operations much easier. Obviously this is much the same as representing 18 as 2*3^2. I've certainly often heard of people talking about a program as well factored once it's broken out into similarly logical chunks."
—"Etymology Of Refactoring" by Martin Fowler
Такое же мнение можно увидеть и на сайте Ward Cunningham:
💬 "Refactoring is a kind of reorganization. Technically, it comes from mathematics when you factor an expression into an equivalence - the factors are cleaner ways of expressing the same statement. Refactoring implies equivalence; the beginning and end products must be functionally identical. You can view refactoring as a special case of reworking (see WhatIsReworking).
Practically, refactoring means making code clearer and cleaner and simpler and elegant. Or, in other words, clean up after yourself when you code. Examples would run the range from renaming a variable to introducing a method into a third-party class that you don't have source for.
Refactoring is not rewriting, although many people think they are the same. There are many good reasons to distinguish them, such as regression test requirements and knowledge of system functionality. The technical difference between the two is that refactoring, as stated above, doesn't change the functionality (or information content) of the system whereas rewriting does. Rewriting is reworking. See WhatIsReworking.
Refactoring is a good thing because complex expressions are typically built from simpler, more grokable components. Refactoring either exposes those simpler components or reduces them to the more efficient complex expression (depending on which way you are going).
For an example of efficiency, count the terms and operators: (x - 1) * (x + 1) = x^2 - 1. Four terms versus three. Three operators versus two. However, the left hand side expression is (arguably) simpler to understand because it uses simpler operations. Also, it provides you more information about the structure of the function f(x) = x^2 - 1, like the roots are +/- 1, that would be difficult to determine just by "looking" at the right hand side."
—"What Is Refactoring" on wiki.c2.com
Таким образом, рефакторинг - это способ управления сложностью, который делает программу более читаемой и понимаемой за счет декомпозиции сложности, что снижает нагрузку на краткосрочную память. Процесс рефакторинга подобен факторизации математического выражения, в результате которого выводится более легкое эквивалентное выражение, т.е. сохраняется функциональная идентичность. Именно поэтому рефакторинг оставляет неизменным внешнее поведение системы:
💬 "Рефакторинг представляет собой процесс такого изменения программной системы, при котором не меняется внешнее поведение кода, но улучшается его внутренняя структура.
Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure."
—Martin Fowler in "Refactoring: Improving the Design of Existing Code" by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts, перевод С. Маккавеева
Во 2-м издании это определение слегка изменилось:
💬 "Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior."
#SoftwareDesign
По основной версии, слово "refactoring" происходит от математического термина "factoring", и дословно переводится как "факторизация" или "декомпозиция", о чем говорит на своем сайте ключевой автор известной книги "Refactoring: Improving the Design of Existing Code" by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts (благодаря которой, рефакторинг и обрел популярность):
💬 "The obvious answer comes from the notion of factoring in mathematics. You can take an expressions such as x^2 + 5x + 6 and factor it into (x+2)(x+3). By factoring it you can make a number of mathematical operations much easier. Obviously this is much the same as representing 18 as 2*3^2. I've certainly often heard of people talking about a program as well factored once it's broken out into similarly logical chunks."
—"Etymology Of Refactoring" by Martin Fowler
Такое же мнение можно увидеть и на сайте Ward Cunningham:
💬 "Refactoring is a kind of reorganization. Technically, it comes from mathematics when you factor an expression into an equivalence - the factors are cleaner ways of expressing the same statement. Refactoring implies equivalence; the beginning and end products must be functionally identical. You can view refactoring as a special case of reworking (see WhatIsReworking).
Practically, refactoring means making code clearer and cleaner and simpler and elegant. Or, in other words, clean up after yourself when you code. Examples would run the range from renaming a variable to introducing a method into a third-party class that you don't have source for.
Refactoring is not rewriting, although many people think they are the same. There are many good reasons to distinguish them, such as regression test requirements and knowledge of system functionality. The technical difference between the two is that refactoring, as stated above, doesn't change the functionality (or information content) of the system whereas rewriting does. Rewriting is reworking. See WhatIsReworking.
Refactoring is a good thing because complex expressions are typically built from simpler, more grokable components. Refactoring either exposes those simpler components or reduces them to the more efficient complex expression (depending on which way you are going).
For an example of efficiency, count the terms and operators: (x - 1) * (x + 1) = x^2 - 1. Four terms versus three. Three operators versus two. However, the left hand side expression is (arguably) simpler to understand because it uses simpler operations. Also, it provides you more information about the structure of the function f(x) = x^2 - 1, like the roots are +/- 1, that would be difficult to determine just by "looking" at the right hand side."
—"What Is Refactoring" on wiki.c2.com
Таким образом, рефакторинг - это способ управления сложностью, который делает программу более читаемой и понимаемой за счет декомпозиции сложности, что снижает нагрузку на краткосрочную память. Процесс рефакторинга подобен факторизации математического выражения, в результате которого выводится более легкое эквивалентное выражение, т.е. сохраняется функциональная идентичность. Именно поэтому рефакторинг оставляет неизменным внешнее поведение системы:
💬 "Рефакторинг представляет собой процесс такого изменения программной системы, при котором не меняется внешнее поведение кода, но улучшается его внутренняя структура.
Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure."
—Martin Fowler in "Refactoring: Improving the Design of Existing Code" by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts, перевод С. Маккавеева
Во 2-м издании это определение слегка изменилось:
💬 "Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior."
#SoftwareDesign
martinfowler.com
bliki: Etymology Of Refactoring
a bliki entry for Etymology Of Refactoring
👍12🔥3
Russian Association of Software Architects
Пришло время разобраться с термином "Refactoring", значение которого часто понимается неверно в значении "переработать". По основной версии, слово "refactoring" происходит от математического термина "factoring", и дословно переводится как "факторизация" или…
- We don't have time to do it right!
- Do you have time to do it twice?
—Randy Shoup, VP Engineering at Stitch Fix in San Francisco
#SoftwareDesign
- Do you have time to do it twice?
—Randy Shoup, VP Engineering at Stitch Fix in San Francisco
#SoftwareDesign
👍7🔥3🤔2
Russian Association of Software Architects
- We don't have time to do it right! - Do you have time to do it twice? —Randy Shoup, VP Engineering at Stitch Fix in San Francisco #SoftwareDesign
💬 "These were elucidated in the mid-70s by Yourdon & Constantine in "Structured Design" and haven't changed. Their argument goes like this:
1. We design software to reduce its cost.
2. The cost of software is ≈ the cost of changing the software.
3. The cost of changing the software is ≈ the cost of the expensive changes (power laws and all that).
4. The cost of the expensive changes is generated by cascading changes — if I change this then I have to change that and that, and if I change that then…
5. Coupling between elements of a design is this propensity for a change to propagate.
6. So, design ≈ cost ≈ change ≈ big change ≈ coupling. Transitively, software design ≈ managing coupling.
(This skips loads of interesting stuff, but I'm just trying to set up the argument for why rapid decomposition of a monolith into micro-services is counter-productive.)"
-- "Monolith -> Services: Theory & Practice" by Kent Beck
1. We design software to reduce its cost.
2. The cost of software is ≈ the cost of changing the software.
3. The cost of changing the software is ≈ the cost of the expensive changes (power laws and all that).
4. The cost of the expensive changes is generated by cascading changes — if I change this then I have to change that and that, and if I change that then…
5. Coupling between elements of a design is this propensity for a change to propagate.
6. So, design ≈ cost ≈ change ≈ big change ≈ coupling. Transitively, software design ≈ managing coupling.
(This skips loads of interesting stuff, but I'm just trying to set up the argument for why rapid decomposition of a monolith into micro-services is counter-productive.)"
-- "Monolith -> Services: Theory & Practice" by Kent Beck
Medium
Monolith -> Services: Theory & Practice
How can we get from a monolith to micro-services quickly?
🔥3👏2👍1
Russian Association of Software Architects
💬 "These were elucidated in the mid-70s by Yourdon & Constantine in "Structured Design" and haven't changed. Their argument goes like this: 1. We design software to reduce its cost. 2. The cost of software is ≈ the cost of changing the software. 3. The cost…
Продолжение:
💬 "Managing Coupling
Note I don't say, "Eliminating coupling." Decoupling comes with its own costs, both the cost of the decoupling itself and the future costs of unanticipated changes. The more perfectly a design is adapted to one set of changes, the more likely it is to be blind-sided by novel changes. And so we have the classic tradeoff curve.
You manage coupling one of two ways:
1. Eliminate coupling. A client and server with hard-coded read() and write() functions are coupled with respect to protocol changes. Change a write() and you'll have to change the read(). Introduce an interface definition language, though, and you can add to the protocol in one place and have the change propagate automatically to read() and write().
2. Reduce coupling's scope. If changing one element implies changing ten others, then it's better if those elements are together than if they are scattered all over the system —less to navigate, less to examine, less to test. The number of elements to change is the same, but the cost per change is smaller. (This is also known as the "manure in one pile" principle, or less-aromatically "cohesion".)"
-- "Monolith -> Services: Theory & Practice" by Kent Beck
Кстати, если вдруг кто-то пропустил, последнее определение SRP от 2022-07-06:
💬 "The Single Responsibility Principle (SRP):
Gather together those things that change for the same reasons and at the same times. Separate those things that change for different reasons or at different times."
— Robert C. Martin
💬 "Managing Coupling
Note I don't say, "Eliminating coupling." Decoupling comes with its own costs, both the cost of the decoupling itself and the future costs of unanticipated changes. The more perfectly a design is adapted to one set of changes, the more likely it is to be blind-sided by novel changes. And so we have the classic tradeoff curve.
You manage coupling one of two ways:
1. Eliminate coupling. A client and server with hard-coded read() and write() functions are coupled with respect to protocol changes. Change a write() and you'll have to change the read(). Introduce an interface definition language, though, and you can add to the protocol in one place and have the change propagate automatically to read() and write().
2. Reduce coupling's scope. If changing one element implies changing ten others, then it's better if those elements are together than if they are scattered all over the system —less to navigate, less to examine, less to test. The number of elements to change is the same, but the cost per change is smaller. (This is also known as the "manure in one pile" principle, or less-aromatically "cohesion".)"
-- "Monolith -> Services: Theory & Practice" by Kent Beck
Кстати, если вдруг кто-то пропустил, последнее определение SRP от 2022-07-06:
💬 "The Single Responsibility Principle (SRP):
Gather together those things that change for the same reasons and at the same times. Separate those things that change for different reasons or at different times."
— Robert C. Martin
👍8🔥4