<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Poisonous John (Ivan Fateev) on Medium]]></title>
        <description><![CDATA[Stories by Poisonous John (Ivan Fateev) on Medium]]></description>
        <link>https://medium.com/@poisonousjohn?source=rss-2c05dcd3c106------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BL9CqFNSXzGtsg4fXw2O_Q.jpeg</url>
            <title>Stories by Poisonous John (Ivan Fateev) on Medium</title>
            <link>https://medium.com/@poisonousjohn?source=rss-2c05dcd3c106------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:52:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@poisonousjohn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to clean up a legacy code: a practical plan that will be liked by team and managers]]></title>
            <link>https://poisonousjohn.medium.com/how-to-clean-up-a-legacy-code-a-practical-plan-that-will-be-liked-by-team-and-managers-b6d1c9f9ca6a?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d1c9f9ca6a</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Tue, 19 Jan 2021 12:37:27 GMT</pubDate>
            <atom:updated>2021-01-19T12:43:11.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of the articles and books tell you how to write a “good code”. But in the real life, you often find yourself deep in the shit after joining some company or project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IdmQHQpuEQhAI_Sf" /><figcaption>My association for working with the dirty codebase | Photo by <a href="https://unsplash.com/@quinoal?utm_source=medium&amp;utm_medium=referral">Quino Al</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Blue or Red pill?</h3><p>When it happens to join a project with a poor codebase, usually you have two options:</p><ol><li>Complain about the code</li><li>Search for another job</li><li>Start doing everything right</li></ol><p>The first two options are easy and crystal clear. But the last one is not.</p><p>I was in the same situation a bunch of times, and always chose the last one. And here what worked for me (TL;DR plan):</p><ol><li>Plan changes</li><li>Isolate legacy</li><li>Lead by example</li><li>Teach</li><li>Scale</li><li>Clean the shit in small and quick iterations</li><li>Document the code as you refactor</li><li>Write tests</li></ol><p>Now, before getting into more details, let’s think a bit.</p><h3>Why does this happen?</h3><p>The poor state of the codebase is a result of previously made decisions. It’s hard to tell if they were right or wrong. But the point is that “clean code” is not always a good option for business.</p><p>Nobody expects you to write a clean and neat code for a prototype. You should make the prototype as fast as you can, check your hypothesis, and throw it away.</p><p>Yes, some people CAN write code fast and clean, but it’s hard to find them. And startups, for example, do not have time and money for that.</p><p>As the company grows, priorities change, and businesses need larger teams, more features etc. It’s impossible to continue in a paradigm where speed is the only priority.</p><p>So, being an experienced developer, you likely may find yourself in a project which was written by less experienced people. And that’s fine.</p><p>My point is that complaining and blaming people for being dumb is not professional.</p><p>Now, let’s move to the points of healing the project in more details</p><h3>Plan changes</h3><p>All changes for the good should start with a plan. Usually I identify what needs to be improved, break it down for tasks, roughly estimate them, and also assess benefits this task can bring to the codebase in a 5-star scale.</p><p>Then I prioritize a backlog by the highest benefit and the smallest size.</p><h3>Isolate legacy</h3><p>To start refactoring without blocking feature development, you need to commit changes in small chunks and predictable deadlines.</p><p>One of the handiest ways to run smooth ongoing refactoring in huge and dynamic projects is to isolate legacy parts.</p><p>This means before rebuilding all of the “legacy” internals, you need to hide them behind a “clean” abstraction layer.</p><p>So you have to have a clear vision of the architecture you want to get to. Then you need to build that “clean” abstraction interface and put it before the “legacy” part. So all the code users will see only a new, clean interface, and already may start building a better code.</p><p>It’s done with the help of the “Adapter” pattern.</p><p>Meanwhile, the legacy part may be ugly, but the adapter connects it to the clean world.</p><p>Once it’s done, you can start reworking the legacy code. Since the legacy code is isolated, your changes won’t affect anybody else. It literally unties your hands.</p><h3>Lead by example</h3><p>It might be helpful to lead changes by example. This means you need to show your teammates how changes may be executed. It’s absolutely unnecessary to have a “Lead” position to do this.</p><p>Not everybody will agree with changes, but if you did your planning well, it should be easy to “sell” them.</p><p>The next possible step might be selling these changes to your manager, or whoever decides what team should be working on.</p><p>After you’re done with it, you might start with actual leading by example.</p><p>You need to take the first task from the backlog, and do it as you see it. It will be an example of how people can take steps towards a bright future.</p><p>The “Lead by example” strategy helped me a bunch of times where other strategies failed. Being skeptical for a programmer is pretty normal. But when you do not only say that it’s possible to make things better, you actually DO it, and do it well, people start changing their minds.</p><p>They see that you’ve managed to do this, and it means that they can do it too. You gain trust, and future changes will go smoother.</p><h3>Teach</h3><p>The “Lead by example” strategy is also a good opportunity to teach people. You can walk through your teammates over your solution and ideas, and show them improvements using Before/After contrast.</p><p>People always understand concepts better, having real-world examples rather than some abstract philosophic statements.</p><p>Make people feel comfortable to ask questions, share ideas, etc.</p><h3>Scale</h3><p>Once you proved that your plan is good, and you’re on the same page with the team, it’s time to scale it out.</p><p>Recruit more team members to help you out. Guide them through this process. After a few iterations, everybody will see fruits of labor and be happy to help more.</p><h3>Clean the code in small and quick iterations</h3><p>It should not be necessary to say why you would need to execute refactoring in small iterations, but yet.</p><ol><li>Large refactoring is hard to review</li><li>If large refactoring got declined by the team, a lot of manhours be wasted. Doing small iterations is much less risky</li><li>More you spend time on refactoring, the more complex merge will be for you and your teammates. You might find yourself solving conflicts over and over, and something will likely break</li><li>We are bad at estimations, so if a refactoring slips the deadline, you might likely be forced to cancel it</li><li>Focused changes are always easier to deliver</li><li>Small changes have fewer risks to break something and are easier to test</li><li>Never mix the code refactoring with the feature development. You will have a huge mess in this case. You won’t be able to release a feature without finishing refactoring before it, or rollback refactoring separately.</li></ol><p>Focus is the most important part. It’s so easy to deep dive in the shit, and start cleaning it from the bottom.</p><p>But you should force yourself to stop and limit the scope only to what’s is relevant for the current iteration.</p><p>If you do, the team will be happy to work that way, and eventually, you’ll get to the final point.</p><p>If you don’t, well… massive refactoring won’t be finished at all, or it will break too many things.</p><h3>Document the code as you refactor</h3><p>Refactoring is also a good opportunity to clarify things. I rarely see a documented code, but often find myself questioning parts of the code, as it’s hard to tell what this code is doing and why.</p><p>If you managed to find out business requirements or some details about it, document it! This will help you or anybody else who will get back to this part later.</p><p>Also, it’s helpful to document your thoughts on your vision on the refactoring approach.</p><p>For example, I add code comments advising what can be done next to improve this or that part, and how to do it better. So if my colleagues stumble on it, they understand how to move forward.</p><h3>Write tests</h3><p>You’re lucky if the subject of the refactoring has any tests at all. But most likely it’s not.</p><p>Ideally, before refactoring, you should write tests, to make sure, that after refactoring behavior remained the same.</p><p>But we’re not in the ideal world. Often there’s no test infrastructure at all.</p><p>Here what I usually do:</p><ol><li>Provide testability for the new “clean” code first.</li><li>Test all of the new features which should be clean.</li><li>Then you can start bringing testability to the legacy code, step by step, small chunks, remember?</li></ol><h3>Any decent programmer should be able to do both at the same time</h3><p>Though this is true, and I didn’t say that the one shouldn’t, but I personally, find it a bad idea, if the refactoring is not tiny. In this article I meant huge refactoring activities, which can’t be done in a single day and by a single person.</p><p>The point of the article is just to show a structured and predictable way of cleaning up the code, that everybody can understand.</p><p>As a programmer, you see what needs to be done, a pool of tasks. As a manager, you understand that refactoring can be mixed into the daily work, and you won’t be spending development resources for weeks with no visible result.</p><h3>Final thoughts</h3><p>Reworking a legacy code is a tough and long task. But it’s possible. It’s easy to say that we need to rewrite everything from scratch. But structured and planned refactoring is a much better way.</p><p>Refactoring has a cumulative effect. With each iteration, it will be easier and easier to work with the code. So be the leader, take the hardest steps, show how this can be done.</p><p>—</p><p>What works for me, might not work for you, but still, I believe you might give it a try.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d1c9f9ca6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you growing your juniors right?]]></title>
            <link>https://poisonousjohn.medium.com/are-you-growing-your-juniors-right-122e9f99ac0?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/122e9f99ac0</guid>
            <category><![CDATA[teaching]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 11:24:10 GMT</pubDate>
            <atom:updated>2020-04-23T11:24:10.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RG8akz05TdDnnSEn" /><figcaption>Photo by <a href="https://unsplash.com/@josealjovin?utm_source=medium&amp;utm_medium=referral">jose aljovin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have a student. At the beginning of his path, I helped him to comprehend our craft. Then he got into a quite big company. What they did to him…</p><p>Nothing! Literally — nothing. And that’s the point.</p><p>When my student told me about what’s happening in his job, I couldn’t take it anymore and decided to write this article. I hope to help at least some people with it.</p><p>Let’s look at a couple of problems. Such situations happen not only in our industry. You can find them in any place where they hire interns/beginners.</p><h3>Problem #1: Nobody cares about junior</h3><p>Junior worked in a different industry before. It took a long time to decide on a career switch. He learned programming in his spare time. Then he put all stakes on it, quit his old job, and spent several months learning non-stop, living on saved money. Finally, he’s got a new job as an intern programmer, but with a salary much less than he had before.</p><p>During the year Junior’s mentors curators changed all the time. They dumbly threw him from one to another, nobody wanted to take care of him.</p><p>They didn’t give any meaningful task. Just dumped on him some weird shit, which nobody wanted to deal with.</p><p>Later even those shitty tasks came to an end. They said to him to sit and read something, learn yourself.</p><p>Then they let him work with some “specific” product. You know, this kind of corporate product which has a really tiny niche. Such experience means nothing on the job market. Nobody else had either desire or experience with it. So he couldn’t even ask anybody to help out.</p><p>It was a first programmer job for him, so he couldn’t evaluate whether such a situation is normal or not. Junior was afraid that if he couldn’t figure out something, they would fire him. It depressed him, he had a feeling that he’s wasting time, but there’s nothing to do about that.</p><p>He shared it with me, and I recommended to change the job. And he did it.</p><h3>Problem #2: Junior is trained by someone who’s not able to teach, or don’t want to do that</h3><p>Junior liked the new job. They assigned a specific mentor, which gave appropriate tasks, kept an eye on their status, taught a bit. Junior started to improve his skills.</p><p>A couple of months later, the mentor started to behave strangely. In such moments there was a feeling of some personal dislike from his side.</p><p>Just look at the dialog below:</p><ul><li>Junior: Mentor, in regards of the task XXX-413, you said: “Change: implement dialog presentation in class RestoreDbAction” — I didn’t get it, What do you mean by “implement”? Now I just made that it calls RestoreDbAction.Confirm instead of IDialogDisplay.Show. Everything else I leave as is, am I right or I missed something?</li><li>Mentor: It took so long for you to understand. Got it finally?</li><li>Junior: … so I got it right?</li><li>Mentor: What?</li><li>Junior: I needed to use Action.Confirm?</li><li>Mentor: Of course</li><li>Mentor: Why didn’t you get it right away? Any questions??</li><li>Mentor: Just as I expected, Junior, you didn’t get ANYTHING again. I’m just surprised at how you’re slow-witted….. (sad) I returned the task back to you</li><li>Junior: But I asked if I got it right</li><li>Mentor: I also asked. 3 times. And you didn’t get it anyway</li></ul><h3>Why a company needs juniors?</h3><p>Let’s see what’s the point in growing juniors?</p><blockquote>Junior is an investment in the future. Long-term project if you want.</blockquote><p>The company gives knowledge and experience, and beginner specialist starts returning investments in the form of completed tasks. So it’s like an effective symbiosis.</p><p>Junior is ready to write code just for fun. But if you pay money for it — just perfect.</p><p>Faster Junior starts completing real tasks, bring value, more profitable it would be for a company.</p><blockquote>Startups rarely hire juniors. Because they need an instant result. For a startup, speed is the most important aspect. Large companies are different. They can afford a slower pace.</blockquote><p>There are two big points to hire juniors:</p><ol><li><strong>Cheap workforce</strong>: they do not ask much. And if you trained your junior quickly, then you get a fair specialist which brings value, familiar with the company’s processes, and does not cost much.</li><li><strong>Predictable source of advanced specialists</strong>. Hiring is always a pain. Searching for a middle developer can take quite a time and effort. Even if you managed to get one through the interview, you can’t predict how he will show himself. In case of a mistake, the company suffers losses.<br>You can hire a bunch of juniors instead. In this case, the probability to find a good fit is much higher. Good employer spots juniors which grew enough, give them a raise and motivate for further growth.<br>So the company gets a new grown developer, with known performance, familiar with processes, and so on. It’s a win-win situation.<br>If such an approach is arranged in a proper pipeline, then the company can grow safely and stably.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*KbI_evzcBCsk1eTDzYxbfg.png" /><figcaption>Here’s how you actually grow someone</figcaption></figure><h3>7 simple tips on growing a Junior</h3><h3>1. Do not hire juniors if nobody can teach them</h3><p>What can we understand from problem #1? The company hired a junior, though nobody could (or want) to teach him. He wanted to learn. Chased any opportunity to do that.</p><p>But the employer didn’t care about beginner developers. Our Junior didn’t bring any value to the company, didn’t grow as professional, yet got his salary. It’s a lose-lose situation.</p><p>Juniors need constant attention and supervision. They are like children who are learning to walk. At first, they are clumsy, can’t take a step. But every time they get better in it. One day they walk on their own, confidently.</p><p>What could happen if you left them alone, while they’re learning? Something bad will likely happen. They could get hurt, crawl somewhere they shouldn’t, even break something. And this is exactly what we have in problem #1.</p><p>The first stage of junior’s training is the toughest one. It requires a lot of time, emotional efforts, and patience. A company needs to understand, the one who mentors will work slower. But in the long term, it will pay off.</p><p>If you’re not ready for such cost, you should not hire juniors. Don’t waste the company’s resources and people’s time. Please.</p><p>That’s it with problem #1, let’s move on to problem #2.</p><h3>2. Don’t pass the buck</h3><p>In dialog from the problem #2 mentor is the one who’s not right. Junior is not qualified enough to formalize a task, find out missing requirements, design a decent solution, etc.</p><p>The mentor is the only one to blame that junior didn’t get the task right. But instead of fixing this situation he just passed the buck.</p><h3>3. For juniors, you should assign tasks which are detailed as much as possible</h3><p>Mentor has to detail tasks as much as possible. Alternatively, if you want a junior to think more, you can just give a clue of the right direction. But you shouldn’t make an “Intuition” show out of it.</p><p>It’s not necessary to give a task solution right away, but the task description should be detailed enough, to exclude any ambiguity.</p><p>If you have any doubts, talk with Junior again and make sure, that you both are on the same page. And one more thing: you should talk, not write in the chat. It helps a lot!</p><h3>4. Do not assert yourself by hurting others</h3><p>Oh, my rant is going to be long for this one. Because such examples give me a butthurt.</p><p>In the dialog above mentor was really rude and unprofessional with Junior. I can guess that:</p><ol><li>The mentor has a personal dislike for the Junior. It’s hard to tell from just one dialog, but Junior said that he had exactly such a feeling. Should I say that it’s absolutely unacceptable?</li><li>The mentor doesn’t want to do mentoring. It might sound silly, but not everyone wants to do that. A company should keep an eye on who’s training juniors. If some person doesn’t like such a job, nothing good can get out of it.</li><li>The mentor is having a hard time doing his own tasks, not to speak of the junior. No matter how difficult it is, you should not transfer your problems, feelings to others. It’s unprofessional at least, but, just humanly, it’s disgusting. Management has to understand that mentoring takes a lot of time and plan accordingly, allocating a fixed buffer of time in the mentor’s schedule.</li><li>The mentor just can’t teach. A good developer — not necessarily a good teacher. Choosing the right words is worth a lot. What result did the mentor expect? That Junior will think “Oh, what a retard I am, I will work on it”? Such words may discourage, raise doubts. Then people complain about impostor syndrome. Words can kill any desire to ask questions and talk with teammates, because of fear. But the worst part is that a person who put everything on a table may turn around and lose everything. There’s nothing except dumb assertion “you’re stupid, I’m a star”. We’ve all been newbies. Remember how did your colleagues treat you? Did they support you? How did you feel?</li></ol><p>None of the options may be an excuse for such a tone of voice. It’s totally unacceptable to talk that way with your subordinates, colleagues. Assert and humiliate others, taking advantage of your position. Nobody has such rights.</p><p>If the mentor would use such a tone of voice with a professional of the same level or higher, the conversation would be absolutely different. But newbie closes his eyes on it. He just keeps all the feelings inside. It won’t lead to anything good.</p><h3>5. Give your Juniors not only routine tasks</h3><p>You can’t improve your skills just by doing the same tasks over and over again. Yes, it’s very convenient to pass boring tasks to someone else. But you shouldn’t treat newbies as your slaves. Junior has to train thinking. He needs challenges.</p><p>Try to mix in interesting tasks to routine. Remember, things which are boring to you, might be something new for junior. It’s important to keep tasks diverse. Education will go faster that way.</p><h3>6. Give not only negative feedback</h3><p>Remember, there are two tools. Often people miss the second one: positive feedback. Though there’s no universal approach for every person. But usually, everybody likes to get praise. And it can be a great stimulus.</p><p>Mentors who are just started to train people often focus attention on mistakes only. And never say or point out where newbie was good at.</p><p>Everything should be in balance. Feedback should be objective and balanced as well.</p><h3>7. Let them make mistakes</h3><p>We learn because of mistakes. When Junior argues with you, you shouldn’t take it personally. If you feel annoyed — it’s your ego.</p><p>You shouldn’t just say “Do like this”, without any explanation why — newbie won’t learning anything from that.</p><p>Shut your ego down somewhere. Let newbie check his hypothesis or idea. Then he’ll have a perfect example to learn from. You can go through every mistake and objectively tell what exactly was wrong, why, and how to do it right.</p><p>Junior will compare “before” and “after”, make conclusions. You’ll see how faster they grow with such an approach.</p><p>Let’s wrap it up.</p><p>Education —<em> </em><strong><em>is not an easy task</em></strong>. Management should take into account that it’ll consume a lot of your mentor’s time, so workload should be adjusted accordingly. It should be a part of a company’s processes.</p><p><strong>Not everyone can teach</strong>. Assign a mentor role only to those who want it and who’s able to.</p><p><strong>Juniors are also humans</strong>. They’re so unconfident. You should not take advantage of your status and cultivate complexes in them. Remember yourself in their place and give all support their need.</p><p>The hiring of juniors is beneficial <strong>only if the education process goes fast and effective</strong>. Interaction and communication with juniors is different than with colleagues of your level. You should keep it in mind and follow the tips.</p><p>If you have a person in your company that fits the role of a mentor, give him or her an opportunity. <strong>It’s definitely worth it.</strong></p><p>If you like the article, give it some claps 👏, and subscribe for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122e9f99ac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Правильно ли вы растите своих джунов?]]></title>
            <link>https://medium.com/gamedev-architecture/are-you-growing-your-juniors-right-ru-c8b4117557f7?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8b4117557f7</guid>
            <category><![CDATA[soft-skills]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[management]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 23:01:58 GMT</pubDate>
            <atom:updated>2020-04-12T23:01:58.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*KbI_evzcBCsk1eTDzYxbfg.png" /></figure><p>У меня есть ученик. В начале его пути я помогал ему постичь наше ремесло, потом он попал в одну крупную компанию. Что с ним там сделали, вы не поверите…</p><p>А <strong>ничего</strong>! Буквально— ничего! В том то и дело.</p><p>Когда мой ученик рассказал о том, что происходит у него на работе, я не смог больше терпеть, и решился на эту статью. Вдруг получится помочь хоть нескольким людям.</p><p>Рассмотрим пару проблем. Подобные ситуации возникают не только в нашей индустрии. Вы их можете найти в любом месте, где нанимают стажеров/новичков.</p><h3>Проблема №1: Джуном никто не занимается</h3><p>Джун до этого работал в другой сфере, и на этот свитч карьеры решался долго. Он учился в свободное от работы время. Потом поставил на кон все, уволился со старой работы и несколько месяцев продолжал учиться нон-стоп, существуя на накопленные средства. И наконец-то получил свою первую работу программистом с окладом, значительно меньшим, чем у него был до этого.</p><p>В течение года наставники кураторы Джуна постоянно менялись. Его тупо перекидывали от одного к другому, никто не хотел им заниматься.</p><p>Никаких внятных задач ему не давали. Скидывали какое-то непонятное говно, с которым никто не хотел возиться.</p><p>Потом и говнозадачи кончились. Сказали сиди там читай что-нибудь, развивайся сам.</p><p>Затем ему дали разбираться с продуктом, который ну очень специфический. Опыт работы с ним практически никак не котируется на рынке труда. При этом, ни у кого другого не было ни опыта ни желания заниматься такой фигней. То есть Джуну даже не к кому было обратиться за помощью.</p><p>Это было первое место работы в качестве программиста, и оценить, нормальна такая ситуация или нет — он не мог. Джун боялся, что если не разберется, то его уволят. Вся эта история психологически угнетала, было ощущение, что время уходит зря, а он бессилен что-либо сделать.</p><p>Он поделился этим со мной, и я рекомендовал сменить место работы. Что он и сделал.</p><h3>Проблема №2: Джуном занимается тот, кто не умеет учить, или не хочет этим заниматься</h3><p>На новом месте работы джуну понравилось больше. Там назначили конкретного ментора, который ставил нормальные задачи, следил за их исполнением, немножко учил. Джун начал прокачиваться.</p><p>Спустя пару месяцев, иногда ментор начинал вести себя странно. В такие моменты появлялось ощущение какой-то личной неприязни, или что-то вроде того.</p><p>Просто посмотрите на пример диалога ниже.</p><ul><li>Джун: М, на счёт задачи XXX-413, Вы написали “Переделать: отображение диалога реализовать в классе действия RestoreDbAction” — я что-то не понял, в каком смысле “реализовать”? я сейчас сделал так, что вызывается RestoreDbAction.Confirm вместо IDialogDisplay.Show, но всё остальное получается оставляю как было, или я чего-то не понял?</li><li>Ментор: До тебя долго доходит. Понял наконец?</li><li>Джун: … я сейчас всё правильно понял?</li><li>Ментор: Что?</li><li>Джун: просто надо было использовать Confirm от Action?</li><li>Ментор: Конечно</li><li>Ментор: Почему сразу не догадался? Ещё вопросы?</li><li>Ментор: Как я и думал, Д, ты опять ничего не понял. Я просто удивляюсь твоей несообразительности….. (sad) Задачу вернул на доработку</li><li>Джун: я же спрашивал, правильно ли я понял</li><li>Ментор: я тоже спрашивал. 3 раза. И все равно ты понял неправильно</li></ul><h3>Зачем компании джуны?</h3><p>Давайте разберемся, в чем смысл растить джунов?</p><p>Джун — это вклад в будущее. Долгосрочный проект, если хотите.</p><p>Компания дает знания и опыт, а начинающий специалист со временем начинает возвращать инвестиции в виде выполненных задач. Получается такой выгодный симбиоз.</p><p>Джун с огоньком в глазах готов писать код просто потому, что это интересно и прикольно. А если за это еще и деньги платят — тем более.</p><p>Чем быстрее Джун начнет выполнять реальные задачи, приносить пользу, тем выгоднее это для компании.</p><p>Стартапы редко берут джунов. Ведь им нужно, чтобы отдача от разработчика была моментальной. Для стартапа, главное — скорость. Большие компании — другое дело. Они могут позволить себе не спешить. {: .notice — info}</p><p>Для работодателя существует две веских причины растить джунов:</p><ol><li><strong>Дешевая рабочая сила</strong>: они не просят много денег. А если джуна прокачали быстро, то за малые деньги компания получит неплохого специалиста, заточенного именно под ее процессы.</li><li><strong>Предсказуемый источник хороших кадров</strong>. Найм — всегда гемор. Поиск миддла может занять много времени и сил. Даже если кандидат идеально прошел собеседование, предсказать как он покажет себя в работе — невозможно. В случае ошибки компания терпит убытки.</li></ol><p>Вместо этого можно нанять пачку джунов. И вероятность найти подходящий кадр выше. Хороший работодатель заметит джунов, выросших в уровне, даст повышение и стимулирует развитие дальше.</p><p>При этом компания получает нового прокачанного разраба, с известной производительностью, знакомого с процессами и так далее. Ситуация win-win.</p><p>Если такой формат поставлен на поток, то компания может довольно стабильно расти.</p><h3>Несколько простых советов по воспитанию джунов</h3><h3>1. Не берите джунов, если ими некому заниматься</h3><p>Что можно извлечь из описания проблемы №1? Компания наняла джуна, но при этом им никто нормально не занимался. Он хотел учиться, и цеплялся за любую возможность.</p><p>Но работодателю было явно не до младших разрабов. Джун просто сидел на окладе, не принося компании выгоды, и не прокачивался сам. Ситуация lose-lose.</p><p>Джуны требуют постоянного надзора. Они как дети, которые пробуют ходить. Вначале у них это совсем не получается, но с каждым разом справляются все лучше. Однажды они начинают довольно уверено ходить и почти не требуют присмотра.</p><p>Что будет с ребенком, если его оставить одного? Наверняка случится что-то плохое. Поранится, уползет куда-нибудь не туда, что-нибудь сломает. Так случилось и в описанном случае.</p><p>Начальный этап взращивания джуна — самый сложный. Он требует приличных затрат времени и моральных сил. Нужно понимать, что тот, кто менторит — будет работать медленнее. Но в долгосрочной перспективе все окупится.</p><p>Если вы не готовы пойти на такие затраты, то не надо брать джунов. Не тратьте ресурсы компании зря, уважайте время людей.</p><p>С проблемой №1 покончено. Перейдем к проблеме №2.</p><h3>2. Не надо перекладывать ответственность</h3><p>В диалоге из проблемы №2 не прав именно ментор. Джун недостаточно квалифицирован, чтобы формализовать задачу, выяснить недостающие требования, спроектировать хорошее решение и так далее.</p><p>То, что Джун неправильно понял задачу — полностью вина ментора. Но он, вместо того, чтобы исправить положение, сложил вину с себя.</p><h3>3. Ставьте Джуну максимально подробные задачи</h3><p>Задача ментора максимально подробно разжевать задачу. Можно подтолкнуть в правильном направлении, но не нужно из этого устраивать шоу “Интуиция”. От этого никто не выиграет. Со временем Джун сам научится задавать правильные вопросы.</p><p>Решение задачи не нужно рассказывать сразу, но постановка должна быть достаточно подробной, чтобы не было вероятности неправильной трактовки.</p><p>Если есть сомнения, еще раз поговорите с Джуном и убедитесь, что вы поняли друг друга верно. И да, лучше разговаривать голосом, а не в чате. Это сильно помогает.</p><h3>4. Не надо самоутверждаться за счет других</h3><p>Уффф, тут мое брюзжание будет долгим, потому что от таких примеров бомбит у меня знатно.</p><p>В приведенном диалоге ментор повел себя с Джуном очень грубо и непрофессионально. Я могу предположить следующее:</p><ol><li>У ментора личная неприязнь к Джуну. По одному диалогу сложно судить, но Джун сказал, что у него было именно такое ощущение в нескольких эпизодах. Стоит говорить о том, что это категорически неприемлемо?</li><li>Ментор не хочет заниматься менторством. Как бы глупо это не звучало. Не все хотят этим заниматься. Компания должна следить за тем, кто натаскивает джунов. Если человеку не нравится такой род деятельности, ничего хорошего из этого не выйдет.</li><li>У ментора трудности со своими задачами, а тут еще джун. Как бы тебе ни было трудно, не нужно переносить свои проблемы, эмоции на других. Как минимум — это непрофессионально, а просто по-человечески — это свинство.<br>Руководство должно понимать, что работа с джунами отнимает много времени, и делать на это скидку при формировании нагрузки ментора.</li><li>Ментору не дано учить. Хороший разработчик — не обязательно хороший учитель. Уметь подобрать правильные слова — многого стоит.<br>На какой результат рассчитывал ментор? Что Джун подумает, “Ой какой я несообразительный, буду над этим работать”?<br>Такие слова могут отбить всякую мотивацию напрочь. Могут зародить сомнения в себе, и потом люди рассказывают про синдром самозванца. Могут просто отбить желание задавать вопросы и общаться с коллегами, потому что будет страшно.<br>Но самое плохое, человек, который поставил на кон все, может просто опустить руки и отказаться от своей мечты.<br>Ничего, кроме тупого самоутверждения “ты — дурак, а я — звезда” тут нет.<br>Все мы были в начале пути. Вспомните, как с вами разговаривали коллеги? Поддерживали ли вас? Что вы чувствовали?</li></ol><p>Ни один из приведенных вариантов не может служить оправданием такого тона. Нельзя так разговаривать с вашими подчиненными, коллегами. Самоутверждаться и унижать других, пользуясь своим положением. Ни у кого нет такого права.</p><p>Если бы ментор так разговаривал с профессионалом своего уровня, то разговор получился бы совершенно другим. Новичок же все проглотит, будет держать в себе. Ни к чему хорошему это не приведет.</p><h3>5. Давайте Джунам не только рутинные задачи</h3><p>На одной рутине не прокачаешься. Да, простые задачи удобно скинуть с себя. Но не нужно воспринимать новичка, как своего раба. Джуну нужно тренировать мышление. Ему нужны сложные испытания.</p><p>Постарайтесь разбавлять скучную работу чем-нибудь интересным. Помните, то что для вас скучно, для новичка может быть впервой. Главное, чтобы задачи были разнообразными. Обучение будет проходить гораздо бодрее.</p><h3>6. Давайте не только негативную обратную связь</h3><p>Помните, кроме кнута есть еще и пряник. Не бывает универсального подхода для всех людей. Но все любят, когда их искренне хвалят. Такое поощрение может быть великим стимулом.</p><p>Начинающие менторы частенько концентрируют внимание только на ошибках, но совершенно не отмечают то, в чем новичок проявил себя хорошо.</p><p>Все хорошо в меру, поэтому между кнутом и пряником должен быть баланс.</p><h3>7. Давайте совершать ошибки</h3><p>Именно благодаря ошибкам мы учимся. Когда Джун оспаривает ваши слова, не нужно воспринимать это на свой счет. Если вы злитесь — в вас играет ваше эго.</p><p>Если говорить “делай вот так”, но не объяснять почему — новичок ничему не научится.</p><p>Уберите ваше самолюбие подальше. Дайте новичку проверить свою гипотезу, идею. Затем уже предметно, объективно, спокойно покажите в чем именно ошибка и как можно было бы сделать лучше.</p><p>Джун сравнит до/после, поразмыслит над аргументами и сделает выводы. Вот увидите, при таком подходе он будет расти гораздо быстрее.</p><p>Подведем итог. Воспитание джуна — непростое дело. Руководство должно учитывать, что это будет требовать много времени и распределять нагрузку на менторов соответственно. Это должно быть частью процессов компании.</p><p>Не все способны учить. Назначайте менторами тех, кто этого хочет, и кто способен на это.</p><p>Джуны — тоже люди. Они очень неуверены в себе. Не нужно пользоваться своим статусом и культивировать в них комплексы. Наоборот, вспомните себя и окажите нужную поддержку новичкам.</p><p>Найм джунов будет выгоден для компании только если этот процесс будет проходить быстро и эффективно. Общение с джунами отличается от общения с коллегами вашего уровня. Это нужно учитывать и следовать советам, которые я описал.</p><p>Если у вас в компании есть человек, подходящий на роль ментора, дайте ему возможность. Оно однозначного того стоит.</p><p>Если статья вам понравилась, подписывайтесь и жмите 👏.</p><p>Больше статей можно найти в моем блоге: <a href="http://fateev.pro/">http://fateev.pro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8b4117557f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/are-you-growing-your-juniors-right-ru-c8b4117557f7">Правильно ли вы растите своих джунов?</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoupling your game code via Command pattern, debugging it flying on the time machine]]></title>
            <link>https://medium.com/gamedev-architecture/decoupling-game-code-via-command-pattern-debugging-it-with-time-machine-2b177e61556c?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b177e61556c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 22:46:39 GMT</pubDate>
            <atom:updated>2018-06-13T22:47:57.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*TD4_4Xf9chdkOlaf.png" /></figure><p>Hi! I write articles dedicated to software architecture in game development. In this article I want to show the <a href="https://en.wikipedia.org/wiki/Command_pattern">Command</a> pattern. It’s absolutely flexible and may be applied in so many ways. But I will show you my favorite trick — time machine for debugging mutations of the game state.</p><p>This approach saves me so much time when I search for a source of bugs and try to reproduce them. It allows me to save “snapshots” of the game state, history of mutations, and apply these changes step by step.</p><p>Junior developers will get acquainted with the pattern, seasoned devs, perhaps will find this trick helpful.</p><p>Wanna know how do you do it? Welcome!</p><h3>Command Pattern</h3><p>What do we mean by the “Command” word? It’s something like an order. One, with the help of command, expresses they the need to perform some <strong>action</strong>. Action is inseparable from command.</p><p>Command pattern — is a way to represent <strong>the Action </strong>in an object-oriented programming (OOP) world. And only with the help of polymorphism it is possible.</p><p>An idea behind the pattern is that all commands are unified in the system. In terms of OOP, all commands have the same interface. System may transparently execute any of them. And this means that command have to absolutely independent, encapsulate all the data required for its execution.</p><p>So far description is pretty abstract, right? Let’s look into concrete examples.</p><p>Here’s the basic interface for all commands:</p><pre>public interface ICommand<br>{<br>    void Execute();<br>}</pre><p>Here’s an example of specific implementation of th ecommand:</p><pre>public class WriteToConsoleCommand : ICommand<br>{<br>    public string Message { get; private set; }<br>    public void Execute() {<br>        Console.WriteLine(Message);<br>    }<br>}</pre><p>It’s something like traditional “Hello world” using command. But how do you execute it? Let’s write a simple system for command execution.</p><pre>public interface IGameSystem<br>{<br>    void Execute(ICommand cmd);<br>}<br><br>public class LoggableGameSystem : IGameSystem<br>{<br>    public LoggableGameSystem(ILogger log)<br>    {<br>        _log = log;<br>    }<br><br>    public void Execute(ICommand cmd) {<br>        _log.Debug(string.Format(&quot;Executing command &lt;{0}&gt;: {1}&quot;, cmd.GetType(), cmd);<br>        cmd.Execute();<br>    }<br><br>    private ILogger _log;<br>}</pre><p>Now we can log any execution of the command for debugging purposes. Helpful, right? But command should be adapted for debugging output. Let’s add ToString() method.</p><pre>public class WriteToConsoleCommand : ICommand<br>{<br>    public string Message { get; private set; }<br>    public void Execute() {<br>        Console.WriteLine(Message);<br>    }<br><br>    public override string ToString()<br>    {<br>        return Message;<br>    }<br>}</pre><p>Let’s see how does it work:</p><pre>    class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            var gameSystem = new LoggableGameSystem();<br>            var cmd = new WriteToConsoleCommand(&quot;Hello world&quot;);<br>            var cmd2 = new WriteToConsoleCommand(&quot;Hello world2&quot;);<br>            gameSystem.Execute(cmd);<br>            gameSystem.Execute(cmd2);<br>        }<br>    }</pre><p>It’s a very basic example. Of course, debug output is a pretty helpful thing, but it’s still unclear what benefits you can get out of this approach.</p><p>In my projects I always use this pattern because of the following reasons:</p><ul><li>Command encapsulates (stores) everything required for its execution. It is in fact immutable object. Therefore it’s easy to pass this objects via network, and execute absolutely identically between client and server. Of course it’s only in case if client and server produce the same result if given the same input parameters.</li><li>Command represents pretty small piece of business logic. It’s easy to write, understand and debug. Since command is immutable, and doesn’t contain any extra dependencies, writing a unit test for the command is like a piece of cake.</li><li>Complex business logic may be expressed via set of simple commands. Commands are easily composable and reusable.</li><li>Command may represent a check-point, or transaction, if you like. If mutation of the state is done only via commands, it simplifies debugging and understanding of program flow. If something gone wrong, you always can track which command introduced the bug. What is helpful — you can see all the parameters command has been executed with.</li><li>Execution of commands may be deferred/asynchronous. Typical example — you send command to a server. When a user initiated any action in the game, command is created and appended to a queue for execution. In fact, command will be executed only after the server confirmed it and responded with success.</li><li>The code written using Command approach, slightly differs from traditional “call function” way. When developers create command instance, they express “intent” to do some action, and do not care when and how it will be executed. It allows one to make very interesting things.</li></ul><p>A bit more details about last point. For example, you have synchronous function, which should become asynchronous. In order to do that, you have to change its signature, and rewrite logic to handle asynchronous result in form of callback, or coroutine, or async/await (in case you’ve switched to .net 4.6 runtime). And you have to do that for every function you need to change.</p><p>Commands approach allows you to abstract from the execution mechanics. Therefore, if command has been synchronous before, it may be easily changed to asynchronous. It can even be done in runtime (which is impossible with traditional approach).</p><p>Let’s look into specific example. Some game should support “partial” offline mode. In case if internet connection is unavailable right now, then commands are appended to the queue, and will be delivered to the server for execution when the connection becomes available again. In case if connection is ok commands are sent instantly.</p><h3>Making a one-way game state modification</h3><p>What’s that “one-way game state modification” exactly? The idea is borrowed from the <a href="https://github.com/facebook/flux/tree/master/">Flux</a> approach, described by the Facebook. The same idea is behind modern libraries like <a href="https://redux.js.org/">Redux</a>.</p><p>In traditional MV* approaches, View interacts with a model in a two-way mode.</p><p>In Unity situation is even worse. Traditional MVC absolutely doesn’t fit here, and data is being mutated right from the View (I’ll show an example below). In complex apps, numbers of these dependencies is insane, update is missed inside another update, everything is messed, and you get a spaghetti.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*0iDfF3mXL2Sfmc_F" /><figcaption>(Source: <a href="https://medium.com/e-fever/revised-qml-application-architecture-guide-with-flux-a1de143fe13e">medium.com</a>)</figcaption></figure><p>Let’s experiment and come up with a system similar to the Redux, but in Unity. The main idea behind Redux is that application state is represented by the single object. In other words, in a single model.</p><p>Some people may be terrified at this point. But serialization of the game state often comes down to serialization of the single object. It’s a natural way for games.</p><p>The second idea is that mutation of the game state is done using <strong>Actions.</strong> In fact Actions are the same as Commands. View can not modify state directly, only using command.</p><p>The third idea — natural continuation of the previous one. View only <strong>reads </strong>the game state and subscribe to its updates.</p><p>Here’s what it looks like in Flux:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*anvCUT5O8-vxGDXP" /><figcaption>(Source: <a href="https://medium.com/e-fever/revised-qml-application-architecture-guide-with-flux-a1de143fe13e">medium.com</a>)</figcaption></figure><p>In our case:</p><ul><li>Store = game state</li><li>Action = Command</li><li>Dispatcher = something that executes commands</li></ul><p>Such approach will give you a bunch of benefits. Since there’s only one a single game state object, and it’s mutated only using commands, then it’s easy and natural <strong>to create a single event of game state update.</strong></p><p>Then UI may be easily switched to the reactive approach. In other words, automatically update UI components when the game state changes (hi <a href="https://github.com/neuecc/UniRx">UniRx</a>! we’ll discuss it in other article).</p><p>Such approach also allows you initiate game state mutation from the server side, the same way: using commands. Since game state update event is the same, then UI is absolutely indifferent where it came from.</p><p>Another great benefit — cool features for debugging. Since View can only send commands, you can track all changes produced by the app like a piece of cake.</p><p>Detailed logging, commands history, bugs reproducing etc. — all that is possible due to this approach.</p><h3>Implementation</h3><p>First, let’s decide what our game state will look like. May it be the following class:</p><pre>    [System.Serializable]<br>    public class GameState<br>    {<br>        public int coins;<br>    }</pre><p>Let’s add game state serialization to the JSON file. I’ll introduce a dedicated manager class for that.</p><pre>public interface IGameStateManager<br>{<br>    GameState GameState { get; set; }<br>    void Load();<br>    void Save();<br>}</pre><pre>public class LocalGameStateManager : IGameStateManager<br>{<br>    public GameState GameState { get; set; }</pre><pre>    public void Load()<br>    {<br>        if (!File.Exists(GAME_STATE_PATH))<br>        {<br>            return;<br>        }<br>        GameState = JsonUtility.FromJson&lt;GameState&gt;(File.ReadAllText(GAME_STATE_PATH));<br>    }</pre><pre>    public void Save()<br>    {<br>        File.WriteAllText(GAME_STATE_PATH, JsonUtility.ToJson(GameState));<br>    }</pre><pre>    private static readonly string GAME_STATE_PATH = Path.Combine(Application.persistentDataPath, &quot;gameState.json&quot;); }</pre><p>Let’s use Dependency Injection library <a href="https://github.com/modesttree/Zenject">Zenject</a> to manage our dependencies wisely. Its installation and setup are pretty trivial and documented well.</p><p>I declare binding for the IGameStateManager.</p><p>I created my class of MonoInstaller called BindingsInstaller, according to documentation, and added it to the scene.</p><pre>public class BindingsInstaller : MonoInstaller&lt;BindingsInstaller&gt;<br>{<br>    public override void InstallBindings()<br>    {<br>        Container.Bind&lt;IGameStateManager&gt;().To&lt;LocalGameStateManager&gt;().AsSingle();<br>        Container.Bind&lt;Loader&gt;().FromNewComponentOnNewGameObject().NonLazy();<br>    }</pre><p>Also I add binding for a Loader component, which will handle loading and exit from the game.</p><pre>public class Loader : MonoBehaviour {</pre><pre>    [Inject]<br>    public void Init(IGameStateManager gameStateManager)<br>    {<br>        _gameStateManager = gameStateManager;<br>    }</pre><pre>    private void Awake()<br>    {<br>        Debug.Log(&quot;Loading started&quot;);<br>        _gameStateManager.Load();<br>    }</pre><pre>    private void OnApplicationQuit()<br>    {<br>        Debug.Log(&quot;Quitting application&quot;);<br>        _gameStateManager.Save();<br>    }</pre><pre>    private IGameStateManager _gameStateManager;<br>}</pre><p>Script Loader starts the first in the game. I use it as a starting point and as a script which handles loading/saving of the game state.</p><p>Now I create simplest View for the UI.</p><pre>public class CoinsView : MonoBehaviour<br>{<br>    public Text currencyText;</pre><pre>    [Inject]<br>    public void Init(IGameStateManager gameStateManager)<br>    {<br>        _gameStateManager = gameStateManager;<br>        UpdateView();<br>    }</pre><pre>    public void AddCoins()<br>    {<br>        _gameStateManager.GameState.coins += Random.Range(1,100);<br>        UpdateView();<br>    }</pre><pre>    public void RemoveCoins()<br>    {<br>        _gameStateManager.GameState.coins -= Random.Range(1,100);<br>        UpdateView();<br>    }</pre><pre>    public void UpdateView()<br>    {<br>        currencyText.text = &quot;Coins: &quot; + _gameStateManager.GameState.coins;<br>    }</pre><pre>    private IGameStateManager _gameStateManager;<br>}</pre><p>I added two methods there, to add and remove coins. Standard approach which I often see — place a business logic right in the view.</p><p>You shouldn’t do that way. But for now we should ensure that our prototype is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Du2ElcWjTv3n34P0.png" /></figure><p>Buttons are working, the game state is being saved and loaded upon game start.</p><p>We’ve made it working. Let’s make it right.</p><p>I create a separate type for commands which mutate the GameState.</p><pre>public interface ICommand<br>{</pre><pre>}<br>public interface IGameStateCommand : ICommand<br>{<br>    void Execute(GameState gameState);<br>}</pre><p>Common interface is empty to express a single shared type for commands. For specific commands which mutate the game state there’s an Execute method which takes GameState as an argument.</p><p>Now I create a service which will execute commands of type IGameStateCommand like the one I showed before. Interface will be generic to fit every type of command.</p><pre>public interface ICommandsExecutor&lt;TCommand&gt;<br>    where TCommand: ICommand<br>{<br>    void Execute(TCommand command);<br>}</pre><pre>public class GameStateCommandsExecutor : ICommandsExecutor&lt;IGameStateCommand&gt;<br>{</pre><pre>    public GameStateCommandsExecutor(IGameStateManager gameStateManager)<br>    {<br>        _gameStateManager = gameStateManager;<br>    }</pre><pre>    public void Execute(IGameStateCommand command)<br>    {<br>        command.Execute(_gameStateManager.GameState);<br>    }</pre><pre>    private readonly IGameStateManager _gameStateManager;<br>}</pre><p>Here’s how I register it in DI.</p><pre>public class BindingsInstaller : MonoInstaller&lt;BindingsInstaller&gt;<br>{<br>    public override void InstallBindings()<br>    {<br>        Container.Bind&lt;IGameStateManager&gt;().To&lt;LocalGameStateManager&gt;().AsSingle();<br>        Container.Bind&lt;Loader&gt;().FromNewComponentOnNewGameObject().AsSingle().NonLazy();</pre><pre>        // added this line<br>        Container.Bind&lt;ICommandsExecutor&lt;IGameStateCommand&gt;&gt;().To&lt;GameStateCommandsExecutor&gt;().AsSingle();<br>    }<br>}</pre><p>Now I implement concrete command which mutates coins value.</p><pre>public class AddCoinsCommand : IGameStateCommand<br>{<br>    public AddCoinsCommand(int amount)<br>    {<br>        _amount = amount;<br>    }</pre><pre>    public void Execute(GameState gameState)<br>    {<br>        gameState.coins += _amount;<br>    }</pre><pre>    private int _amount;<br>}</pre><p>Update CoinsView to use AddCoinsCommand instead of the direct modification.</p><pre>public class CoinsView : MonoBehaviour<br>{<br>    public Text currencyText;</pre><pre>    [Inject]<br>    public void Init(IGameStateManager gameStateManager, ICommandsExecutor&lt;IGameStateCommand&gt; commandsExecutor)<br>    {<br>        _gameStateManager = gameStateManager;<br>        _commandsExecutor = commandsExecutor;<br>        UpdateView();<br>    }</pre><pre>    public void AddCoins()<br>    {<br>        var cmd = new AddCoinsCommand(Random.Range(1, 100));<br>        _commandsExecutor.Execute(cmd);<br>        UpdateView();<br>    }</pre><pre>    public void RemoveCoins()<br>    {<br>        var cmd = new AddCoinsCommand(-Random.Range(1, 100));<br>        _commandsExecutor.Execute(cmd);<br>        UpdateView();<br>    }</pre><pre>    public void UpdateView()<br>    {<br>        currencyText.text = &quot;Coins: &quot; + _gameStateManager.GameState.coins;<br>    }</pre><pre>    private IGameStateManager _gameStateManager;<br>    private ICommandsExecutor&lt;IGameStateCommand&gt; _commandsExecutor;<br>}</pre><p>Now CoinsView <strong>only reads GameState.</strong> All mutations are made using commands.</p><p>What looks dirty here is a manual call of the UpdateView. We may forget it. Or the GameState may be changed by command from another View.</p><p>Let’s add an event of GameState update in ICommandExecutor. Also let’s create a separate alias-interface IGameStateCommandsExecutor, in order to hide extra types of generic interface.</p><pre>public interface ICommandsExecutor&lt;TState, TCommand&gt;<br>{<br>    // added event<br>    event System.Action&lt;TState&gt; stateUpdated;<br>    void Execute(TCommand command);<br>}<br>public interface IGameStateCommandsExecutor : ICommandsExecutor&lt;GameState, IGameStateCommand&gt;<br>{</pre><pre>}</pre><p>Now I need to update registration in DI.</p><pre>public class BindingsInstaller : MonoInstaller&lt;BindingsInstaller&gt;<br>{<br>    public override void InstallBindings()<br>    {<br>        Container.Bind&lt;IGameStateManager&gt;().To&lt;LocalGameStateManager&gt;().AsSingle();<br>        Container.Bind&lt;Loader&gt;().FromNewComponentOnNewGameObject().AsSingle().NonLazy();<br>        // updated this line<br><strong>        Container.Bind&lt;IGameStateCommandsExecutor&gt;()<br></strong>                                            .To&lt;DefaultCommandsExecutor&gt;().AsSingle();<br>    }<br>}</pre><p>Let’s add an event to theDefaultCommandsExecutor.</p><pre>public class DefaultCommandsExecutor : IGameStateCommandsExecutor<br>{<br>    // this event added<br>   <strong> public event Action&lt;GameState&gt; stateUpdated<br>    {<br>        add<br>        {<br>            _stateUpdated += value;<br>            if (value != null)<br>            {<br>                value(_gameStateManager.GameState);<br>            }<br>        }<br>        remove<br>        {<br>            _stateUpdated -= value;<br>        }<br>    }</strong></pre><pre>    public DefaultCommandsExecutor(IGameStateManager gameStateManager)<br>    {<br>        _gameStateManager = gameStateManager;<br>    }</pre><pre>    public void Execute(IGameStateCommand command)<br>    {<br>        command.Execute(_gameStateManager.GameState);<br>        // these lines added<br>        if (_stateUpdate != null)<br>        {<br>            _stateUpdated(_gameStateManager.GameState);<br>        }<br>    }</pre><pre>    private readonly IGameStateManager _gameStateManager;<br>    // this line added<br>    private Action&lt;GameState&gt; _stateUpdated;</pre><pre>}</pre><p>It’s worth to pay attention to implementation of the event. Since executor is sharing the game state only inside the event, it’s important to invoke it right after the subscription.</p><p>Finally, update the View.</p><pre>public class CoinsView : MonoBehaviour<br>{<br>    public Text currencyText;</pre><pre>    [Inject]<br>    public void Init(IGameStateCommandsExecutor commandsExecutor)<br>    {<br>        _commandsExecutor = commandsExecutor;<br><strong>        _commandsExecutor.stateUpdated += UpdateView;<br></strong>    }</pre><pre>    public void AddCoins()<br>    {<br>        var cmd = new AddCoinsCommand(Random.Range(1, 100));<br>        _commandsExecutor.Execute(cmd);<br>    }</pre><pre>    public void RemoveCoins()<br>    {<br>        var cmd = new AddCoinsCommand(-Random.Range(1, 100));<br>        _commandsExecutor.Execute(cmd);<br>    }</pre><pre>    public void UpdateView(GameState gameState)<br>    {<br>        currencyText.text = &quot;Coins: &quot; + gameState.coins;<br>    }</pre><pre>    private void OnDestroy()<br>    {<br><strong>        _commandsExecutor.stateUpdated -= UpdateView;<br></strong>    }</pre><pre>    private IGameStateCommandsExecutor _commandsExecutor;<br>}</pre><p>View doesn’t needIGameStateManager now, since UpdateView takes GameState as an argument. Excellent, we’ve got rid of extra dependency! UpdateView itself I’ve subscribed to the event in IGameStateCommandsExecutor. It’ll be invoked every time GameState changes. Also it’s important to unsubscribe from the event in OnDestroy.</p><p>That’s it. Pretty clean and straightforward approach. Now it’s impossible forget to invoke UpdateView in some place, in some who-the-hell-knows condition, which reproduces only in certain phase of the moon.</p><p>Nice, you may take a break, then we’ll move forward. There are few more benefits.</p><h3>Using commands history as a time machine for debugging a complex business logic.</h3><p>How do you reproduce bugs? You launch the app and follow repro steps. Often these steps are performed manually. Walking from screen to screen, hitting buttons, etc.</p><p>It’s ok if the bug is simple or repro steps are easy. But what if the bug depends on network logic and time. For instance, there’s a game event, which runs for 10 minutes. Bug occurs at the end of the event.</p><p>Every iteration of testing will take 10 minutes minimum. Usually you need at least several iterations, and between them you fix something.</p><p>I’ll show an interesting approach which utilizes all we’ve done so far, and which will save you from the headache.</p><p>There’s an obvious bug in the code from previous example. Number of coins can not be negative. Of course, the case is not so difficult, but I hope you have a good imagination.</p><p>Imagine, that business logic is complex, and it’s really hard to reproduce a bug every time. But at some point, you or your QA mate stumbled on the bug. What if you could “save” that bug?</p><blockquote><em>Now the trick: save the initial game state you had on game start, and heep a history of all the commands that have been applied to it during a game session.</em></blockquote><p>That data is enough to reproduce the bug as many times as you may need, for the matter of milliseconds. At the same time there’s no need to launch UI at all, since all modifications of the broken game state are stored in commands history. It’s like a small integration test-case.</p><p>Now, let’s move to the implementation. Since this approach required more advanced serialization than Unity’s JsonUtility may provide, I’ll install Json.Net for Unity from the Asset Store.</p><p>First, let’s create a debug version of the IGameStateManager, which clones initial game state to the separate file.</p><pre>public class DebugGameStateManager : LocalGameStateManager<br>{<br>    public override void Load()<br>    {<br>        base.Load();<br>        File.WriteAllText(BACKUP_GAMESTATE_PATH, JsonUtility.ToJson(GameState));<br>    }</pre><pre>    public void SaveBackupAs(string name)<br>    {<br>        File.Copy(<br>            Path.Combine(Application.persistentDataPath, &quot;gameStateBackup.json&quot;),<br>            Path.Combine(Application.persistentDataPath, name + &quot;.json&quot;), true);<br>    }</pre><pre>    public void RestoreBackupState(string name)<br>    {<br>        var path = Path.Combine(Application.persistentDataPath, name + &quot;.json&quot;);<br>        Debug.Log(&quot;Restoring state from &quot; + path);<br>        GameState = JsonUtility.FromJson&lt;GameState&gt;(File.ReadAllText(path));<br>    }</pre><pre>    private static readonly string BACKUP_GAMESTATE_PATH<br>                            = Path.Combine(Application.persistentDataPath, &quot;gameStateBackup.json&quot;);</pre><pre>}</pre><p>Behind the scenes I’ve left the change of parent’s methods to virtual ones. It will be an exercise for you. Also there’s a SaveBackupAs methods which we’ll be used later, so we can save our “Snapshots” with a specific name.</p><p>Now let’s create a debug version of executor, which can store everything we need to “replay” a bug.</p><pre>public class DebugCommandsExecutor : DefaultCommandsExecutor<br>{<br>    public IList&lt;IGameStateCommand&gt; commandsHistory { get { return _commands; } }<br>    public DebugCommandsExecutor(DebugGameStateManager gameStateManager)<br>        : base(gameStateManager)<br>    {<br>        _debugGameStateManager = gameStateManager;<br>    }</pre><pre>    public void SaveReplay(string name)<br>    {<br>        _debugGameStateManager.SaveBackupAs(name);<br>        File.WriteAllText(GetReplayFile(name),<br>                            JsonConvert.SerializeObject(new CommandsHistory { commands = _commands },<br>                                                        _jsonSettings));<br>    }</pre><pre>    public void LoadReplay(string name)<br>    {<br>        _debugGameStateManager.RestoreBackupState(name);<br>        _commands = JsonConvert.DeserializeObject&lt;CommandsHistory&gt;(<br>                        File.ReadAllText(GetReplayFile(name)),<br>                        _jsonSettings<br>                    ).commands;<br>        _stateUpdated(_gameStateManager.GameState);<br>    }</pre><pre>    public void Replay(string name, int toIndex)<br>    {<br>        _debugGameStateManager.RestoreBackupState(name);<br>        LoadReplay(name);<br>        var history = _commands;<br>        _commands = new List&lt;IGameStateCommand&gt;();<br>        for (int i = 0; i &lt; Math.Min(toIndex, history.Count); ++i)<br>        {<br>            Execute(history[i]);<br>        }<br>        _commands = history;<br>    }</pre><pre>    private string GetReplayFile(string name)<br>    {<br>        return  Path.Combine(Application.persistentDataPath, name + &quot;_commands.json&quot;);<br>    }</pre><pre>    public override void Execute(IGameStateCommand command)<br>    {<br>        _commands.Add(command);<br>        base.Execute(command);<br>    }</pre><pre>    private List&lt;IGameStateCommand&gt; _commands = new List&lt;IGameStateCommand&gt;();</pre><pre>    public class CommandsHistory<br>    {<br>        public List&lt;IGameStateCommand&gt; commands;<br>    }</pre><pre>    private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings() {<br>        TypeNameHandling = TypeNameHandling.All<br>    };<br>    private readonly DebugGameStateManager _debugGameStateManager;<br>}</pre><p>Here you can see that JsonUtility couldn’t handle it. I had to specify TypeNameHandling for serialization settings, so during load/save of the snapshot, commands are a typed objects, because the business logic is tied to the type.</p><p>What are other interesting points about this executor?</p><ul><li>Svaes every command to the history</li><li>Can save and restore both commands history and state</li><li>Key method Replay — replays all the commands, applying them to the initial state until command with target index is reached.</li></ul><p>I wouldn’t want to waste the memory on debug stuff in release project, thus I register debug service only if there’s #DEBUG define.</p><pre>public class BindingsInstaller : MonoInstaller&lt;BindingsInstaller&gt;<br>{<br>    public override void InstallBindings()<br>    {<br>        Container.Bind&lt;Loader&gt;().FromNewComponentOnNewGameObject().AsSingle().NonLazy();<br>    #if DEBUG<br>        Container.Bind&lt;IGameStateManager&gt;().To&lt;DebugGameStateManager&gt;().AsSingle();<br>        Container.Bind&lt;DebugGameStateManager&gt;().AsSingle();<br>        Container.Bind&lt;IGameStateCommandsExecutor&gt;().To&lt;DebugCommandsExecutor&gt;().AsSingle();<br>    #else<br>        Container.Bind&lt;IGameStateManager&gt;().To&lt;LocalGameStateManager&gt;().AsSingle();<br>        Container.Bind&lt;IGameStateCommandsExecutor&gt;().To&lt;DefaultCommandsExecutor&gt;().AsSingle();<br>    #endif<br>    }<br>}</pre><p>Ah, we need to prepare a command for serialization:</p><pre>public class AddCoinsCommand : IGameStateCommand<br>{</pre><pre>    public AddCoinsCommand(int amount)<br>    {<br>        _amount = amount;<br>    }</pre><pre>    public void Execute(GameState gameState)<br>    {<br>        gameState.coins += _amount;<br>    }</pre><pre>    public override string ToString() {<br>        return GetType().ToString() + &quot; &quot; + _amount;<br>    }</pre><pre>    [JsonProperty(&quot;amount&quot;)]<br>    private int _amount;<br>}</pre><p>Here I’ve added JsonProperty, since _amount property is private and will not be serialized by default. Also I’ve overrided ToString(), so the command may be logged nicely.</p><p>In order to get debug version working, do not forget ot add “DEBUG” define in Player Settings -&gt; Other Settings -&gt; Scripting define symbols.</p><p>Then I want to have a way to save and load the history of commands and state right from Unity’s UI. Let’s create a custom EditorWindow.</p><pre>public class CommandsHistoryWindow : EditorWindow<br>{</pre><pre>    [MenuItem(&quot;Window/CommandsHistoryWindow&quot;)]<br>    public static CommandsHistoryWindow GetOrCreateWindow()<br>    {<br>        var window = EditorWindow.GetWindow&lt;CommandsHistoryWindow&gt;();<br>        window.titleContent = new GUIContent(&quot;CommandsHistoryWindow&quot;);<br>        return window;<br>    }</pre><pre>    public void OnGUI()<br>    {</pre><pre>        // this part is required to get<br>        // DI context of the scene<br>        var sceneContext = GameObject.FindObjectOfType&lt;SceneContext&gt;();<br>        if (sceneContext == null || sceneContext.Container == null)<br>        {<br>            return;<br>        }<br>        // this guard ensures that OnGUI runs only when IGameStateCommandExecutor exists<br>        // in other words only in runtime<br>        var executor = sceneContext.Container.TryResolve&lt;IGameStateCommandsExecutor&gt;() as DebugCommandsExecutor;<br>        if (executor == null)<br>        {<br>            return;<br>        }</pre><pre>        // general buttons to load and save &quot;snapshot&quot;<br>        EditorGUILayout.BeginHorizontal();<br>        _replayName = EditorGUILayout.TextField(&quot;Replay name&quot;, _replayName);<br>        if (GUILayout.Button(&quot;Save&quot;))<br>        {<br>            executor.SaveReplay(_replayName);<br>        }<br>        if (GUILayout.Button(&quot;Load&quot;))<br>        {<br>            executor.LoadReplay(_replayName);<br>        }<br>        EditorGUILayout.EndHorizontal();</pre><pre>        // and the main block which allows us to walk through commands step by step<br>        EditorGUILayout.LabelField(&quot;Commands: &quot; + executor.commandsHistory.Count);<br>        for (int i = 0; i &lt; executor.commandsHistory.Count; ++i)<br>        {<br>            var cmd = executor.commandsHistory[i];<br>            EditorGUILayout.BeginHorizontal();<br>            EditorGUILayout.LabelField(cmd.ToString());<br>            if (GUILayout.Button(&quot;Step to&quot;))<br>            {<br>                executor.Replay(_replayName, i + 1);<br>            }<br>            EditorGUILayout.EndHorizontal();</pre><pre>        }<br>    }</pre><pre>    private string _replayName;<br>}</pre><p>That’s it. Pretty simple. What does it look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/0*R_2eL12xwq9t1Zql.gif" /></figure><p>I’ve saved empty “initial” sate, so I could get back to it in case of something went wrong. Then I’ve hit the buttons couple of times, coins counter has changed. Also you may see a list of commands applied to the game state.</p><p>Then I’ve saved final snapshot with a name “version1”.</p><p>Then I use “Step to” buttons to “replay” all mutations until specific command.</p><p>Now let’s get back to the bug with negative coin values. May testers accidentally stumbled on the bug. I’ve shared the “Save snapshot” button only in Unity, but it may be implemented right in the game UI. In such case the tester may specify a snapshot name “negativeCoins” and then hit “Save” button.</p><p>Then they browse to “saves” folder and found two files: negativeCoins.json and negativeCoins_commands.json.</p><p>Then they send it to developers. Developers puts those files to the same folder on his machine. In debug window they put “negativeCoins” name, hit Load button and voila. They have a perfect test-case in their hands.</p><p>Moreover, you can create an empty scene, without any UI, in which you may “replay” game state snapshots only. This may save your time dramatically.</p><p>You may even build an integration process around this approach. For instance, keep a list of “snapshots” which should be tested on every build.</p><p>Ok, let’s stop our fantasy. Let’s fix the bug.</p><pre>public class AddCoinsCommand : IGameStateCommand<br>{</pre><pre>    public AddCoinsCommand(int amount)<br>    {<br>        _amount = amount;<br>    }</pre><pre>    public void Execute(GameState gameState)<br>    {<br>        gameState.coins += _amount;<br>        // this is the fix<br>        if (gameState.coins &lt; 0)<br>        {<br>            gameState.coins = 0;<br>        }<br>    }</pre><pre>    public override string ToString() {<br>        return GetType().ToString() + &quot; &quot; + _amount;<br>    }</pre><pre>    [JsonProperty(&quot;amount&quot;)]<br>    private int _amount;<br>}</pre><p>Let’s check it out on our snapshot, we’ve saved before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IEQ-0CHFvxrhFNG9.gif" /></figure><p>As you see, can not be negative anymore. Win!</p><h3>Summary</h3><p>In this article I’ve shared my vision of Command pattern. I believe there are so much ways to apply it. I’ve showed only few out of the bunch I’m using.</p><p>In next articles I plan to share more ways to use commands:</p><ul><li>communication with game server using commands</li><li>basic logic of command handling between client and server</li></ul><p>Also I’ve slightly touched painful UI topic, Flux approach, and reactive approach.</p><p>I’ve showed the interesting way of debugging, which may seem as time machine, when you literally replay game state mutations like in debugger.</p><p>Combining these patterns, we’ve got a flexible architecture, which is easy to support, refactor and debug. Of course many things may be improved. But it’s up to you.</p><p>Also I want to point out that in this case reactive approach in UI and Command pattern dramatically decoupled the system. When I added debug versions of executor and GameStateManager, I literally changed nothing.</p><p>UI is a pretty broad topic to cover, and there will be a separate article for that.</p><p>Source code you may find <a href="https://github.com/PoisonousJohn/articles/tree/master/Telegram_Posts/decoupling-via-commands/Patterns">in this repository</a>.</p><p>If you like the article, do not forget to show it with claps, or write your thoughts in comments :)</p><p>Subscribe and don’t miss new content.</p><p>My contacts:</p><ul><li><a href="https://t.me/gamedev_architecture">My channel about GameDev Architecture</a> (Russian)</li><li><a href="https://t.me/poisonous_john">Telegram</a></li><li><a href="https://github.com/poisonousjohn">Github</a></li><li><a href="https://twitter.com/poisonous_john">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b177e61556c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/decoupling-game-code-via-command-pattern-debugging-it-with-time-machine-2b177e61556c">Decoupling your game code via Command pattern, debugging it flying on the time machine</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Абстракциями тебе по голове]]></title>
            <link>https://medium.com/gamedev-architecture/%D0%B0%D0%B1%D1%81%D1%82%D1%80%D0%B0%D0%BA%D1%86%D0%B8%D1%8F%D0%BC%D0%B8-%D1%82%D0%B5%D0%B1%D0%B5-%D0%BF%D0%BE-%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%B5-d10655098020?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/d10655098020</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Wed, 30 May 2018 12:52:21 GMT</pubDate>
            <atom:updated>2018-05-30T12:52:21.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*kq6LVdOeGU1s9MgWj2So7Q.jpeg" /><figcaption>Image credits: <a href="https://4quartets4lent.org/2018/03/01/hit-by-a-book-east-coker-4/">4quartets4lent.org</a></figcaption></figure><p>Стараться спроектировать систему максимально гибкой и универсальной — хорошее желание. Но мы имеем тенденцию увлекаться. Не все можно учесть и обобщить, да и нужно ли?</p><p>Архитектура — это действительно важно, но писать код ради кода бессмысленно. Он должен решать реальную проблему, а не ту, которая будет когда-нибудь потом.</p><p>Увлекаясь, мы городим все новые и новые слои абстракции, стараясь предусмотреть все возможные случаи использования. В итоге, сложность решения превышает разумные пределы.</p><h4>Как измерить эти пределы?</h4><p>Когда в системе слишком много сущностей и уровней абстракции, непросто докопаться до истины. Вместо того, чтобы сразу заняться делом, мы выстраиваем в голове все связи между этими сущностями. Закапываемся в интерфейсах, абстрактных классах, виртуальных функциях. И вот там, где то на дне, лежит код, который и делает всю работу.</p><p>Выстраивание модели системы в голове создает когнитивную нагрузку. Чем выше эта нагрузка, тем ниже наша эффективность. Именно поэтому “overengineering”, то есть переусложнение, считается плохой практикой.</p><p>Кстати, высокая когнитивная нагрузка — это одна из главных причин, по которой мы не хотим разбираться в чужом коде.</p><p>Что забавно, тенденеция к этому никак не зависит от опыта. Этим грешат как новички, создающие классы на каждый пук, так и опытные разработчики, усложняя систему другими “более умными” способами =). Что греха таить, я и сам себя ловлю на мысли, что слишком увлекся.</p><h4>Ну и что же с этим делать?</h4><p>Во-первых, если вы почувствовали, что зашли слишком далеко — остановитесь. Доведите систему до рабочего состояния, а затем взгляните на все свежим взглядом. Попробуйте выстроить все снова в голове, и прислушайтесь к себе. Легко ли вам это все понять? Попробуйте убрать все излишние части, усложняющие понимание. Сделал хорошо? Теперь сделай просто :)</p><p>Во-вторых, покажите код коллеге. Если система слишком сложна, он обязательно об этом вам скажет. Ну или просто завалит вас вопросами. Уже не в первый раз говорю о великой пользе код-ревью.</p><h4>Имейте смелость признаться в ошибке и все исправить</h4><p>Ну и напоследок, хотелось бы сказать, что независимо от того сколько времени вы потратили на ваше детище, если оно не работает как надо, или является слшком сложным, вы должны быть смелым и признать этот факт.</p><p>После признания и принятия этого факта сердцем, придут мысли о том как можно исправить ситуацию. Это же вас может привести к совершенно свежим решениям, новым открытиям и интересному опыту.</p><p>Я всегда руководствуюсь правилом, что идеальный тот код, которого нет. Удалять все лишнее, неипользуемое, неправильное — это как лечение больного от недугов. Если та “масштабируемость”, которая была заложена в систему, не понадобилась или не окупилась, то ее нужно вырезать.</p><p>Абстракции не только бьют по нашему сознанию, но и привносят накладные расходы: тратят память, ухудшают производительность и т.д.</p><p>Ну и в конце, хочу сказать, что программирование — это искусство поиска равновесия. Между красотой и производительностью, качеством и временем, функциональностью и простотой.</p><p>Если статья вам понравилась, не забудьте похлопать и подписаться :).</p><p>Еще больше статей и заметок вы можете найти на Telegram канале <a href="https://t.me/gamedev_architecture">GameDev Architecture</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10655098020" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/%D0%B0%D0%B1%D1%81%D1%82%D1%80%D0%B0%D0%BA%D1%86%D0%B8%D1%8F%D0%BC%D0%B8-%D1%82%D0%B5%D0%B1%D0%B5-%D0%BF%D0%BE-%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%B5-d10655098020">Абстракциями тебе по голове</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Архитектура и командная работа]]></title>
            <link>https://medium.com/gamedev-architecture/%D0%B0%D1%80%D1%85%D0%B8%D1%82%D0%B5%D0%BA%D1%82%D1%83%D1%80%D0%B0-%D0%B8-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D0%BD%D0%B0%D1%8F-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0-fd05952111f8?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd05952111f8</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Tue, 15 May 2018 09:08:43 GMT</pubDate>
            <atom:updated>2018-05-15T09:08:43.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AiVCuJG6_ArG38bAkd1myg.png" /><figcaption>Image credits: <a href="https://pixshark.com/software-engineering-team.htm">https://pixshark.com/software-engineering-team.htm</a></figcaption></figure><p>Разрабатывая архитектуру под конкретную задачу, мы, обычно, выкладываемся по полной. Стараемся все предусмотреть и решить заранее.</p><p>Но, на практике, такой подход работает редко. Все дело в том, что архитектура никогда не бывает статичной.</p><p>Бизнес требования меняются постоянно, часто — совсем кардинально. Это требует адаптации существующей архитектуры, а то и, вовсе, тотального рефакторинга.</p><p>Прессинг со стороны менеджмента заставляет закрывать глаза на проблемы и “заняться делом”. Это понятно, если сразу бросаться все переделывать — далеко не уедешь. Но есть и другая сторона проблемы.</p><p>Если многие механики игры завязаны на одну и ту же архитектуру/модули, то все больше и больше задач затрагивают общий код. Каждый пытается подогнать архитектуру под себя минорными изменениями, и, в конце концов, получается эдакий франкенштейн, который никому не нравится, и никто не хочет им заниматься. Все его прогоняют от себя, и связываются с ним только когда очень надо, и то, осторожно тыкая его палками.</p><p>В таком случае, каждая проблема, на которую закрыли глаза, аукается многократно, но не сразу.</p><p>Все любят говорить, что архитектура должна быть “гибкой” (ой как все мы любим слово “agile”), подразумевая под этим, что она должна легко адаптироваться под любые задачи. Но люди редко учитывают, что с первой попытки такую архитектуру построить практически невозможно. А это значит, что архитектура должна постоянно меняться, улучшаться, адаптироваться.</p><p>Соль в том, что в проектировании архитектуры должна участвовать <strong>вся</strong> команда.</p><h3>Взгляд снизу</h3><p>Что обычно делает <strong>рядовой</strong> разработчик, когда натыкается на проблемное место? Он либо ищет простейший способ сделать свою задачу, например, сделав быстрый фикс на соплях. Либо же он совершенно не хочет вникать в подробности, и изобретает свой новый велосипед, который еще хуже существующего. У обоих вариантов общий корень зла — безразличность.</p><p>Оба варианта только добавляют еще больше технического долга, более того, если нет практики код-ревью, то он еще останется и незамеченным.</p><p>Разработчики поопытнее и постарше, как правило, вникают гораздо глубже. Они могут докопаться до корня проблемы, и применяют фиксы более продуманно и аккуратно. Но, <strong>обычно, не принимают каких-либо глобальных мер по исправлению ситуации</strong>.</p><p>Если разработчик не безразличен, и понимает, что это влияет на всех, в том числе и на него, то он попытается донести результаты своих исследований до коллег, а потом и наверх. Но, если не будет услышан, то может просто забить и смириться. Многие считают, что это не их обязанность заниматься такими вещами. Как говорится, “проблема не на нашей стороне”.</p><p>Такой подход немного лучше, но все равно, со временем, закопает проект еще глубже.</p><p>Воистину заинтересованные разработчики могут в корне изменить ситуацию, наладив коммуникацию внутри команды и организовать согласованную работу по доработке архитектуры. Но, чтобы это имело достаточно большой размах, нужны определенные полномочия. Такие разработчики идеальные кандидаты в тим лиды.</p><p>Как видно из описанного выше, общение в команде — одна из ключевых вещей. Что нужно для разработки “гибкой” архитектуры? Общаться и услышать мнение каждого. Ведь для каждого разработчика эта “гибкость” может выражаться по разному.</p><p>Человек, который разрабатывает архитектуру может не учитывать какого-то аспекта, очевидного для другого. Разные люди по-разному подходят к решению задачи, поэтому иметь на руках несколько точек зрения — всегда полезно.</p><h3>Взгляд сверху</h3><p>Как выглядит ситуация со стороны менеджмента?</p><p>Они планируют определенную загрузку на релиз. В течение нескольких релизов команда работает с определенным темпом. В какой-то момент, темп команды начинает значительно замедляться.</p><p>В глазах менеджмента это выглядит как какая-то халтура. Может разработчики тратят время на что-то еще? Может они в соц. сетях зависают? Надо на них надавить, чтобы они работали быстрее.</p><p>Разработчики же в это время загибаются от нагрузки. Менеджмент вместо того, чтобы выяснить реальную причину замедления темпа, прислушаться к команде (плакатам и транспорантам “Нам нужен рефакторинг!”), просто накидывают еще задач, и постоянно давят.</p><p>Тим лид в этой ситуации должен выступать медиатором, и блюсти интересны как менеджмента, так и разработчиков. Проблема многих команд — отсутствие нормальной коммуникации. Тим лид должен брать на себя обязанности по общению с менеджментом и разрешению общих проблем проекта.</p><p>Чтобы все было хорошо, менеджмент должен доверять тим лиду, либо при его отсутствии, прислушиваться к общему мнению коллектива разработчиков.</p><h3>Выводы</h3><p>Про то, <a href="https://medium.com/gamedev-architecture/%D0%B0%D0%BD%D0%B0%D0%BB%D0%B8%D0%B7-%D0%B7%D0%B4%D0%BE%D1%80%D0%BE%D0%B2%D1%8C%D1%8F-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-29896c6c3ade">как анализировать здоровье проекта и как его лечить с технической стороны</a>, я уже писал в отдельной статье. В этой статье я хотел показать, что жизнь и архитектура проекта — это не только технические аспекты, но и командные.</p><p>Чтобы у проекта все было хорошо, над архитектурой нужно постоянно работать, улучшать, адаптировать. Чтобы этот процесс происходил эффективно, должно быть налажено общение и культура донесения конструктивной критики.</p><p>Если статья вам понравилась, не забудьте похлопать и подписаться :).</p><p>Еще больше статей и заметок вы можете найти на Telegram канале <a href="https://t.me/gamedev_architecture">GameDev Architecture</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd05952111f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/%D0%B0%D1%80%D1%85%D0%B8%D1%82%D0%B5%D0%BA%D1%82%D1%83%D1%80%D0%B0-%D0%B8-%D0%BA%D0%BE%D0%BC%D0%B0%D0%BD%D0%B4%D0%BD%D0%B0%D1%8F-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0-fd05952111f8">Архитектура и командная работа</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Анализ “Здоровья” проекта]]></title>
            <link>https://medium.com/gamedev-architecture/%D0%B0%D0%BD%D0%B0%D0%BB%D0%B8%D0%B7-%D0%B7%D0%B4%D0%BE%D1%80%D0%BE%D0%B2%D1%8C%D1%8F-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-29896c6c3ade?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/29896c6c3ade</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Sat, 07 Apr 2018 13:54:08 GMT</pubDate>
            <atom:updated>2018-04-08T12:29:49.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuPltM148s6i2Skx6Iqj7w.jpeg" /><figcaption>Image credits: mashinapro.ru</figcaption></figure><p>Говорить про архитектуру можно бесконечно долго. Разводить холивары про то, какой движок, фреймворк, код стайл пользовать. Но что реально важно — смотреть на все в контексте прикладных задач.</p><p>Управление проектом — тоже часть построения архитектуры. И оно так же требует итеративного подхода, с целью анализа и последующей оптимизации.</p><p>Пост-мортем проекта — важная штука. Но есть нюанс. После драки кулаками уже не машут. Часто бывает, что ситуацию можно изменить и до того, как проект сдохнет.</p><p>Но люди фокусируются не на том. Думают о том как напихать побольше фич. Реализация затягивается. Релизы сдвигаются. И никто не замечает очевидных причин.</p><p>Можно остановиться на день. И посмотреть на ситуацию под другим углом.</p><h3>Профайлинг проекта</h3><p>Когда мы пишем код, и видим, что где-то есть лаги, тормоза, что мы делаем? Мы открываем профайлер и ищем источник проблем. То же самое можно сделать и на более высоком уровне.</p><p>Посмотрите какие были задачи. Какие из них сильно вышли за рамки оценок. Попробуйте определить причины. Связаны ли они с ошибкой в оценке конкретным человеком, или проблема более систематична. Может она одинакова для всех. Имеют ли такие задачи нечто общее? Может они затрагивают одну и ту же подсистему.</p><p>Я делал это упражнение в нескольких проектах. И оно помогло выявить больные места архитектуры. Например, несколько спринтов подряд все задачи, связанные с UI, сильно выходили за рамких оценки. Кто-бы не брался за эти задачи, все равно не мог уложиться. Плюс ко всему на следующем спринте появлялось много задач по фиксу багов в реализованном функционале. Проблема была систематичекой.</p><p>Взглянув на проблемные места на более низком уровне, источник стал более очевидным. Функции, осуществляющие подготовку данных для отрисовки в UI были крайне неоптимальными.</p><p>Было много дублирования кода. Логики было настолько много, что никто не мог найти существующих функций, и переписывал тот же функционал раз за разом. При этом повторяя все те же ошибки, которые уже были зафикшены.</p><p>Конечно, люди были в курсе проблем. Но из-за того, что сверху сильно давили реализацией новых фич, остановиться на рефакторинг никто не мог. Да и, по всей видимости, не хотел.</p><p>Представив полученную перспективу верхнего уровня менеджменту, объяснив, что проекту плохо и дальше будет только хуже, нам удалось привлечь внимание.</p><p>Взгляд с высокой колокольни помогает заметить те вещи, которых не видно в рутине каждодневных задач.</p><h3>Назначаем лечение</h3><p>Выяснив “нездоровый” участок проекта, нужно начать его “лечение”. Так же как оптимизация кода не может быть “вслепую”, так же и рефакторинг нужно проводить точечно и с умом.</p><p>От того что мы стали использовать табуляцию вместо пробелов, стали бы мы делать меньше ошибок?</p><p>Никто из менеджеров не даст карт-бланш, если не будет достаточной мотивации. А рефакторинг конкретной части проекта, из-за конкретных причин, звучит гораздо реалистичнее, чем “переписать все нахрен”.</p><p>Имея в голове конкретные причины, которые тормозят всю команду, нужно составить конкретный план по их лечению. Он должен быть разбит на шаги, каждый из которых самодостаточен и не ломает проект.</p><p>При рефакторинге нужно быть последовательным, упрямым и настойчивым. Всегда нужно помнить, что не доведя дело до конца, пользы от него будет мало.</p><p>А что любят менеджеры? Правильно: видеть результат.</p><h3>Переходим к делу</h3><p>В зависимости от размера рефакторинга, нужно выделить определенное количество человек. И <strong>не дергать их по другим задачам</strong>.</p><p>Лучше всего рефакториг делать <strong>маленькими</strong> частями. Тогда и людей нужно будет меньше. И проводить его можно будет быстрее.</p><p>Вся работа должна осуществлятся в отдельной ветке VCS, так чтобы не мешать другим. Если проигнорировать эту часть, то можно привнести негативное впечатление от рефакторинга, что он только ломает, а не помогает.</p><p>Ведя же работу в отдельной ветке, менеджеры будут думать, что “они что-то там делают, но у нас есть рабочий билд”. Так им намного спокойнее.</p><p>Не нужно отвлекаться на другие “грязные” вещи, замеченные во время рефакторинга, не относящиейся к текущей задачи. Так можно потерять фокус и слишком затянуть работу, рискуя получить приказ “все бросить”.</p><p>Важно понимать, что чем дольше идет рефакторинг, тем сложнее его будет интегрировать обратно в рабочую ветку. Поэтому в ваших же интересах все делать как можно быстрее.</p><h3>Анализ результата</h3><p>Проведя рефакторинг, важно показать результат руководству. После нескольких спринтов посмотрите на статистику задач.</p><p>Стало ли багов меньше? Стала ли оценка задач совпадать с фактически затраченным временем?</p><p>Если положительный результат будет замечен, то в следующий раз менеджмент с радостью даст время на такие работы по оздоровлению.</p><p>Темп работы — самый критичный фактор. Особенно в играх.</p><p>Я привел пример из жизни. Проблема с UI не раз возникала на проектах. Но по факту, больным местом может быть что угодно. И только детальный анализ позволит “не быть пустословом”.</p><p>Высокий темп разработки сильно давит. Когда проекту плохо, то давление еще выше. И если ничего не сделать, то пузырь может лопнуть.</p><p>DevOps — это не только CI/CD. Это полный цикл разработки. Анализ “здоровья” проекта должен быть частью этого цикла.</p><p>Если статья вам понравилась, не забудьте подписаться :).</p><p>Еще больше статей и заметок вы можете найти на Telegram канале <a href="https://t.me/gamedev_architecture">GameDev Architecture</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29896c6c3ade" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/%D0%B0%D0%BD%D0%B0%D0%BB%D0%B8%D0%B7-%D0%B7%D0%B4%D0%BE%D1%80%D0%BE%D0%B2%D1%8C%D1%8F-%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B0-29896c6c3ade">Анализ “Здоровья” проекта</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NoSQL для сохранения стейтов пользователя]]></title>
            <link>https://medium.com/gamedev-architecture/nosql-%D0%B4%D0%BB%D1%8F-%D1%81%D0%BE%D1%85%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F-%D1%81%D1%82%D0%B5%D0%B9%D1%82%D0%BE%D0%B2-%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F-9306a8eef790?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/9306a8eef790</guid>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Sun, 01 Apr 2018 12:13:43 GMT</pubDate>
            <atom:updated>2018-04-01T12:13:43.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KqQ3Pf1JDfGmLtuh." /><figcaption>Image credits: <a href="https://gameserverarchitecture.com/2016/04/podcast-hanselminutes-scaling-the-walking-dead-no-mans-land-with-next-games-kalle-hiitola/">gameserverarchitecture.com</a></figcaption></figure><p>Очень интересно изучить детали того, как построены крупные проекты. Конечно, во многих статьях это очень поверхностно. Но иногда хватает и общих концепций.</p><p>Вот, например, <a href="https://gameserverarchitecture.com/2016/04/podcast-hanselminutes-scaling-the-walking-dead-no-mans-land-with-next-games-kalle-hiitola/">The Walking Dead: No Man’s Land</a>.</p><p>Несколько интересных моментов из статьи/подкаста:</p><p>1. <strong>Используется #NoSQL.</strong> Среди студии часто вижу, что для сейвов пользуют именно #NoSQL. И даже если сохраняется это все в SQL, то используется просто в виде Key-Value хранилища, где Value — сериализованный стейт.<br>2. <strong>Данные пользователей хранятся в памяти</strong>. Сохраняются только когда юзер логаутится. Кэширование сделано в виде обычной хэш таблицы [я думаю по user id].<br>3. <strong>Стейт юзера и команды представлены в виде JSON</strong>, и сериализация/десериализация — единственное что сильно грузит проц. Поэтому хранить все in-memory в виде нативных объектов — сильно разгружает систему.</p><p>Такой подход я вижу довольно часто, и он работает очень эффективно.</p><p>Что тут нужно заметить. Юзера нужно привязывать к определенному серверу, т.е. должен быть session affinity. Тогда не будет конфликта в данных пользователя.</p><p>Помимо сохранения на log off я бы еще порекомендовал периодически сохранять стейт (если изменился). Это спасет при случае, когда сервак рухнет, тогда данных по юзерам потеряется меньше.</p><p>Этот подход прекрасно ложится <a href="https://gameserverarchitecture.com/2016/04/podcast-hanselminutes-scaling-the-walking-dead-no-mans-land-with-next-games-kalle-hiitola/">на пример с паттерном Command</a>, который я описывал ранее.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9306a8eef790" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/nosql-%D0%B4%D0%BB%D1%8F-%D1%81%D0%BE%D1%85%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F-%D1%81%D1%82%D0%B5%D0%B9%D1%82%D0%BE%D0%B2-%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8F-9306a8eef790">NoSQL для сохранения стейтов пользователя</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Попроще или подольше?]]></title>
            <link>https://medium.com/gamedev-architecture/%D0%BF%D0%BE%D0%BF%D1%80%D0%BE%D1%89%D0%B5-%D0%B8%D0%BB%D0%B8-%D0%BF%D0%BE%D0%B4%D0%BE%D0%BB%D1%8C%D1%88%D0%B5-c1e6a80c0bfa?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e6a80c0bfa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Mon, 26 Mar 2018 08:56:44 GMT</pubDate>
            <atom:updated>2018-03-26T11:56:18.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*bjrHNyZDHTP3nYF6.png" /><figcaption>Image credits: <a href="https://doc.photonengine.com/en-us/realtime/current/getting-started/quick-start">https://doc.photonengine.com/en-us/realtime/current/getting-started/quick-start</a></figcaption></figure><p>Интересный факт. Замечаю, что многие студии начинают с решения попроще. Например, для сетевого мультиплеера, часто выбирают Photon (или любой другой easy-to-go фреймворк).</p><p>Это позволяет быстро начать разработку и заниматься <strong>игрой</strong>, а не тулсетом. Но, в конечном счете, когда игра выходит в продакшен, Photon (да и любой другой подобный инструмент) становится обузой.</p><p>Я не раз видел, когда после значительного времени разработки, от Photon’a используют только транспорт. Потому что большинство других фич недостаточно кастомизируемы.</p><p>Саму задачу реализации транспорта несложно сделать и без Photon’a. Но к моменту, когда приходит время заменить его на что-то другое, более кастомизируемое, клиент игры уже весь испещрен зависимостями, и <strong>намертво привязан к библиотеке</strong>.</p><p>Это выливается в немалые накладные расходы:</p><p>- Photon работает только под Windows. А виртуалки на винде могут стоить в 1.5 раза (!) дороже линуксовых.<br>- Клиент переписывать долго и дорого. Да и не имеет особого смысла, ведь все же работает!</p><h4>И что же делать? — спросите вы.</h4><p>Начинайте с того, что проще, и что максимально ускорит разработку. Photon — неплохой вариант.</p><blockquote>Но чтобы избежать проблем в будущем, думайте на архитектурой уже сейчас.</blockquote><p>Не забывайте, что конкретные библиотеки можно скрыть за интерфейсом. Да, это небольшие накладные расходы во время разработки. Но это может сэкономить кучу денег и времени в будущем!</p><p>Если сетевые фичи будут скрыты за интерфейсом, то вы всегда сможете подменить одну реализацию на другую. В минимальные сроки. Это касается как клиента, так и сервера.</p><p>То же самое должно быть сделано и с бизнес-логикой. Она должна быть абстрагирована от сети.</p><p>Такой подход дает и свободу остаться на исходном решении, если оно вас устраивает.</p><p>Предварительная оптимизация — тоже зло. Поэтому, начинать с написания собственного решения, может убить проект на корню. Ведь вместо того, чтобы сделать игру, вы разработаете сетевой фреймворк.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e6a80c0bfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gamedev-architecture/%D0%BF%D0%BE%D0%BF%D1%80%D0%BE%D1%89%D0%B5-%D0%B8%D0%BB%D0%B8-%D0%BF%D0%BE%D0%B4%D0%BE%D0%BB%D1%8C%D1%88%D0%B5-c1e6a80c0bfa">Попроще или подольше?</a> was originally published in <a href="https://medium.com/gamedev-architecture">GameDev Architecture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Антипаттерны в игровой разработке]]></title>
            <link>https://poisonousjohn.medium.com/%D0%B0%D0%BD%D1%82%D0%B8%D0%BF%D0%B0%D1%82%D1%82%D0%B5%D1%80%D0%BD%D1%8B-%D0%B2-%D0%B8%D0%B3%D1%80%D0%BE%D0%B2%D0%BE%D0%B9-%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%BA%D0%B5-%D0%B7%D0%B0%D0%B2%D0%B8%D1%81%D0%B8%D0%BC%D0%BE%D1%81%D1%82%D0%B8-%D0%B2-%D0%BA%D0%BE%D0%B4%D0%B5-1bd879ef46ad?source=rss-2c05dcd3c106------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd879ef46ad</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Poisonous John (Ivan Fateev)]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 10:01:53 GMT</pubDate>
            <atom:updated>2022-12-22T12:25:35.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Антипаттерны в игровой разработке: Зависимости в коде</h3><p>Хорошая архитектура в играх так же важна, как и в любом другом ПО. В интернете довольно много туториалов базового уровня. Но, как только проект вырастает из “песочницы”, появляется и необходимость в архитектуре. А это уже более продвинутый уровень.</p><p>Вся ирония в том, что в игровой разработке проблемы ровно те же, что и в любой другой.</p><p>Если посмотреть на принципы построения правильной архитектуры с высокой колокольни, то они крутятся вокруг низкой связности кода.</p><p>Что это значит? Рассмотрим интересный случай из моей практики.</p><p>На одном из проектов был гигантский статик класс, который в себе содержал референсы на различные “<strong>сервисы</strong>”. Мы так называли своего рода синглтоны (но они не были синглтонами, просто создавали по одному экземпляру), которые отвечают за одну из задач.</p><p>Например:</p><ul><li>Сервис отправки аналитики</li><li>Сервис показа рекламы</li><li>Сервис локальных Push уведомлений</li><li>Сервис серверного API</li><li>и т.д.</li></ul><p>Каждый из сервисов требовал разного рода информации для инициализации. Например, сервис показа рекламы требовал user id, который в свою очередь может быть получен только через сервис серверного API.</p><p>Если представить уже зарелиженный проект, то там насчитается порядка 40 сервисов. А степень зависимости сервисов между друг другом ужасает.</p><h3><strong>В чем проблема?</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/545bb1b48f334d42a2692df55175a637/href">https://medium.com/media/545bb1b48f334d42a2692df55175a637/href</a></iframe><p>Здесь на лицо две проблемы:</p><ol><li>Привязка к конкретным классам сервисов</li><li>Инициализация сервисов никак не определена и может происходить где угодно и как угодно</li></ol><h4>Привязка к конкретному классу</h4><p>Казалось бы, чем плохо привязываться к конкретному классу?</p><p>Предположим, что мы гоняем игру на своей локальной машине, на которой нет сетевого соединения, как себя будет вести игра?</p><p>Большинство игр посылают разные данные на сервер, и при отсутствии сетевого соединения могут показывать ошибки или ограничивать определенный функционал. Стандартный подход для решения этой проблемы — поддержка оффлайн режима.</p><p>Как мы это можем сделать? Шлепнуть еще один static флаг isOffline, и проверять его в каждом методе сервиса, завязанного на сетевое соединение:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0f7c75c1a001553d4fe32ae2b8506e9/href">https://medium.com/media/f0f7c75c1a001553d4fe32ae2b8506e9/href</a></iframe><p>Но это, по сути, перемешивание дебажного кода с релизным, что чревато дополнительными багами. Более чистый вариант:</p><ul><li>создать специальную оффлайн версию класса сервиса</li><li>сделать методы виртуальными и унаследоваться от базового сервиса</li><li>переопределить методы, требующие оффлайн поддержки</li><li>инициализировать отдельную оффлайн версию сервисов при локальной оффлайн отладке</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff5b39b17e244e563c648c83d1df82d6/href">https://medium.com/media/ff5b39b17e244e563c648c83d1df82d6/href</a></iframe><p>Уже лучше. Но что, если базовый класс APIService требует сложной инициализации и других зависимостей, например, от базы данных. Наследование очень сильно ограничивает. Поэтому, интерфейсы предпочтительнее.</p><p>За интерфейсом можно спрятать что угодно, в том числе абсолютно не связанные имплементации.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/514a9eff7b8a2b7a35df642dcc8ff93e/href">https://medium.com/media/514a9eff7b8a2b7a35df642dcc8ff93e/href</a></iframe><p>Я здесь использовал класс <a href="https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx">Lazy</a>. К сожалению в .Net 3.5 его нет. Но мы можем написать его сами.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9ff4fa0441307e556768fb2eb594c72/href">https://medium.com/media/c9ff4fa0441307e556768fb2eb594c72/href</a></iframe><p>В данном случае, объект будет инициализироваться лениво, в момент, когда его запросят через <strong>Value</strong>. Ленивая инициализация несколько развязывает руки. Что ведет нас к следующей теме.</p><h4>Еще немного про интерфейсы</h4><p>Типичная ситуация, мы закончили реализацию старой игры и начинаем новую. Мы знаем, что можно переиспользовать часть функционала, и начинаем перетаскивать в новый проект нужные классы.</p><p>И вот мы перетащили все что нужно, начинаем компилить. Бац! Нужен еще вот этот класс. А потом еще вот этот. И вот вы уже перетащили 100500 легаси классов со старого проекта, включая те, от которых давно следовало избавиться.</p><p>А если в проекте был фанат ООП и наследования, то в проект перекочуют еще больше зависимостей в виде базовых классов.</p><p>Если бы мы использовали интерфейсы, то вместо большинства легаси классов можно было бы воткнуть либо адаптеры к существующим реализациям на новом проекте, либо временные заглушки.</p><h4>Произвольная инициализация</h4><p>Инициализация зависимостей может быть раскидана по всему коду. Потому что обычно она пишется в императивном стиле, как это было показано в самом первом примере. Из-за асинхронности зависимости создаются в разное время и в разных местах.</p><p>С помощью Lazy обозначать инициализацию сервиса, можно декларативно, в виде лямбды. Что позовляет объявить инициализацию всех сервисов в одном месте, не беспокоясь о времени вызова.</p><p>Аналогично, вместо прямой ссылки на зависимость, можно прокидывать <strong>Lazy&lt;T&gt;</strong>. Это очень полезно, если есть кросс-ссылки. Т.е. когда сервисы завязаны друг на друга.</p><p>Рассмотрим простой пример. Предположим, я хочу, чтобы Logger отображал идентифактор пользователя на сервере, если таковой имеется. Но при этом, APIService может пользоваться тем же логгером. Как раз, кросс-зависимость.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934bfee0c0bfecbe217985aa1e80e3ed/href">https://medium.com/media/934bfee0c0bfecbe217985aa1e80e3ed/href</a></iframe><p>Давайте посмотрим что выводится в консоль.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*KqLB1-iPEhQ446qVtznkbg.png" /></figure><p>Итак, что это дало? APIService создастся только когда его кто-то вызовет через Services.api.Value. Чтобы показать это, в Awake скрипта я вставил лог “Loading started”. Он обозначает пользователя как anonymous, что подтверждает, что APIService не создан.</p><p>Запись “Login started” вызывается из APIService, а это подтверждает, что кросс-зависимост успешно работает.</p><h3>Пользуемся благами цивилизации</h3><p>Чем плох подход со статическим классом Services? Хотя проблема с инициализацией и разрешена, мы все еще привязаны как к самому классу Services, так и к конкретным его полям.</p><p>К сожалению, использование такого подхода заставляет людей писать код, нарушающий принципы внедрения зависимостей. Слегка изменю предыдущий пример.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dcde1f6c5064a8f6e6a11e520d3b02e/href">https://medium.com/media/6dcde1f6c5064a8f6e6a11e520d3b02e/href</a></iframe><p>На 7 строчке вы можете видеть прямое использование класса Services.</p><p>Это привносит как минимум две проблемы:</p><ol><li>Из сигнатуры конструктора APIService не понятно, что он зависит от логгера</li><li>APIService нельзя использовать изолированно, например, для тестов работы с API. Нужно обязательно тянуть за собой класс Services, котя можно было бы просто прокинуть логгер в конструктор</li></ol><p>Развиваем тему.</p><p><strong>А что, если каждому из сервисов понадобится свой логгер? </strong>Придется перелопачивать весь код, отвязываясь от класса Services.</p><p><strong>Что если для тестовых сцен нужно отключить сервисы или сделать на них заглушки?</strong> Менять определение инициализации прямо в Services?</p><p><strong>Что если вы собрались написать Unit тест?</strong> Нужен ли вам класс Services в них? Сомневаюсь.</p><p>Все это не очень красиво, да и не особо удобно.</p><p>Эта проблема давно уже решена за нас. <a href="https://ru.wikipedia.org/wiki/%D0%92%D0%BD%D0%B5%D0%B4%D1%80%D0%B5%D0%BD%D0%B8%D0%B5_%D0%B7%D0%B0%D0%B2%D0%B8%D1%81%D0%B8%D0%BC%D0%BE%D1%81%D1%82%D0%B8">Dependency Injection</a> — это довольно распространенный паттерн для разрешения проблемы зависимостей.</p><p>Это довольно обширная тема, чтобы покрывать ее в этой статье, поэтому я поделюсь ссылками:</p><ol><li><a href="https://habrahabr.ru/post/188438/">Dependency Injection в Unity</a></li><li><a href="http://blog.gandjustas.ru/2009/01/19/ioc/">Введение в Inversion of Control</a></li><li><a href="https://unity3d.college/2016/02/22/dependency-injection-and-unit-testing-unity/">Dependency Injection and Unit testing in Unity</a></li></ol><h3>Подведем итоги</h3><ol><li>Не привязывайтесь к статическим классам</li><li>Будьте дисциплинированы и держите ваши зависимости под контролем</li><li>Используйте интерфейсы, вместо конкретных реализаций</li><li>Используйте, по возможности, существующие решения для разрешения зависимостей, Dependency Injection или другие вариации Inversion of Control</li></ol><p>Если статья была полезной и понравилась вам, подписывайтесь:</p><ul><li><a href="https://t.me/gamedev_architecture">Telegram</a></li><li><a href="https://twitter.com/Poisonous_John">Twitter</a></li><li><a href="https://medium.com/@poisonousjohn">Medium</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd879ef46ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>