Midnight in Chernobyl

I don’t have any particular curiosity towards soviet or post-soviet history. I watched the HBO mini-series “Chernobyl” and “Chernobyl The Lost Tapes” documentary, so I got enough of an idea about what happened. Since I was born in Russia and spent good chunk of my life there, I don’t need to be explained about corruption, incompetence and the Soviet ways.

So how did I end up with the book? I have a Canadian friend, really sharp guy, reads books, thinks things through, really fun to talk to. Many years ago, yet another regular conversation took a turn towards the topic of corruption in Canada. Before long he made a broad statement: “… it is the same in Russia”. I disagreed and he disagreed with my disagreement. This was the first time when I realized that people in Canada and in the west, don’t really understand Russia, more specifically that there is a difference between corruption and Russian corruption. In nutshell it is like comparing teenage hockey and professional hockey. Not long ago, my friend, came back to the subject of corruption, but now with a totally different position, now he no longer disagreed with me. I was surprised and he elaborated on his revelation – “Midnight in Chernobyl”, insisting that I should read the book as well.

So how is the book? Well, without a doubt the book is good, very good. It is well written and can be gulped without breaks. What you don’t find in any show or movie is nitty-gritty details and the book does a lot of justice to that. You can feel and see the system at work, incompetence, secrecy, economic and social struggle in “full HD color”. I believe the book represents a relative short and concise case study of the Soviet Union and how people though, operated and sacrificed. To some degree you will be able to understand even current situation and decision making of Russia today (including Russian invasion of Ukraine). The book is about Chernobyl, it is about the tragedy but Chernobyl story spans way beyond boundary of one location and far across entire USSR.

In a nutshell:
+: Well written & easy read
+: Lots of details
+: Brief history of soviet reactor building
+: Great insight into how the state operated
+: Overview how people lived, all equal but some are more equal than others
=: It is a good book, if you have any interest in historic events, pick it up. Chernobyl is one of the greatest disasters and perhaps it is worth while to learn about it, at the very least for the sake of not repeating it.

Title: Midnight in Chernobyl: The Untold Story of the World’s Greatest Nuclear Disaster
Author: Adam Higginbotham

Midnight in Chernobyl | Book by Adam Higginbotham | Official Publisher ...

This is marketing

Business is a very strange beast to me, on the one hand I understand importance of it, on the other hand I never wanted to dive deep into it. I guess business to me is like forbidden fruit – it is there, it is tempting but I never got enough desire to take a bite.

Something changed over last few years and I figured it wouldn’t hurt to learn a thing or two about marketing. This book was chosen almost randomly. As I scrolled over a blog, someone highly recommended the book, without much thought I picked it up.

This is my first book about marketing and since I’m fairly clueless on the subject, it is hard to judge the content. However I can cross reference some ideas from other books and materials:

And so as I read the book, I came across some previously acquired knowledge (good refresher or reinforcement) and since the book is focused on one topic, there were more interesting tidbits.

Now I’ve been dragging my feet with this book for a very long time, embarrassingly long. It is a short read so what the problem? Well, the delivery is… for the lack of better word – ugly. Whenever I picked it up, shortly after I find my mind wondering away, loosing focus and interest. Often I had to put it away and say to myself: “may be tomorrow”. The book just simply does not flow. It is like a bumpy ride, might be entertaining for a bit but ultimately wears you out. Some books you can’t wait to pickup and keep on going, this one is the opposite – delay delay delay.

In a nutshell:
+: Interesting aphorisms, anecdotes and stories
+: General case studies and analysis
+: More on psychological side
+/-: Short book but hard read
-: Lack of concrete recipes and techniques
=: It is hard to make a conclusion on the book in the subject matter that I don’t know much about. I guess if you have to read it (because of a job or deep interest in the subject) then go for it. Otherwise it is not a pleasant read, you will have to commit to get through.

Title: This is Marketing: You Can’t Be Seen Until You Learn To See
Author: Seth Godin

How to get rich

The material got into my hands from a friend of mine. Something tells me he never read the material, but somehow convinced me to read it. Let me say right off the bat, while the material is somewhat interesting and philosophical, rather than hands-on practical, I believe it is worth while.

From this point on, I’ll call it a book, even though it might not qualify. The book is a collection of brief and not terribly deep conversations on the topic of “getting rich”. Now, I can’t blame the author since Twitter is somewhat limited in terms of thought expression. Also the book leaves much to be desired in terms of structure and language. Quite often I had to do double, triple, quadruple take and still couldn’t understand a meaning behind a sentence. Yeah and I’m still calling it a book. But in this day and age perhaps none of this matters.

So will this book make me rich? Well, it’s up to you, or your genetics or upbringing or education and luck. But is there a “secret sauce”? Nope! Effectively the book just talks about your own behaviour and how to focus on essential things and let everything else go – because extreme focus on one thing, is exactly what it takes to get rich.

“Extreme people get extreme results.”

Sam Altman

So, no deep discussions, poorly written, no “secret sauce”, why should I bother? Because (in my opinion) the same techniques and ideas can be applied elsewhere. You don’t have to play status games, you should read books, you should learn to build, learn specific knowledge, you should experiment and go beyond recipe books. Not everything from the book will be applicable, but most of it seems like pretty universal advice that can be applied to other areas of life.

“Don’t partner with cynics and pessimists. Their beliefs are self-fulfilling.”

Naval Ravikant

I wish authors went deeper into discussions with more concrete examples and exercised more upon each topic. At times some material feels like pure philosophy – a wishful thought if I may. However I read few things before and able to fill some gaps or extrapolate some idea further, but I wonder how would this book read to someone without prior knowledge. Perhaps this is on purpose, by design – leave them striving for more and they shall achieve more.

“A calm mind, a fit body and a house full of love. These things can not be bought. They must be earned.”

Naval Ravikant

P.S: if you want to read the book, you can search online or download copy here

