Collective Code Ownership
Материал из AgileWiki
Содержание |
Общая информация
Статья
Collective Code Ownership
Alternative to CodeStewardship.
ExtremeProgramming considers code to belong to the project, not to an individual engineer. As engineers develop required functionality, they may browse into and modify any class. They are responsible for keeping all the UnitTests running (and writing new ones for new functionality). They take on the same integrity-preserving duties as the class owner in a CodeOwnership situation.
Working in this mode lets a responsible team move quickly to add new functionality while keeping responsibility in the right objects. CodeOwnership creates dependencies and bottlenecks when implementing UserStories. We avoid code ownership, because it conflicts with commitment from the PlanningGame. ("Code is nothing, stories are everything!")
The ability to make this work requires at least:
- all engineers use the same Coding Standards;
- code management tools to detect and resolve conflicts (CVS!);
- a comprehensive suite of Unit Tests to ensure quality;
- powerful browsing and Refactoring Tools to find references to old methods and replace them with the new;
- Continuous Integration (or nearly that) so that conflicts are rare (also CVS).
exprogramming.ru
Коллективное владение кодом стимулирует разработчиков подавать идеи для всех частей проекта, а не только для своих модулей. Любой разработчик может изменять любой код для расширения функциональности, исправления ошибок или рефакторинга.
С первого взгляда это выглядит как хаос. Однако принимая во внимание что как минимум любой код создан парой разработчиков, что Unit тесты позволяют проверить корректность внесенных изменений и что в реальной жизни все равно так или иначе приходится разбираться в чужом коде, становится ясно что коллективное владение кодом значительно упрощает внесение изменений и снижает риск связанный с высокой специализацией того или иного члена команды. Наш опыт.
При условии выполнения остальных требований XP, больших проблем с этим нет.
CodeOwnership
There are various schemes of Code Ownership that I've come across. I put them into three broad categories:
- Strong code ownership breaks a code base up into modules (classes, functions, files) and assigns each module to one developer. Developers are only allowed to make changes to modules they own. If they need a change made to someone else's module they need to talk to the module owner and get them to make the change. You can accelerate this process by writing a patch for the other module and sending that to the module owner.
- Weak code ownership is similar in that modules are assigned to owners, but different in that developers are allowed to change modules owned by other people. Module owners are expected to take responsibility for the modules they own and keep an eye on changes made by other people. If you want to make a substantial change to someone else's module it's polite to talk it over with the module owner first.
- Collective code ownership abandons any notion of individual ownership of modules. The code base is owned by the entire team and anyone may make changes anywhere. You can consider this as no code ownership, but it's advocate prefer the emphasis on the notion of ownership by a team as opposed to an individual. (The term collective code ownership comes from Extreme Programming, although in the second edition the practice is called Shared Code.)
Of the three the one I really don't like is strong code ownership. There are just too many situations where something you need to do needs changes to other people's code. Persuading them to make the change and waiting for the change often takes so long that it leads to delays and deeper problems, this is particularly galling when the change is a simple one.
A good example of a simple change that causes trouble is renaming a public method. Modern refactoring tools can do this safely with extensively used public methods. But this violates code ownership if you cross a module boundary. Essentially you've turned all interfaces between developers into PublishedInterfaces, with all the attendant overheads to change.
Even worse is when you want an implementation change, but because you can't get it quickly enough you make a copy of the foreign code into your module, call your copy of the code and make the change. Of course you intend to sort out the mess later.
Weak code ownership is a good way to mitigate these kinds of problems. People can make changes freely, the code owner just has to keep an eye on things.
The choice between weak and collective ownership has more to do with the social dynamics of the team. Both seem to work, and fail, equally well. Personally I prefer the dynamics of a collective code ownership team - particularly in the context of Extreme Programming.
agileatlanta.org
Anyone can change any code anywhere is the system at any time.
Why is this a "best practice"?
- lowers our "truck-count"
- don't have to wait for Fred to make his changes to "his code"
- eliminates finger-pointing
- promotes comradery, team-building
Any disadvantages?
- egos?
If this is a "best practice", then why don't people do it?
- "divide and conquer" is easier to manage?
- it's the "default"
- takes less effort
- egos?
How is it any different if done "eXtreme"?
- pairs switch often
- programmers share their knowledge willingly
What other practices support this practice?
- Common Vocabulary improves communication
- Simple Design makes it more effective
- Unit Testing makes it more effective, safe
- Pair Programming and knowledge transfer makes it more effective, safe
- Continuous Integration decreases file contention
- Coding Standards makes it effective
What other practices are supported by this one?
- everyone can work on whatever needs doing, enabling Small Releases
- helps us have a Sustainable Pace
- I can take vacation whenever I want
- more eyes reviewing/refactoring the code toward Simple Design
- more coders are knowledgable and allowed to do more Refactoring
- makes Pair Programming easier?
How do I get started?
- Once you have ownership, it's difficult to break. So, start a new project (and start it out right).
- pair program
- cross train: switch pairs often (at least once every couple days up to multiple times per day depending on the situation)
- simple design, write tests, refactor
Next: Continuous Integration (path A); Small Releases (path B).
Коллективное владение кодом
Автор: Denis Miller (draft)
Предлагаю обсудить тему «Коллективного владения кодом». Прошу высказаться, кто что под этим понимает?
Результаты нашего обсуждения формируют наше общее видение на эту приктику и поможет лучше и качественнее нам работать.
Предлагаю обсудить тему «Коллективного владения кодом». Прошу высказаться, кто что под этим понимает?
Результаты нашего обсуждения формируют наше общее видение на эту практику и поможет лучше и качественнее нам работать.
Знание, которые мы получим в ходе нашего обсуждения будет хранится в вики, куда мы сможем обратиться и углубить его в случае необходимости (и надеюсь расширить примерами нашего удачного применения этой практики)
Начну с себя. Для меня коллективное владение кодом это 1 принцип и 1 простая практика:
Принцип: любой ответственнен за любую часть программы и кода.
Практика: 1) общий пул задач (у нас это N) и каждый освободившийся подхватывает самую критичную для бизнеса. 2) парное программирование 3) peer review
В основном обсуждается тема 1. Как самая непонятная для мэнэджеров.
Теперь объяснения.
- Коллективное владение кодом означает открытость и готовность каждого члена команды быть способным вносить изменения в любую часть программы без привязки делал ты это или сталкивался ли с этой функциональностью раньше.
- Нет «зонального принципа», когда кто-то что-то делал и все задачи по этой части будут направлятся к нему. Это не коллективное владение, это больше коллективное знание, кто виноват J
- Коллективное владение кодом провоцирует большее общение и взаимодействие внутри команды. Участники спрашивают, интересуются друг у друга. Повышается уровень осознанности. Если я взял задачу, с которой не знаком - я подхожу и спрашиваю того, кто работал в этой области когда-то. 10 минут хватает, чтобы войти в курс дела и начать разработку. Скорость разработки не падает, а только возрастает, так как объясняющий может подкинуть отличные идеи по реализации. А две головы всегда лучше одной.
- Трудность: У меня возникал страх, что кто-то полезет ко мне в код и будет указывать на мои ошибки. Считаю этот СТРАХ - угроза проетка и с ним нужно бороться всеми доступными методами, а команда должна помогать. Ведь находя ошибки других учатся СРАЗУ 2 ЧЕЛОВЕКА. Тот кто не заметил (я даже знаю почему - когда находишься в контексте задачи всегда что-то пропускаешь), и тот кто редактировал. Таким образом повышается кросс-функциональность. Эта сложность (страх за ошибки) возникает из-за незнания своего права. А право у нас есть, оно звучит так «Каждый вправе ошибаться». Но тут есть ход конём. Ошибка обнаруженная на фазе кодирования с использованием практики «коллективного владения кодом» стоит в тысячи раз дешевле, нежели ошибка обнаруженная пользователем. Поэтому нужно не боятся признавать свои ошибки - ибо на них мы учимся и растём. И вместе с нами растёт качество нашего продукта.
Стратегические плюсы практики:
- повышается техническая кросс-функциональность - здесь объяснений не требуется
- косвенно повышается осознание командой проекта
- команда повышает знание о предметной области => команда выводится с уровня банального технического исполнителя на качественного новый уровень предоставление консалтинга, а как следствие рост доверия клиента и успеха проекта
- любой участник проекта сможет адекватно оценивать любую задачу и любую проблему проекта, а с выходом в продакшен это сверх важно. В идеале каждый сможет граммотно ответить на возникающий критический вопрос с любое вермя суток, даже в 4 часа ночи J
Трудности:
- сразу ничего не бывает
- эта практика требует усилий, но оно окупиться стоицей
- у нас провал по теме базы данных
Мои мысли: я думаю для нашего проекта нам нужно от 6 месяцев до 1 года применение этой практики, чтобы достичь приемлемого уровня владения кодом.