In a nutshell:
+: Short & fun read
+: Generally good advice / philosophy (not everything I agree with)
+: Get a feel for what it takes to be rich
-: Not a smooth read – text should be seriously cleaned up
-: Some topics are not well covered or expanded on
=: While the material is rough, some topics are not well covered and some ideas need deeper investigation, overall its worth the time. Philosophy feels quite universal, advices can be adopted for many situations and more importantly, continuous learning is something to be adopted.

Title: How to get rich (without getting lucky)
Author: Naval Ravikant, Babak Nivi

Maverick by Ricardo Semler

I found out about Ricardo Semler from an IT blog, I don’t remember details, but the gist of it: successful Latin-American IT company follows Ricardo Semler’s approach – corporate democracy. The last bit peaked my curiosity, ultimately driving me to the book and let me say, if you never crossed the path, it is enlightening.

Every company wants to stay lean, competitive and ahead of the curve. There are multiple options to achieve it, however once a company grows, it inevitably gets fat and the ability to maneuver is diminished. Ricardo Semler addresses exactly the point – how to stay lean, agile, profitable in a competitive and turbulent environment.

“To survive in modern times, a company must have an organizational structure that accepts change as its basic premise, let’s tribal customs thrive, and fosters a power that is derived from respect, not rules. In other words, the successful companies will be the ones that put quality of life first. Do this and the rest – quality of product, productivity of workers, profits for all – will follow.“

The book is an easy read, the closest I can compare it to is “The Phoenix Project: A Novel About IT, DevOps, and Helping Your Business Win”. However Maverick is written from experience in a real company (Semco) and by a real CEO/Chairman (Ricardo Semler) – it is not a novel or a fantasy. The author has a nag for writing, I found the book entertaining to read, among other things. Described ideas, practices and methodologies that are innovative and provocative at least at a time the book was published – 1995. Not all ideas are original (but what’s new under the moon), some came from the land of rising sun, others from elsewhere, however all of them seem to be remixed and modified to fit the unique Brazilian market conditions Semco found itself in. Considering the age of the book, some of the ideas seemed to survive and flourish in fairly modern and big companies, such as Amazon and Netflix. As I was reading the book, I couldn’t help but say to myself: “oh look, Amazon does this…” or “sure sounds like Netflix’s approach”. I don’t know if those companies consciously adapted those ideas or arrived to the same ideas independently.

So it is fair to ask: is the book relevant after so many years? As I mentioned before, some modern companies already adopted some ideas, but not everything the author had to offer. There is more and the reason for more is fairly simple: the author is examining ideas, practices and methods that deal with human organizational conditions and not with any particular technical issue. Humans are slow to change and after decades of technological progress we still do business the good old way.

“The conflict between advanced technology and archaic mentality is, I believe, a major reason why the modern workplace is characterized by dissatisfaction, frustration, inflexibility, and stress. If only minds were as easy to change as machines. I’ll wager that it’s easier to invent a new generation of microchips than get a generation of middle managers to alter the routes they drive to work every day. Technology is transformed overnight; mentality takes generations to alter. Who can blame us for thinking technology will cure all that ails the workplace. It’s so much easier to acquire.”

In a nutshell:
+: Easy & fun read
+: Many great ideas, practices and methodologies
+: Based on real company and written by the CEO/Chairman
+: Great discussions and examples
+/-: Wound be great to have more details but not at the expense of abstract
=: I enjoyed the book. It contains lots of interesting, provocative and as years passed, very applicable ideas. I wish the author provided more details. Even if you have no interest in business, you might have lots of fun reading the book, at least I did.

Title: Maverick: The Success Story Behind the World’s Most Unusual Workplace
Author: Ricardo Semler


Ah mastery, who doesn’t want to be a master? A rhetorical question, yet an important one.

I’ll come back to the question later, but for now, how is the book? I like it, strange to say from the get-go but yeah… I enjoyed the story, examples & discussions. The book takes mystery of being a genius and breaks it down into concise, foundational sequences of events that each master had to go through in order to climb to the top of their respective field. Each event and a sequence is analyzed by the author and discussed. If you ever wanted a guide on “Mastery”, this might be it.

As I was going through the book, I couldn’t help but ask myself: “well, alright, but who is this book written for?”. Is it a recipe book? I’m not sure, some of the recipes are kinda long – start when you are 5 or 10 year old. Sure, mastery takes long time, you can’t be on the top of a field in just couple of years or by following few “easy” steps. I get it, but it doesn’t answer my question. If you got this book and comprehended it by the age of 17, perhaps you can make it, but for anyone over 30 there aren’t that many recipes in the book. To be fair, the book is fascinating and at any age you should take some ideas out of it, but let’s be real, in order to take full advantage, you should be at the very young age – perhaps you can prepare your children for the journey?

But do you want to be a master? Is it even a conscious choice? I don’t know, but overarching theme seems to be outliers. Those masters have a very different view of the world, some don’t even fit into society. It feels to me that the journey starts with a perceived defect in a person. Something deep inside drives those people forward, some get unlucky and go to live on mountains (figuratively speaking), others get lucky (timing, resources) and lunge forward through many years of hard work but in the end some become dazzling stars of our society, providing example and direction for others to follow.

In a nutshell:
+: Easy & fun read
+: History, analysis, discussions
+: Examples from different eras
+: Useful bits and pieces even if you are not planning on a mastery
-: Is mastery a choice?
=: I don’t know if mastery is a choice, but I can still learn quite a few things from the book. Perhaps if you are young, you should read the book early on. If you have children, perhaps you want to read it as well and set your child on a journey. But perhaps you want to explore minds of the masters for the fun of it, then please enjoy.

Title: Mastery
Author: Robert Greene

Is DDD still relevant?

I heard someone mentioning Eric Evans and DDD (Domain Driven Design) a few times and so I decided to see what’s its all about. It took me a while to get through the book, partly because I’m a slow reader, partly because the book is long and partly because the read is dry. As I was working through the book, I often wondered to myself: “is this still relevant?”.

Lots of described techniques are common place in everyday software development, however some of them evolved, for example: Microservice. It represents a bounded-context and due to the nature of a microservice, it is separated and doesn’t share objects or internals. Translators, entities, value objects and aggregates are fairly standard on projects I’ve been in so far. Layered architecture, frameworks, team work, supplier-consumer team relations, managers, refactoring and ivory tower architects are fascinating subjects, but again been there and done that. I’m not a history buff but I do enjoy it and so I find myself smiling reading through some parts, lets not forget the book is almost 20 years old. I did find an answer to one lurking question I had for a while: “why less capable engineers tend to accumulate in a legacy but still important, core software systems?” and let me say, Eric nailed it.

So some techniques might be dated but in my mind still relevant, however all of it is just peripheral stuff. What about the core? What about domain? Well this is where things get muddy for me. As I read through examples and discussions, I understood the value of good design, born in ubiquitous language, with help of business specialists, capable fearless engineers with commitment to deep thinking and forever deepening understanding of a business model. In theory DDD is the best thing that can ever happen on a project, however in reality (and by some degree of the author’s own admissions and disclaimers), DDD is not always the best choice or even a possibility. In my mind too many things must align in order for DDD to happen and bare fruit. In any system with many moving parts, there are things that can and typically will go wrong, especially when we are talking about creative work and human operated system.

But is the book still relevant? I think so, I would not be putting it on the top of “must read before programming”, but it still be on the list. I’m sure that commitment to deep thinking and modelling will not be going away any time soon. On top of it, perhaps as an industry we are no long bounded by monolith, but bounded-context is here to stay in one form or another.

In a nutshell:
-: long, dry read
-/+: relevance of some ideas in present software development
+: methodology to design and implementation
+: covers lots of aspects of system development
+: plenty of discussions
=: the book is good, I think people aspiring to be or current architects will reap lots of benefits. Few things feel dated but lots is still very much applicable and valuable. There are lots of books and materials that hold (IMHO) more value for developers in early and middle stages of learning the craft. But at some point Domain Driven Design should be considered.

Title: Domain-Driven Design: Tackling Complexity in the Heart of Software
Author: Eric Evans

Domain-Driven Design by Evans Eric

I took few notes during the read:

The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life

The book wasn’t on my reading list, but I had a long drive and a friend suggested it, so here I am. Now I’m not into “self-help” books, however I did read a couple related books in the past.

So should you give a f*ck about this book? The book is well written and quite interesting but by no means deep. Like many other books, it essentially calls for you to figure out your priorities and focus on them. Unlike other books, this one seems to fill a particular niche – millennial struggle. One has to admit, life nowadays is different from the past and the pace of change is accelerating. It is not a bad thing per se, but presents different challenges. Perhaps you have less chances to be physically harmed or abused, but mentally… I say more. Information stream is just overwhelming and it comes from every part of the world, depending on your web-preference, you can be endlessly bombarded by good or bad news. On top of that there is instant-gratification phenomenon, press a button or better yet just imagine it and you are the winner.

Now one thing that got my curiosity peaked is: “counterintuitive approach” – which took me a bit by surprise, but let me explain. Due to my background, upbringing and some personal challenges in the past, I’m not what you would call a cheerful person. I consider myself a neutral, but I would not blame you if I come across as pessimistic. As a kid I never could answer: what would I like to achieve or be when I grew up. As teenager I adopted “avoidance strategy” (I also call it “working from negative”) – do anything to avoid A or B or C outcomes. So I went to university in order to avoid being a disappointment to my mother and working for low wage for the rest of my life. By default I always pick to do something in order to mitigate or eliminate an obvious or bigger problem (in my estimation) that is coming up. But no-one is perfect and self-delusion is an evolutionary tool, so drinking, smoking and junk food are my guilty pleasures. So to my big surprise the author actually explores, explains and recommends the “avoidance strategy” to achieve things and make a better life for yourself.

In a nutshell:
-: can use a bit more depth and some examples are questionable
+: well written & easy read
+: recipes and methods
+: a counterintuitive approach
+: short
=: it is a good book, with some out of the box ideas and discussions. It is short, hits all main issues and doesn’t overburden – can be read in one (perhaps long) sitting – well-worth ROI.

Title: The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Author: Mark Manson

Clean Agile: Back to Basics

Robert C. Martin (aka uncle Bob) is one of the men who wrote Agile Manifesto. He created lots of worth while material for developers and championed TDD in a very hands-on approach – thanks for 3 laws of TDD.

I read couple of his books and watched countless hours of his teachings on YouTube. I invested heavily into TDD (thanks to Kent Beck ), which payed off for me in more ways than one and my commitment goes beyond words – please feel free to download and print TDD posters.

So I’m a fan, well… not really. I see lots of value in uncle Bob’s ideas and practices, so I have to give credit where it is due. However I don’t agree with everything he says and so I have couple of bones to pick over the book, but first things first.

The book came out at a very interesting times (end of 2019), when agile is a mainstream – everyone does agile now. Agile coaches without any technical background are training software teams, management happy to track development progress by every commit you make on hourly basis and damn the XP practices, full speed ahead. So timing of the book feels spot on, my only wish is that the book ends up in hands of managers.

But what about developers? Did I as a developer waste my time on the book? No, absolutely not! The book is a very good – easy read, short, concise and no fluff. It contains core concepts on what agile is, what it is meant for and all the practices associated. Now don’t expect details, it is a short book with it’s main focus on agile as a whole and not a full blown technical guide. However, it will provide enough to go and dig into each individual practice and believe me, some of these practices worth their own book. For example:

Now I can’t shake the urge, so I’ll indulge it: I read Kent’s Beck TDD by example book in 2019, however the book originally was published in 2000 – speaking of being late to the party. By that time I was doing TDD for few years and participated in a few heated discussions on the subject. I guess 19 years is enough time for any subject to become semi-mysterious, bloated and extended beyond the original purpose. So the book was short of a revelation to me, it was simple, pure or how uncle Bob puts it: “back to basics”. It cleared the water, set boundaries and removed mysticism. Is it dated? Yes. Does it deal with modern complexity of micro services? No. But that’s the whole point: what is the original issue and how to deal with it; nothing more, nothing less.

Uncle’s Bob book is exactly the same way. It describes original issues and explains how to deal with them, nothing more and nothing less. If agile doesn’t fit into your team/organization then so be it. Don’t buy into over extended claims of agile industry that it will solve your problems. See for yourself what is agile all about, if it fits, go for it, if it doesn’t then look for something else. Perhaps there are next generation processes and perhaps they are based off agile, but don’t try to force something that doesn’t fit. One last note that I can’t pass, because it is personal and eats me up, I believe Kent Beck summarized it the best:

good engineering is only a small part of a successful project but bad engineering is main reason project fails

Kent Beck

Now it is time to pick a bone or two with the book. I respect uncle Bob and with this in mind let me ask: why go into something that he has limited knowledge and/or interest. In particular he offers his thoughts on agile in large enterprises. The subject came out iffy at best and confusing at worst. “Agile is for small teams” – yes and let’s leave it at that. There is no need to elaborate on the subject with dubious conclusion: world knows how to manage large projects, the modern society is a testament to that. I guess modern Boeing 737 MAX is also a testament to world’s ability to manage large projects. While he might be right, the book doesn’t answer or give much insight into the subject, so why talk about it at all?

Another bone is the value itself, I always been confused by the word and perhaps the whole argument stems from that, but let me elaborate. If we ask developer why he created so much code for let’s assume rather simple requirement, an answer could be: the code is fail safe, optimized and design wise allows for extensibility. Now in the mind of that developer he created ultimate value for the customer! What could be better than having a safe, fast and extendable code? Another developer might look at the same code with a very different perspective: it took too long to write, by making the code safe, it has many conditions that will never come to be, simply because such a data doesn’t happen that deep into the module. It is fast, but the functionality is not time bound, so unnecessary complexity for no apparent value. The code is extendable but no one has a crystal ball, so why make the code extendable at a cost to a customer who might not need to extend or modify it at all. Has this ever happened in your team?

Now I know, there are XP/Agile practices that guide us through all those tough technical challenges. But in order to invoke those practices (TDD, Simple design, refactoring, pair programming and so on) we must once again talk about the value. One developer with years of experience will look at TDD and say: “nonsense, overkill, waste of time”. Another developer might have exactly the opposite view, but do those opinions matter? If the entire team has to decide on values, then each opinion will matter, now it becomes a debate and political struggle to adopt XP practices/policies. More over how do you go about proving the value of those practices? The book says: “Instead of pushing TDD, maybe we could start agreeing on the value of reducing the time it takes to test our entire system. How long does it take today? Two hours? Two days? Two weeks? How many people are involved? What if we could reduce it to 20 minutes? Two minutes? Maybe even 2 seconds? And what if we could do that at any time just by pressing a button? Would that give us a good return on investment? Would that make our lives easier? Would we be able to release reliable software faster?”

Brilliant, we need to measure and record everything and apply statistics. Now, complexity of the decision making and cost of the entire team is going up, at the cost to a customer and thus far with no apparent value. And by the way, there are other ways to achieve the same result without let’s says TDD or any other practice. But let’s move on next and assume that we agreed on practices. Statistics is powerful, but does management need convincing? Do they want to spend more money? Is data all it takes to convince management and customers? Could there be other values at play? Ultimately a value is an elusive term, we all want a value but which one is a great question. Humanity is diverse and so value is very relative. All of us see value in different things even when statistics and data dictates otherwise. In lots of cases we don’t even have the right or enough data to deduce a value, yet we place bets and talk about the value.

Now the value topic is endless and perhaps I should examine it in a separate post, but now it’s time for final thoughts. The book has its flaws, some I discussed, some I didn’t (hello to end-to-end testing and QA responsibilities). However I wholeheartedly believe that the book is worthwhile the investment. Uncle Bob is entertaining as ever, the timing is spot on, the subject is fascinating and engaging. More importantly though, it brings agile back to the inception, drawing boundaries and highlighting essentials.

In a nutshell:
-: a bit short and has some confusing topics
+: easy read, to the point, concise
+: useful examples and discussions
+: helpful for managers, clients and developers
+: much needed refresh on agile
=: good book, has a lot of value for any developer, manager and client. Book is a bit short and some topics could have been expanded, but over all worthwhile the investment.

Title: Clean Agile: back to basics
Author: Robert C. Martin

I made few note while I was reading the book, so I figured to leave them here just for fun:

The Mythical Man-Month

“Adding manpower to a late software project makes it later.”

Brooks’s Law

Sooner or later every developer learns about Brook’s Law, for me it was later, but still better than never. After the encounter and countless references to the book on the internet, I decided to read it for myself and see what it’s all about.

The original book came out in 1975 and the latest revision in 1995. I think it is important to set expectations right, and accept that the author wrote a lot from that perspective – good old days when the industry still debated “if-else block” vs “goto statement”. In addition, the book isn’t an easy read, lot of technologies/terminologies aren’t familiar to me and that made it harder to follow. However I don’t think any of that should be a showstopper, I say: “push through”!

Opinions are like assholes – everyone got one and I’m no different. However I’m really struggling to express my thoughts on this book. On one hand the book is quite insightful, on the other hand, for the lack of better word – irrelevant. On one hand human behaviour didn’t significantly change since 1975, on the other hand business did. Let me give you an example from my personal experience: 45 years after the book has been published, managers still think that adding new developers to meet a three-month deadline is a solution. Never mind that a good developer typically needs more than three months to even get up to speed on our projects. However, adaptation of scrum (or alike) methodologies and business acceptance of small value-adding iterations has changed the way developers schedule and deliver code. There is no more hiding, in every sprint something of a value must be developed, demoed and shipped.

I can grumble, agree and disagree with the author on several points, but I think it is meaningless and unfair. I think the book should be taken for what it is, and not some sort of a guide from the days long gone to the present generation. Nevertheless, perhaps some people must read it for the sake of not solving the same old problems, the same old way, that never worked anyhow. Perhaps everyone should read it and understand that not all IT problems uniquely belong to IT industry and an answer is readily available just outside of it. Perhaps I should stop rambling and admit: may be the book didn’t impress me as much as I hoped it would but at least I don’t feel any regrets spending my time with it.

In a nutshell:
-: Not an easy read if you aren’t familiar with terminology and technology of the past
-: Some irrelevant concepts
+: A lot of insight into software industry, some still hold true
+: Interesting references and opinions
+: Enjoyable, with certain expectations
=: I don’t think this book should be atop a reading list. However if you are curious and have time, I wholeheartedly recommend it. Don’t set any expectations, remember the book originated in 1975 and enjoy the essay.

Title: The Mythical Man-Month: Essays on Software Engineering
Author: Frederick Brooks

Notes & Quotes from the book, I couldn’t help myself but to take:

“Solutions to many IT problems already exist in other industries, but IT pro feel and act as those don’t apply.”

“Techniques proven and routine in other engineering disciplines are considered radical innovations in software engineering.”

“Self-Documenting Programs – a basic principle of data processing teaches the folly of trying to maintain independent files in synchronism. It is far better to combine them into one file with each record containing all the information both files held concerning a given key. Yet our practice in programming documentation violates our own teaching. We typically attempt to maintain a machine-readable form of a program and an independent set of human-readable documentation, consisting of prose and flow charts. The results in fact confirm our teachings about the folly of separate files. Program documentation is notoriously poor, and its maintenance is worse. Changes made in the program do not promptly, accurately, and invariably appear in the paper.”

“Long before any code exists, the specification must be handed to an outside testing group to be scrutinized for completeness and clarity. As Vyssotsky says, the developers themselves cannot do this: “They won’t tell you they don’t understand it; they will happily invent their way through the gaps and obscurities.””

“Day-by-day schedule slippage is harder to recognize, harder to prevent, and harder to make up than calamities. The first step in controlling a big project on a tight schedule is to have a schedule, made up of milestones and dates for them. Milestones must be concrete, specific, measurable events defined with knife-edge sharpness. A programmer will rarely lie about milestone progress, if the milestone is so sharp he can’t deceive himself.”

“Cosgrove advocates treating all plans, milestones, and schedules as tentative, so as to facilitate change. This goes much too far— the common failing of programming groups today is too little management control, not too much.”

“Intercommunication is worse. If each part of the task must be separately coordinated with each other part/ the effort increases as n(n-I)/2. Three workers require three times as much pairwise intercommunication as two; four require six times as much as two. If, moreover, there needs to be conferences among three, four, etc., workers to resolve things jointly, matters get worse yet. The added effort of communicating may fully counteract the division of the original task”

“The basic fallacy of the waterfall model is that it assumes a project goes through the process once, that the architecture is excellent and easy to use, the implementation design is sound, and the realization is fixable as testing proceeds. Another way of saying it is that the waterfall model assumes the mistakes will all be in the realization, and thus that their repair can be smoothly interspersed with component and system testing.”

“The first step is to accept the fact of change as a way of life, rather than an untoward and annoying exception. Cosgrove has perceptively pointed out that the programmer delivers satisfaction of a user need rather than any tangible product. And both the actual need and the user’s perception of that need will change as programs are built, tested, and used.”

“First, the man with strong management talent and strong technical talent is rarely found. Thinkers are rare; doers are rarer; and thinker-doers are rarest.”

“The job done least well by project managers is to utilize the technical genius who is not strong on management talent.”

“In tasks that can be partitioned but which require communication among the subtasks, the effort of communication must be added to the amount of work to be done.”

“In tasks that can be partitioned but which require communication among the subtasks, the effort of communication must be added to the amount of work to be done.”

“Failure to allow enough time for system test, in particular, is peculiarly disastrous. Since the delay comes at the end of the schedule, no one is aware of schedule trouble until almost the delivery date. Bad news, late and without warning, is unsettling to customers and to managers.”

“But false scheduling to match the patron’s desired date is much more common in our discipline than elsewhere in engineering. It is very difficult to make a vigorous, plausible, and job-risking defense of an estimate that is derived by no quantitative method, supported by little data, and certified chiefly by the hunches of the managers”

“The fate of WIMP: Obsolescence. Despite its excellencies, I expect the WIMP interface to be a historical relic in a generation. Pointing will still be the way to express nouns as we command our machines; speech is surely the right way to express the verbs. Tools such as Voice Navigator for the Mac and Dragon for the PC already provide this capability.”

“Men and months are interchangeable commodities only when a task can be partitioned among many workers with no communication among them”

“The bearing of a child takes nine months, no matter how many women are assigned.”

Frederick Brooks

Refactoring: Improving the Design of Existing Code / Рефакторинг: улучшение дизайна существующего кода

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.

Refactoring (verb): to restructure software by applying a series of refactorings without changing its observable behavior.

О книге

Ах, Мартин Фолер, каждый программист хотя бы один раз слышал его имя. По какой-то ещё не осознанной причине, я всегда ассоциирую Мартина со своеобразным духовным лидером разработчиков и архитекторов. Его выступления всегда заставляют задуматься. На этой неделе я с грустью дочитал его книгу по теме рефакторинга. С грустью? Я очень, очень медленно шел по последним 30 страницам книги, переодически останавливаясь, откладывая «на потом». Что-то внутри меня не хотело заканчивать эту книгу – хотелось чтобы приключение продолжалось. Но все хорошее когда-либо заканчивается, а значит пора подвести итог.

Заметок и мыслей собралось у меня много и поэтому начну с конца: книга хорошая – стоит времени и денег! Я лично считаю, что мне стоило прочитать эту книгу на пару лет раньше – возможно, это помогло бы мне с некоторыми неправильными представлениями о разработке и рефакторинге. У книги есть 2-е редакции, первая базирована на языке Java, а вторая на Javascript. Я прочитал вторую редакцию и, хотя мой “боевой” язык программирования Java, мне очень понравились приведённые в книге примеры и идеи на Javascript-е. Стоит отметить – я НЕ фанат Javascript-а по многим причинам, однако после Java, это как доза беспечной свободы и креатива – делай что хочешь, как хочешь, даже если тебя это впоследствии убьет. Также, по словам автора, он изменил пару советов во второй редакции, так как за прошедшее время некоторые традиции в программировании изменились, однако большинство советов остались прежними. Книга делится на две части: первые 100 страниц – история о разработке софта, почему и как рефактор является неотъемлемой частью разработки и дизайна. Вторая часть (300 страниц) – “бесконечные” техники рефакторинга из одной структуры кода в другую и наоборот, с объяснениями и хорошо разобранными примерами. В итоге, я считаю, что книга подойдет разработчикам с разными уровнями опыта, но возможно не начинающим! Как ни странно (сарказм), но автор очень сильно опирается на тесты, поэтому желательно усвоить тематику заранее, а также быть хотя бы немного знакомым с TDD, не зря со-автором книги является Кент Бэк.

+: Простое и доступное изложение
+: Детально описанные примеры
+: Набор методик с объяснениями
+: Для всех разработчиков, за исключением начинающих
+: Отличные наставления
=: Хорошая, доступная, полезная книга – стоит вкладывать деньги и время.

Название: Refactoring: Improving the Design of Existing Code
Авторы: Martin Fowler & Kent Beck

Разработка и жизненный опыт

Я не люблю мешать свой жизненней опыт с обзором книги, однако в редких моментах оно того стоит. Тут я хочу обсудить некоторые советы/заметки из книги и поделиться опытом, для того чтобы другие программисты не ступали туда, где побывали уже все – поверьте оно того не стоит.

Не рефактор

“If someone says their code was broken for a couple of days while they are refactoring, you can be pretty sure they were not refactoring.”

“Если кто-то сказал что код был сломан пару дней, потому что они делали рефакторинг, можете быть уверены, это был не рефакторинг”.

Довольно рано в моей карьере я лично повстречался с таким феноменом. Один программист уходил в “рефакторинг” не на пару дней, а на неделю или две. После этого фичи ломались, новый код невозможно было смерджить и наступал хаос. Как минимум ещё неделю программисты ходили с перьями, бубнами, барабанами на шее, зачитывая мантры, танцуя вокруг огня в попытке воскресить этого Франкенштейна. Со стороны все это выглядело жутко, так как сроки горели, софт работал плохо и менеджмент смотрел на нас как на врагов народа, мечтая о плетке и кандалах.

Вытекающие последствия: менеджмент думает что вся команда не компетентна (даже если хаос сеет один программист) и на то есть причины. Доверие к команде падает и соответственно программистов начинают слушать все меньше и меньше. Далее менеджмент начинает придумывать процесс, который в теории должен предотвратить такой хаос. Слово рефакторинг считается нецензурным и употребление его разрешается только в особых и согласованных случаях. В итоге, на первых парах все отлично, фичи добавляются, софт работает, хаос остановлен. Однако код начинает медленно деградировать, так как никто не хочет/может рефакторить. Спустя некоторое время, добавление фич начинает замедляться и разработка начинает занимать все больше и больше времени.


“The whole purpose of refactoring to me is to program faster, producing more value with less effort”. “Refactoring is always done to make the code easier to understand and cheaper to modify.”

“Для меня, вся цель рефакторинга – программировать быстрее, создавая больше ценности с меньшим усилием”.
“Рефакторинг всегда делается для того, чтобы код было легче понимать и дешевле модифицировать”.

Некоторые программисты думают, что писать много кода это хорошо. Если мы забудем про память и другие ресурсы компьютера и отдельно посмотрим на “много кода”, то в теории ничего плохого в этом нет. Проблемы начинаются в тот момент, когда код нужно изменять, допустим, для новой фичи. Первая проблема: нужно много читать, вторая проблема: много понимать, третья проблема: много менять. Все эти занятия выливаются во “много времени” и как итог “много денег”.

Теоретически, проблему можно решить на корню – писать минимальный и чистый код, однако реальность диктует свои правила. Когда первый раз решаешь проблему, то редко получается с первого раза. Вариаций на “первый раз” может быть много: новая платформа, новая библиотека, отсутствие опыта, незнание домена и так далее. Реалистичное решение проблемы – постоянный рефакторинг: начал работать над кодом; прочитал; понял; посмотри, что можно исправить (очень часто, исправить можно много чего). Добавил код, пройдись ещё раз, посмотри, если ты понимаешь что-то лучше теперь, чем изначально, исправь – сделай проще.


“To really operate in an agile way, a team has to be capable and enthusiastic refactorers – and for that, many aspects of their process have to align with making refactoring a regular part of their work.”

“Чтобы по настоящему работать в agile, команда должна состоять из способных и полных энтузиазма «рефакторов» – а для этого много аспектов рабочего процесса должно выстраиваться так, чтобы рефакторинг был частью повседневной работы.”

К большому сожалению опыта с этим у меня нет. Для меня рефакторинг это часть моего личного процесса разработки. Перед тем как я пишу код, я читаю много кода, пытаясь понять что происходит и как оно работает. Пока я это делаю, я также рефакторю код по мере возможности и ценности. Потом я добавляю новую фичу и опять читаю, смотрю, думаю и рефакторю код по мере возможности и ценности. Такой режим работы возможен потому что:
⁃Я практикую TDD
⁃Большинство команды или практикует TDD или пишет хорошие тесты (советую книгу)
⁃ Там, где тестов нет или они плохие, я делаю рефакторинг исключительно автоматизированными средствами IDE.

Теперь большинство команды смотрит очень вяло на рефакторинг и обходят его стороной по возможности. Это происходит по нескольким причинам. Первая: способности и знания самих программистов у нас довольно тусклые. Вторая: культура компании такова – если ты все делаешь быстро (даже тяп-ляп и в продакшен), то ты герой и лавры тебе, а потом хоть потоп – это кто-нибудь другой разгребет. Третья: долгое время старшие программисты и архитекторы не давали рефакторить, даже банальные и простые вещи, ссылаясь на качество наших программистов. В итоге, когда я начал мой рефактор-путь, меня много критиковали, вставляли палки в колеса и так далее. Но я выжил и по меньшей мере сейчас никто ничего мне не говорит, даже если я изменил очень много кода. Но тут важное “но” – я никогда не оставляю код в сломанном состоянии и очень редко добавляю баги по причине рефакторинга. Баги в основном прокрадываются там, где плохие тести или их нет.

Методические рекомендации

“Here’s a guideline Don Roberts gave me: The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyways. The third time you do something similar, you refactor.“

“Вот методические рекомендации от Дона Робертса: Когда ты первый раз что-то делаешь, то просто сделай. Когда ты делаешь что-то похожее второй раз, поморщись и сделай дубликат кода. Когда ты делаешь похожее третий раз, то делай рефакторинг”.

Отличная рекомендация, которой следует пользоваться, так как порой в порыве энтузиазма, хочется рефакторить при первом же появлении дубликата кода. Но частенько бывает так, что тратишь много времени на рефакторинг, а в итоге овчинка выделки не стоит. Нюх на рефакторинг приходит с опытом и практикой, поэтому стоит быть терпеливым, практиковаться и не забывать эту простую и эффективную рекомендацию.

Оптимизация цикла

Я всегда придерживался аксиомы: дубликат кода – всемирное зло, которое должно быть найдено и уничтожено. Часто, когда обрабатываешь массив данных, используешь for-loop (цикл), в котором находятся “правила” изменения данных. Если правил много, то кода в цикле получается тоже много. Читать такой код занимает время и можно было бы все упростить, если сделать несколько циклов и выполнять разные правила в разных циклах по мере необходимости. Однако такой подход значит, что по массиву надо будет проходить несколько раз – в свою очередь большая “О” будет расти, а это как мы знаем из обучения в университете – зло!

Мартин на это смотрит в точности наоборот! Приоритет должен отдаваться не количеству подобных циклов, а чистоте и легкости понимания кода. Автор считает, что лучше иметь чистый код в цикле и пусть с дубликатами, чем один цикл, но без дубликатов. Объяснений тут несколько, первое: компиляторы умные и могут оптимизировать код, второе: проблемы производительности редко приходят из обработки данных в памяти, третье: если нужно оптимизировать производительность кода, то это куда легче сделать с простым кодом, чем со сложным.

Для меня это был немного сложный разворот, однако, немного подумав о своем личном опыте, я понял что это действительно так. Частенько все вкладывается в один цикл на “благо ради”, а потом код в цикле разрастается и в определенный роковой момент, кто-то по необходимости добавляет звонок на внешний ресурс (база данных, сервис или файлик). Если система начинает тормозить и нужно оптимизировать, то это превращается в кошмарный сон, так как нужно рефакторить все и сразу.

Когда хочется написать комментарий

“When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous.”

“Когда чувствуешь, что нужно написать комментарий, сперва попробуй отрефакторить код таким образом, чтобы комментарий стал излишним”

Честно говоря, я даже не помню когда последний раз писал комментарии на код. Мартин не первый человек который обсуждает эту тему, на мой взгляд тематика лучше разобрана в книге дядюшки Боба – Чистый код.

Не будьте великим программистом

Statement Kent Beck often makes about himself: “I’m not a great programmer; I’m just a good programmer with great habits.”

Кен Бек часто говорит о себе: “Я не великий программист, я просто хороший программист с отличными привычками”.

Из личного опыта мне довелось поработать с великим программистом и опыт довольно интересный. С одной стороны “писькомер” с другой “Дартаньян”. Для этого великого программиста ВСЁ было крайне просто: написать сложный код; пропустить тесты, потому-что “код тривиальный”; оптимизировать до того как надо. С одной стороны я выучил много чего, работая с ним, с другой я видел ошибки, которые он делал и он не хотел даже выслушивать доводы. Великий программист ушел, его код остался и до сих пор его дизайн поражает воображение, так как там черт ногу сломит, программисты обходят его код стороной!

Тут я хочу дать пару советов программистам. Учитесь, всегда учитесь, практикуйтесь, читайте книги, блоги и документацию! Не изобретайте колесо там где оно уже давно есть. Практикуйтесь писать чистый, понятный код – помните простота сестра таланта. Изучите разные техники, включая TDD, оно всегда поможет. Заприте свое эго под большой замок, оно никому не нужно и в итоге будет только мешать. Взращивайте отличные привычки и знания.

Что говорить менеджеру о рефакторе

“What do I tell my manager about refactoring? Of course, many managers and customer don’t have the technical awareness to know how code base health impacts productivity. In these cases I give my more controversial advice: Don’t tell!”

“Что говорить менеджеру о рефакторинге? Конечно, многие менеджеры и клиенты не имеют технических знаний о том как хороший код влияет на продуктивность. В таких случаях я даю свой спорный совет: Не говорите!”

Этот совет я слышу не первый раз и не от одного человека. Много раз, когда я ходил на семинары, эта тема всплывала и ответ был одним и тем же. Если вы находитесь в таком положении, то я поддерживаю совет – делайте что надо и не нужно никому ничего говорить. Однако помните выше описанные советы и методики – это очень важно! Так же прочитайте эту книгу, она вам очень поможет.

Теперь хочу поделиться опытом альтернативного пути развития событий. Такой путь обычно происходит в не шибко умной команде с бесхребетным тимлодом, которого больше интересуют политические игры, чем технологии. В какой-то момент, рефакторинг попадет на горизонт и будет расценен как что-то мифически-полезное, но опасное и будет принят на вооружение как оружие массового поражения. Другими словами рефакторинг включат в официальный процесс работы и будут применять только там, где нужно изменить “все”. Из личного опыта такое заканчивается по двум сценариям. Первый сценарий: пишутся рефактор-карты и кладутся в бэклог, где они долго бродят, протухают и в итоге выкидываются. Второй сценарий: выделяется неделя или две на рефакторинг какого-нибудь Титаника. И тут в зависимости от программиста: или переставляются стулья на палубе или происходит такой кап-ремонт, что в последствии принимается решение такого больше не делать, подписывая договор с менеджментом об ограничении использования оружия массового поражения.


“I’m sure you have heard many times that you cannot prove that a program has no bugs by testing. That’s true, but it does not affect the ability of testing to speed up programming.“

“Я уверен что вы слышали много раз, что нельзя доказать что в программе нет багов через тестирование. И это правда, однако это не значит что тесты не помогают вам программировать быстрее.”

“Don’t let the fear that testing can’t catch all bugs stop you writing tests that catch most bugs”

“Не позволяйте страху остановить себя от написания тестов которые поймают большинство багов, лишь потому что тесты не поймают все баги”

“A suite of test is a powerful big detector that decapitates the time it takes to find bugs”

“Набор тестов это очень мощный детектор, который позволяет сократить время поиска багов”

Я лично фанат TDD и почти всегда пишу тесты. Теперь стоит отметить, что я не фанатик и понимаю, что не всегда и не везде нужно писать тесты, однако по большинству я их всегда пишу. К такому состоянию я пришел из личного опыта написания кода и считаю что тесты действительно помогают писать код быстрее и допускать меньше ошибок. Если взять один момент из моего опыта, то тесты спасли меня когда я в аварийном режиме разрабатывал патч для прода, работал по 12 часов в день и если бы не тесты, я бы не успел закончить во время. Так же стоит отметить что на протяжении почти 2-х лет, код работал четко и без ошибок или багов. Позже код был удален, так как больше не был востребован.

Pull Request

“The common pull request model, where a reviewer looks at code without the original author, doesn’t work too well. It’s better to have the original author of the code present because the author can provide context on the code and fully appreciate the reviewers’ intentions for their changes. I’ve had my best experience with this by sitting one-on-one with the original author, going through the code and refactoring as we go. The logical conclusion of this style is ‘pair programming’: continuous code review embedded within the process of programming.”

“Обще принятая модель пул реквестов, где рецензент просматривает код без автора, не работает особо хорошо. Намного лучше сидеть с автором кода, который может предоставить контекст к изменениям и обьяснить, почему были приняты те или иные решения. Из моего опыта лучше всего сидеть вместе с автором, разбирая код и делая рефакторинг на лету. Логическое завершение такого стиля работы называется: “парное программирование”, где процесс рецензии происходит по ходу разработки.”

У меня на работе пул реквест модель является де-факто. К большому сожалению, все косяки этой модели выходят на лицо, когда невозможно понять почему именно так было сделано. Сидеть с автором редкая реальность, а парное программирование запретная практика. Менеджмент считает, что это бесполезная трата денег. Я лично считаю, что это большая ошибка, так как когда работаешь парно (а с этим опыт у меня есть), то код разрабатывается быстрее. Так же довольно легко передается опыт и ремесло. Например: если новый джун. программист работает один, то зачастую это потерянное время. Он делает много ошибок или не может сделать сам вообще ничего. В итоге после нескольких дней, ему все равно приходится работать с другим программистом. Если подсчитать, было бы быстрее и дешевле сразу так сделать. Когда два опытных программиста работают вместе, то получается быстрее, проще и чище.

Однако у парного программирования есть и свои косяки. Одна большая проблема – это личность человека. Не все могут работать в паре, может кто-то жуткий интроверт и ему очень тяжело. Так же если в команде нет способа избавиться от непригодного программиста (допустим он не хочет учиться и/или не умеет программировать, а такое тоже бывает), тогда парная работа превращается в один работает, а другой спит! У нас на работе такое явление частое, а команда ничего по этому поводу сделать не может. Менеджмент по непонятным причинам не увольняет таких чудо-работников, а дает бесконечные вторые шансы. В таких ситуациях программисты начинают отказываться работать парно и по понятным причинам, в итоге результат на лицо.


“Renaming is not just an exercise in changing names. When you can’t think of a good name for something, it’s often a sign of a deeper design malaise. Puzzling over a tricky name has often led us to significant simplifications to our code.”

“Переименование это не просто изменение имени. Когда ты не можешь придумать хорошее имя для чего-либо, часто это знак более глубокой проблемы. Долгое размышление над замысловатым именем, часто приводило к существенному упрощению кода.”

Как говориться в программировании есть две сложные задачи: придумывать названия и кэширование. Интересно, сколько существует вариаций этой шутки? Я даже не знаю сколько раз я повторял выше описанное своим программистам. Когда я перешел в новую команду и посмотрел на их тесты, то вздрогнул. Спустя пару месяцев я ввел обязательную методику по названию тестов (если интересно, пишите я раскажу) и ещё 8 месяцев объяснял почему и как, не раз объясняя, если тест не соответсвует названию, то тест слишком сложный – разбейте на несколько отдельных тестов. Уже на данный момент все идет по маслу, битв больше нет, тесты плюс/минус в хорошем состоянии. Невероятно как маленькие изменения в названии ведут к большим изменениям в коде и работе.

Запомните это

“I was just as surprised myself when Kent Beck showed me how to do this in a hotel room in Detroit two decades ago. The key to effective refactoring is recognizing that you go faster when you take tiny steps, the code is never broken, and you can compose those small steps into substantial changes. Remember that – and the rest is silence.”

“Я был очень удивлен, когда 20 лет назад Кен Бэк показал мне как это делается в комнате гостиницы в Детройте. Ключ к эффективному рефакторингу – это осознание что ты программируешь быстрее когда делаешь маленькие изменения, код никогда не ломается и ты можешь составлять маленькие изменения в большие. Запомни это, а остальное тишина.”

Думаю, весь цимис успеха заключается именно в маленьких шагах. Зачастую мы думаем что это муторно, излишне и медленно. Однако если цель и задача в том чтобы сделать что-то хорошо и четко, то самый быстрый способ это делать работу маленькими фокусированными шагами. Возможно такой подход идет в разрез с общепринятой идеологией, но для меня он работает и работает хорошо.

Я советую вам попробовать этот подход на себе, главный трюк – разбить работу на маленькие шаги. Стратегий много и описывать их не буду, однако оставить с пустыми руками тоже не могу – посмотрите на “Как это решить”.