<?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[TechTalks@Vattenfall - Medium]]></title>
        <description><![CDATA[Challenges, ideas, and tips brought by Vattenfall IT. Stories of programmers. - Medium]]></description>
        <link>https://medium.com/vattenfall-tech?source=rss----4240c54ef437---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>TechTalks@Vattenfall - Medium</title>
            <link>https://medium.com/vattenfall-tech?source=rss----4240c54ef437---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:55:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/vattenfall-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[You might not need all those design patterns in TypeScript]]></title>
            <link>https://medium.com/vattenfall-tech/you-might-not-need-all-those-design-patterns-in-typescript-d5671b34410a?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/d5671b34410a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Stawiarski Jakub]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 07:46:56 GMT</pubDate>
            <atom:updated>2022-01-21T07:46:56.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZBOlsUZAZLU0lqxuGX0mQ.jpeg" /><figcaption>Photo by <a href="https://pixabay.com/users/mickey970-1278620/">mickey970</a> from <a href="https://pixabay.com/photos/busy-office-ol-answer-the-phone-880800/">Pixabay</a>.</figcaption></figure><p>TypeScript’s type safety and object-oriented features made it quite simple for web developers accustomed to languages such as Java or C# to start using it. I experienced this switch first hand, having spent most of my career thinking in Java.</p><p>There is a pitfall, though. One might be tempted to apply the same solutions he knows from other object-oriented languages. Those might either not work exactly the same, may have simpler alternatives, or may solve problems that do not exist here at all.</p><p>As an example, let’s take a look at a couple of well-known (or a bit more exotic) design patterns and see how the problems they try to solve can be approached differently in this language.</p><h4>Singleton pattern</h4><p>Explaining why we should steer away from this one should be simple, since this pattern is no longer really considered good practice, even back in the object-oriented world.</p><p>To use a real-life example, let’s assume that we are introducing multiple language support to an app, and we want a single, globally usable way of translating a text. Using a singleton, it could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4df57c6a2bd334fc2188d68c036cd45/href">https://medium.com/media/d4df57c6a2bd334fc2188d68c036cd45/href</a></iframe><p>That is quite a lot of boilerplate we need to type even before we start implementing the actual translation logic. What may also be surprising is that the instance isn’t perfectly protected against being changed. We could make it a bit better by using a symbol to refer to the instance, using the JavaScripts # notation for private fields, making everything read-only, .etc., but before we make the singleton even more complex let’s consider different options.</p><p>In our simplistic example, the singleton is used just to expose a single method and does not need to hold any state. Since TypeScript is a superset of JavaScript and functions do not need to be a part of a class here all of that could possibly be replaced with just the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b6b5842045a1bdcba803b46b3cc0a8b/href">https://medium.com/media/1b6b5842045a1bdcba803b46b3cc0a8b/href</a></iframe><p>But what if there were multiple functions we want to expose, and we want to create a sort of namespace for them and group them? Maybe we specifically need an object so that we can pass a reference to it? In that case, we can use the fact that not all objects in TypeScript need to be instances of a specific, named class. We could use an object literal and create a constant instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7415d2ed1e1bb7484af14e352e3370cb/href">https://medium.com/media/7415d2ed1e1bb7484af14e352e3370cb/href</a></iframe><p>That is still much less code than what we had to write in the singleton example. It also gives us some additional benefits. The client code seems more readable. We are also protected against accidentally changing the object.</p><h4>Strategy pattern</h4><p>The strategy pattern turns a group of behaviours into objects. This allows us to decide what implementation is used at runtime. We can also add new behaviours without modifying existing classes or introducing new subclasses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/704e7fb33d2dd2b100b6305bb77ab176/href">https://medium.com/media/704e7fb33d2dd2b100b6305bb77ab176/href</a></iframe><p>If we think about it, this pattern allowed us to simulate callbacks in a purely object-oriented way. You know, back in the days when something being purely object-oriented was still considered a good thing.</p><p>In JavaScript (and TypeScript) functions are already objects and callbacks are a thing. That means we do not need to simulate them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0a404f618713539a5f4ba381c80c352/href">https://medium.com/media/f0a404f618713539a5f4ba381c80c352/href</a></iframe><p>Note that most object-oriented languages made a similar thing possible already with lambda expressions.</p><p>If our strategy needs to hold some state, we can still work with functions. We can use a closure in that case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea98789ef4535724226e087f00cdbcd4/href">https://medium.com/media/ea98789ef4535724226e087f00cdbcd4/href</a></iframe><h4>Builder pattern</h4><p>The builder pattern is a creational pattern that is supposed to help us build complex objects by breaking up the creation into steps.</p><p>Example code that uses this pattern to create a Car instance could look something like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0891a5d9b879becf2b0ee0ba8b0c424/href">https://medium.com/media/f0891a5d9b879becf2b0ee0ba8b0c424/href</a></iframe><p>There are a couple of things that I would not be happy about when I would have to work with code like that. First of all, it is quite verbose for the thing it is trying to achieve. Secondly, there are some optional and some required properties that the client code needs to provide in order to get a Car instance, but the compiler cannot help us distinguish which are which. The only way to notice that the make and model properties are required is to run the code and see the error in runtime.</p><p>One way to make it a bit better would be to accept an object with all the properties and make the client code use an object literal to create it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf9d4ee6945c03ef106cae7a7ceaf0b/href">https://medium.com/media/baf9d4ee6945c03ef106cae7a7ceaf0b/href</a></iframe><p>The implementation is a bit less verbose even in this simple case and will surely scale better.</p><p>Notice that we made the constructor private so that we can still use the shorthand form and not have to declare all the properties separately. The if statement can be quite safely removed, as the compiler will now be able to warn the client when he does not set all the required properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kj66ZcNuHhO2AWBcku0izQ.png" /></figure><p>If we wanted to be a little fancier (and were using at least TypeScript 4.1) we could construct a type for our defaults. That way, the compiler could warn us when there are new properties added to our CarDetails type that do not have any defaults set. Here is how it could look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a4ecde3f76d9c585bb6c4e822c3b65/href">https://medium.com/media/25a4ecde3f76d9c585bb6c4e822c3b65/href</a></iframe><p>While it may look a bit scary for the uninitiated in TypeScripts mapped types, all this does is keep the optional properties of a given type T and remove all the required properties. This could become a utility type like the built-in Omit, Pick and other similar types.</p><p>The usage could look something like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MA8nR7kvz2cutrmwMX0QsA.png" /></figure><h4>Visitor pattern</h4><p>To show how can we replace the visitor pattern, let’s first take a look at why we would use it in the first place. One of the reasons is to solve the clash between the single responsibility and the open-closed principles from SOLID.</p><p>Say we are writing an app that both draws and calculates the area of multiple types of shapes. While this example might not feel very life like, we could face similar issues when working with any type of app that should be split into multiple layers or modules. Think separating some type of API from the business logic and storage.</p><p>One way to implement something like this could be to use polymorphism.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae918a1c7dd44bb281958a84e4be747/href">https://medium.com/media/dae918a1c7dd44bb281958a84e4be747/href</a></iframe><p>What is nice about this solution is that we can add new shapes to the app without modifying the client code. What is not so nice is that our shape classes now have multiple responsibilities. They clearly break the single responsibility principle. Both the complexity and the number of their dependencies may quickly grow.</p><p>To fix this, we might try to separate the drawing logic and try to inspect the type of shape there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36aac8f40154547f302c1bcea2e23b28/href">https://medium.com/media/36aac8f40154547f302c1bcea2e23b28/href</a></iframe><p>While this solves the single responsibility issue, it introduces a new one. To introduce a new Shape we would now need to go through all of the code and find all places where such distinction was being done and add a new if statement. The compiler would not be able to help us with this task. This breaks the open-closed principle.</p><p>Let’s now use a visitor instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e20d56ca20ecaebd50ed2d1fa619676a/href">https://medium.com/media/e20d56ca20ecaebd50ed2d1fa619676a/href</a></iframe><p>One might argue that this is the best out of a set of bad solutions. The drawing logic is separated so our Shape classes will not grow uncontrollably. We could even implement calculating the area as another visitor. That means we can add new functionality to a hierarchy of classes easily.</p><p>If we add a new Shape subclass, we will be forced to add a method to the ShapeVisitor interface. The client code will need to change, but at least the compiler can clearly show us which places in the code need to change in response.</p><p>One big drawback is that the solution is quite complex and verbose. The visitor pattern also seems to be not as popular as other patterns I mentioned before. If someone comes across it the first time, it might be challenging to get what is going on.</p><p>An alternative coming from the functional languages could be to use pattern matching. Unfortunately, Typescript does not include it natively. We can quite nicely simulate it using discriminated union types, though.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc5955952d4b52ac862c3c1162857b11/href">https://medium.com/media/cc5955952d4b52ac862c3c1162857b11/href</a></iframe><p>Since the type property of our shapes can only have two possible values, the compiler can know which type of object will be used in which branch. That is why we can safely access the properties of the shape in each of them.</p><p>The compiler could also warn us if there would be a new shape added later on and the switch statement would not be updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tgwdGQVybz9no2DKMuhWw.png" /><figcaption>This not perfect compilation error means, that this function can sometimes return `undefined` even though it’s signature says it cannot.</figcaption></figure><p>Even if we did not specify the return type of our function explicitly, we could still detect the missing branches as long as we had the noImplicitReturns config flag enabled when compiling TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*uCTHYyad-5Hi_gamCzZDGg.png" /><figcaption>The compilation error becomes cleaner.</figcaption></figure><p>This solution becomes a bit more complex when we want to write a function that doesn’t return anything (which isn’t really that functional, btw.). We can then rethink our solution and actually return something, even if it’s just a wrapper for the success or error message, or use a bit of TypeScript magic (a.k.a. a hack).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c585c4cf4972a32a260cbb1c5dc2e21/href">https://medium.com/media/0c585c4cf4972a32a260cbb1c5dc2e21/href</a></iframe><p>The handleNonExhaustiveSwitch the function is a way of telling the compiler that the code that calls it should never be reached. That is why it accepts the never type as an argument. Thanks to this, it could be declared once in the project and then reused in multiple files.</p><p>If after some future change in the code the last branch of the switch statement could be reached, the compiler will warn us about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4EYJU_T1yfHJ7qMcduVtg.png" /></figure><p>It is also worth mentioning that even though TypeScript does not offer pattern matching out of the box, its type system is powerful enough that the feature can be built on top of it with exhaustiveness checks. In fact, it was built already. One example is the quite nice <a href="https://www.npmjs.com/package/ts-pattern">ts-pattern</a> library.</p><h4>Summary</h4><p>I hope this article helped someone see how some language features, mostly stemming from the fact that TypeScript builds on top of JavaScript, let us achieve similar or better results than trying to copy the solutions from other languages.</p><p>I also hope that it inspires someone to take a step back, deepen their understanding of TypeScript and find better and simpler solutions to the problems he or she is trying to solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5671b34410a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/you-might-not-need-all-those-design-patterns-in-typescript-d5671b34410a">You might not need all those design patterns in TypeScript</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrum adventures of a junior developer]]></title>
            <link>https://medium.com/vattenfall-tech/scrum-adventures-of-a-junior-developer-748b2a1907c7?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/748b2a1907c7</guid>
            <category><![CDATA[empirical-process]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[vattenfall]]></category>
            <dc:creator><![CDATA[Bartosz Hanuszkiewicz]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 10:02:11 GMT</pubDate>
            <atom:updated>2022-01-14T10:06:13.191Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>In this article, you will find:</strong></h3><ul><li>The story is addressed for developers who never experienced scrum and would like to be prepared.</li><li>The story is about my first dive into the scrum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*rT_MXpM-Y36tdVch" /><figcaption>The sign which has welcomed me in the scrum process</figcaption></figure><h3><strong>Before the adventure starts</strong></h3><p>A long, long time ago over the hills and far away, somewhere between coal mines in Katowice where I lived — a junior developer with some experience in waterfall’s big and small projects. The history starts when I was thrown into the scrum inferno. Without any experience. With the image where scrum is developers’ hell with tortures of too many unnecessary meetings and a devil in person of a scrum master. I’ve heard a lot of stereotypes and myths about how scrum is preventing poor developers from coding and developing their products. Is it true? Let’s take a look at my journey and how I see it now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYOigpMg9NXaLxln21LrEQ.png" /><figcaption>The First Sprint</figcaption></figure><h3><strong>The First Sprint</strong></h3><p>I remember the first day with a feeling when you come to the new project, and uncertainty about how you will be accepted into the team. That exciting sensation of learning and experiencing new things.</p><p>Scrum ceremonies were the first day in the Team. The day started with Sprint Review. It was easy at that moment to understand what is the purpose of this meeting. Of course, it was to share what the team had done in the sprint. After we started, Sprint Retrospective — it sounded like breaking sprint into pieces and evaluating how it went. Like to judge if it was a good or a bad sprint. Then planning started. I thought that it’s about planning a few tasks which we will do in the next 2 weeks.</p><p>In breaks between meetings, I remember the openness of the team. They were truly interested in who I am. How did it happen that I joined the team? What hobbies do I have? They also introduced themselves. That made me feel like I was already a team member. Maybe you can say that it’s trivial, but for the newbie, that was very important. At that moment I first experienced that one of the team values is respect. And already got to know that the team spirit is based on strong values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*3rHJJG2QLtqEM_OY" /><figcaption>Many faces of the Scrum Master</figcaption></figure><h3><strong>The Devil</strong></h3><p>After all T̶h̶e̶ ̶D̶e̶v̶i̶l̶ The Scrum Master came and explained to me what already happened and what is the true purpose of each of Scrum Event. And it occurred to me in simple words the review is not about showing the product but about getting feedback, the retrospective is about process improvements and planning is about committing how we will increase the value of our product. This is just a simplification, but this conversation showed me how wrong I was when I thought about scrum. This moment was the first moment when I found the point why scrum is a very good framework to deliver products.</p><h3><strong>Empirical learning process</strong></h3><p>Sprint Retrospective, Sprint Planning, Sprint Review, Daily Scrum, Product Owner, Sprint, Product Backlog… The worst thing wasn’t to remember those terms but to understand what is the idea that stands behind each of them. After some time, I realized that the fundamental and essential moment of getting into the scrum process is experiencing it on my own. Without that, it’s impossible to say that it’s not working.</p><p>For me, the time when I experienced scrum was like going back to my childhood. Ask questions. Break all the pieces and understand all the stuff myself with the big help of Scrum Master.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*gL8AlN3sSbctxFtU" /><figcaption>Transparency, inspection, and adaptation</figcaption></figure><h3><strong>The Lesson I’ve learned</strong></h3><p>The exaggerated scrum hell can be a very nice, warm place where I can sit comfortably with my laptop and jump into a deep flow of coding our product! In this process, I feel comfortable, and I know that there are many mechanisms for checking if the product and the team are on the right path. I know that I have the break, that I can pull anytime when I feel that we need to stop, recognize what is going on, and maybe take a step back.</p><p>That feeling gives me the courage to experiment and try a new way of working. It makes me focused on developing the product and making it as valuable as it can be. Building these boundaries makes our product adaptable to market, minimalizes the risk of failure, and decreases my stress level.</p><p>But the biggest lesson that I’ve learned is that sometimes failure is the best thing that can happen, and it can save a lot of money, effort, and misunderstandings.</p><p>And it’s a very big challenge to create an atmosphere where admitting a failure is not a shame but another opportunity to make a product, process, or ourselves better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=748b2a1907c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/scrum-adventures-of-a-junior-developer-748b2a1907c7">Scrum adventures of a junior developer</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS testing — 4 crossroads technique — Part 2]]></title>
            <link>https://medium.com/vattenfall-tech/ios-testing-4-crossroads-technique-part-2-3809ac46db98?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/3809ac46db98</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Krzysztof Brawański]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 14:21:03 GMT</pubDate>
            <atom:updated>2022-01-05T18:33:29.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS testing — 4 crossroads technique — Part 2</h3><p>This is the second part of the two-part series. The first part is:</p><p><a href="https://medium.com/vattenfall-tech/ios-testing-4-crossroads-technique-part-1-a842ce11795">iOS testing — 4 crossroads technique — Part 1</a></p><p><strong><em>Credits to </em></strong><a href="https://medium.com/u/42a025d4c6c4"><strong><em>Jacek Gzel</em></strong></a><strong><em>, co-creator of the series.</em></strong></p><h3><strong>Stage 2 — View’s actions</strong></h3><p>In the second round, we want to focus on creating view actions and dynamically changing data depending on the state of the station. For this purpose, we will use a view model that will preserve the state of our stations for us. Firstly, the view model will be responsible for orchestrating the station data and providing information to display. The view model, on the other hand, will be used to handle user actions. As in the first round, our work will be test-driven, so we are going to add a test case to it before implementing the activities. Are we going to write those unit tests again? No, we will test more than just make sure the element is visible on the screen. This time we will focus on testing the integration between the view model and the view. We will verify that user actions are affecting the view model data and that the view is re-rendered when the view model is changed. The integration test will work perfectly in this scenario.</p><p>In this scenario, we will use a new test structure function — <strong>context</strong>. The context will be used to precisely define what scenario we will be testing in, to keep our tests even more readable. Check out an example below in which we are splitting our test between two situations — when the station is in an available state and charging state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*7ZWaQhgCOsn7txNJuK0jag.png" /></figure><p>Let’s move on to our first integration test. Consider a scenario where the user clicks a button to start charging the electric vehicle. What are our expectations? We want our station to start charging and to display it in view correctly.</p><p>Firstly, we are going to add a new <strong><em>describe()</em></strong> function to create space for new assertions. In the <strong><em>beforeEach()</em></strong> function we are going to simulate the user’s click by calling the tap method on the start charging button. Finally, we are ready to create some test cases with our expectations. In the first step, we can check if the station image is changed to the charging one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/242a99c24e07dd59ed83d65fb037311c/href">https://medium.com/media/242a99c24e07dd59ed83d65fb037311c/href</a></iframe><p>To make our integration test pass, we need to introduce the view model, which we mentioned before. The view model will have information about the station state and will be able to manage the state of the station, which is necessary to handle user clicks. Simple implementation of view model below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28824b4ef0197873601061d3aa71b2dd/href">https://medium.com/media/28824b4ef0197873601061d3aa71b2dd/href</a></iframe><p>For now view model takes station state from the init method. This will allow us to create different view model states for testing purposes. Station state is published to view.</p><p>The next step is to inject our view model into view and mark it as an observed object, so the view will react to view model changes. Finally, we are going to add a condition that will decide which station image should be displayed. Last but not least is button action. Without it, our test case will still not pass, because the station state will not be changed by the view model. Let’s add button action!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b584bba45b1d4bfb375bf1a383cd77b4/href">https://medium.com/media/b584bba45b1d4bfb375bf1a383cd77b4/href</a></iframe><p>We are ready to run our integration test again. This time test is passing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*5j0krq_XkM2cXqUtEwJKig.png" /></figure><p>The next step is to implement the rest of the changes, like changing the status of the station with description and button label. When everything will be done our test should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*1cbt_G7lcEsX6hM8ZvV8tg.png" /></figure><p>In this short example, we introduced the view model which is capable of station state management and view, which is ready to react to changes. Additionally, the user can start charging on his/her charging station to get the vehicle ready for the tour. The most important is that we are sure that, everything is working fine in our application. How cool is it, huh?</p><h3><strong>Stage 3 — API integration</strong></h3><p>In this round, we should have view with a view model able to hold a state that can be changed by the user. Now is the time to communicate with external API or other data sources to get and store some data.</p><h4>Service building block</h4><p>To achieve the goal we need to introduce a new building block which is service. In our approach service is an abstract layer that allows us to play with data and actions that should be handled somewhere else eg. in a storage system, API, or so on. Services separate business logic from technical details, so generally it unlocks us to be more focused on behaviors and writing good tests instead of thinking about how to connect to the API, what headers should be used, and so on. The biggest value is that we can change the implementation without touching the business logic, so for example we can connect to a new API, change storage system, and so on without the need of changing our test cases. One could ask, what about testing concrete implementation, and of course, this is a valid question, nevertheless in this article, we are going to focus only on core/business logic scenarios. In real development, You could consider how to approach this topic. One solution might be the usage of a mock in-memory HTTP server that launches only in tests and gives some responses. Another, that we chose, is to test it only manually.</p><h4>Technologies — Cuckoo</h4><p>Behind the funny Cuckoo name, we can find a really powerful tool that can help us mock dependencies that we are not going to test or rather test only interactions with the dependency without taking care about the concrete implementation. So, for instance, we can use it to inject some test data and not necessarily read it from real API or we can check if a particular function that is responsible for eg. Sending data to backend was invoked with correct data when the user taped button.</p><p>Before writing the test Cuckoo requires some configuration. We need to set up the compiler to use the Cuckoo command line tool to generate mocks and stubs. Unfortunately, it is the biggest disadvantage of this library in our opinion, because requires maintaining an additional file with a list of Swift files that should be used to generate mocks. However, is not the problem with the library but rather with the Swift language and lack of proper reflection in this language. Authors of the library described it as:</p><blockquote><em>“Unfortunately Swift does not have a proper reflection, so we decided to use a compile-time generator to go through files you specify and generate supporting structs/classes that will be used by the runtime in your test target.”</em></blockquote><p>Nevertheless, it is still more profitable to maintain one file instead of writing mock manually for every protocol that You need for the test. In this stage, we are not going to add new test cases because almost all cases should be defined in previous stages. Here we would like to refactor existing test cases to ensure that charging station data was read from service and request, when the user taps the start/stop charging button, was passed to the service with correct data.</p><h4>Create service and refactor tests</h4><p>In the first step, we need to rebuild the view model to load data from the service. So let’s define service and generate mock.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3cfff1d253987f596702cb2f5b448d8/href">https://medium.com/media/f3cfff1d253987f596702cb2f5b448d8/href</a></iframe><p>Add a new service to the script which generates mocks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c95c91244de2844779a831b0d6f6384/href">https://medium.com/media/9c95c91244de2844779a831b0d6f6384/href</a></iframe><p>And refactor the first test case to allow injecting service into the view model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/525459c64614dddc68bcc008cff6edd8/href">https://medium.com/media/525459c64614dddc68bcc008cff6edd8/href</a></iframe><p>Let’s examine what is done here. So cuckoo command line tool is based on script generated mock of the service. Now we can create a new instance of the mock, define stubs on it and eventually inject it into the view model. Generally, in this step, we are going to teach our mock how it should behave. So we are saying when method <em>loadStation()</em> will be invoked on mocked service it should publish object with charging station in a free state. Here You can also find examples of how to handle Combine in tests. Method <em>loadStation()</em> returns <em>AnyPublisher&lt;ChargingStation, Never&gt;</em> to satisfy this requirement in test we created <em>CurrentValueSubject</em> with the charging station data. When the test case is launched with prepared stub in such a way, every time if there is a request to load station, the production code will get our test data.</p><h4>Verify service interactions</h4><p>Above we covered the topic of how to provide test data to the code now let’s focus on a slightly different topic. We would like to verify if the method <em>save()</em> was invoked with correct data. For this purpose, we can use <em>verify()</em> method delivered by Cuckoo and <em>ArgumentCaptor</em> structure.</p><p>First of all, we need to define the mock for save method that is doing just nothing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5716a072bee0213f204afc77b68de2ff/href">https://medium.com/media/5716a072bee0213f204afc77b68de2ff/href</a></iframe><p>Then we need to define empty argument captor. It should be defined in scope when we are testing interaction with the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/555fcfff864e9a69d285f6e285dc65f1/href">https://medium.com/media/555fcfff864e9a69d285f6e285dc65f1/href</a></iframe><p>Eventually, we are ready to verify interactions and data captured</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31d8b9257d770cc4e72c8d1b7a3757f9/href">https://medium.com/media/31d8b9257d770cc4e72c8d1b7a3757f9/href</a></iframe><p>Verify method is an interesting structure, We can use it to check how many times a certain method was invoked by production code, and also in the same line, we capture arguments and then write expectations for captured values. Worth mentioning is that if You don’t need to capture arguments You can use generic methods like <em>any()</em>, <em>anyString(),</em> or so on provided by the Cuckoo framework to just ensure that the method was invoked with the expected argument type.</p><h3><strong>Stage 4 — User interface experience</strong></h3><p>In the last three steps, we managed to create an application that has all the necessary view elements, can respond to user actions, and has a connection to the backend application from which it derives data. We only miss one thing — the appearance of our application. We must admit that the current design will not satisfy our users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*kYsIFyVCmKfHGZ1Ecd1ksg.png" /></figure><p>In the last and fourth steps, we want to focus on the styles of our application. Perhaps you are wondering why we are doing this now? We prefer an approach in which we focus on the functionality of our software rather than the appearance of the application itself.</p><p>This time, styling the view will not affect the test cases. We will not prepare tests for application styles. Why? If we tested all styles given to our view individually, we would reach the point where every change of color, padding, etc would force us to change the test. To make the styling of the application very heavy and long-lasting. Imagine a situation where a UX designer says to redo the view a bit. We change font sizes, create a new view structure, and introduce new colors. Suddenly 30 tests stop working. Do not do this!</p><p>I think it is better to test the functionality of the application and whether all elements are displayed to the user. This should be enough for us and ensure that we are working properly. Thanks to this approach, changes to the tests will only be required when we change the operation of our application.</p><p>So how do we test our views? We put styles into our application and run it to see what it looks like, just. Style, run, repeat. So let’s go to work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*74iHoVVWl7z5wfOYCDDCfw.png" /></figure><p>After adding a few styles to our application, the view of the station is much more pleasing to the eye.</p><h3>Summary</h3><p>4 Crossroads Technique could bring benefits to Your codebase but remember that in the development process there are no golden hammers, and the best approach is just a compromise. Here is similar, we described just some foundations that You can adopt to Your field. In some cases, it might bring more benefits if You merge some steps or just change the order. So don’t hesitate to play with this method and tweak it to Your needs to achieve the best performance.</p><h4>Links</h4><p>Cuckoo — <a href="https://github.com/Brightify/Cuckoo">https://github.com/Brightify/Cuckoo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3809ac46db98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/ios-testing-4-crossroads-technique-part-2-3809ac46db98">iOS testing — 4 crossroads technique — Part 2</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS testing — 4 crossroads technique — Part 1]]></title>
            <link>https://medium.com/vattenfall-tech/ios-testing-4-crossroads-technique-part-1-a842ce11795?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/a842ce11795</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Jacek Gzel]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 14:18:35 GMT</pubDate>
            <atom:updated>2022-01-05T18:07:51.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS testing — 4 crossroads technique — Part 1</h3><p>This article is the first part of two. The second part is:</p><p><a href="https://medium.com/vattenfall-tech/ios-testing-4-crossroads-technique-part-2-3809ac46db98">iOS testing — 4 crossroads technique — Part 2</a></p><p><strong><em>Credits to </em></strong><a href="https://medium.com/u/505c4816836c"><strong><em>Krzysztof Brawański</em></strong></a><strong><em>, co-creator of the series</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E3C2A9dVqMnWvr0FebqWoA.jpeg" /></figure><h4>Long story short — why we created this article</h4><p>In Vattenfall, we are working in a cross-functional team responsible for the whole smart-charging electric vehicles feature. We have started doing backend development in the JVM world, then we have been doing the frontend part eventually, it turned out that our business required also the mobile app.</p><p>So, we’ve started iOS development from scratch. Our main idea was to keep quality standards that we followed in other technologies, so we were looking for good documentation of testing on iOS. However, we quickly figured out that there is not any complete documentation on how to test the iOS app. We spent days experimenting with frameworks and approaches. Eventually, we found the best compilation of test frameworks that allow us to write code in the “Behavior/Test Driven Development” way, and in this article, we would like to share with You our experience.</p><h4>Why testing iOS is important for us</h4><figure><img alt="Google search why iOS developers don’t write unit tests" src="https://cdn-images-1.medium.com/max/904/1*IOP1ZivV4_c4sgeyknUwNA.png" /></figure><p>Probably many of You have heard opinions about iOS developers that they don’t write unit tests, and for sure many of You would disagree with such hurting opinion because You are real test fighters (kudos for You). However, it could be something bigger than just an ordinary rumor, because we have started iOS development in a project without tests. We were wondering why there are no tests, and one of the possible answers could be that the views were implemented in Storyboards. And only those, who have ever tried to write lightweight tests for Storyboards know, how difficult this task is. So, in this article, we are going to describe only the approach for SwiftUI because in our opinion this is the only way how to write lightweight, focused-on behaviors, tests in iOS.</p><p>You could ask why we need unit tests though? And it would be a nice idea of a separate article or even a whole series. But to not leave questions without answers let’s look at our main drivers.</p><ul><li>Future code changes/refactors are safer and easier to conduct.</li><li>Less code to write (just as much as is required to pass the test) so, building a codebase is easier to maintain in the future.</li><li>The solution is tested against corner cases, which are difficult to reproduce in manual tests.</li></ul><h4>4 Crossroads Technique — foundations</h4><p>Our approach is based on 4 rounds of Test Driven Development (TDD). Every round You are focusing on a different scope like static view, view’s actions, API integration, and user interface experience. The goal is to have after four rounds of coding a decent view integrated with API that users can interact. This approach we called the 4 Crossroads Technique. This fancy name came to our minds because we compared the TTD technique to street lights RED GREEN REFACTOR(orange) and every round to different crossroads. So, if You want to deliver a new view to the user You need to travel through 4 crossroads. The approach also fits with the pair programming technique. You can adapt it as You like eg. change each other every TDD round/stage or crossroad.</p><h4>A few words about code examples and context</h4><p>We created a small app that displays a simple view of the charging station that gives the possibility to interact with users by starting or stopping the charging sessions. So, the use case is user comes to the charging station, connects the car, and uses a mobile app to start the charging session. When the car is charged, the user can stop the charging session. We use an abstract layer of HTTP API because we would like to focus on behaviors in the app (business cases) not the infrastructure that might be additionally tested as well with mock HTTP servers or manually.</p><p>All code is available on GitHub. There are PRs for every stage so You can easily switch between them and check what are the differences.</p><p><a href="https://github.com/jgprogram/iOS-charging-station-testing">GitHub - jgprogram/iOS-charging-station-testing</a></p><h3>Stage 1 — Static view</h3><p>In the first round, we want to focus on creating a simple static view, without any actions, dynamically changing data or so on. Our work should be driven by tests, so before adding a new element to the view like <em>Text</em> or <em>Button</em> we will create a unit test case for it that doesn’t pass, and then we will satisfy it by adding an appropriate view element. We are following this way until each required UI element is shown on the screen.</p><h4>Technologies</h4><p>At the very beginning, we would like to briefly discuss the frameworks we will be using in this stage. Let’s start with Quick. Quick is a behavior-based programming framework for Swift and Objective-C that has a clean, self-explanatory syntax so you can write tests easily. Quick comes in conjunction with Nimble — a matcher framework for your tests. These two can do a great job and make your testing very enjoyable. Last but not least is ViewInspector. ViewInspector is a library for unit testing SwiftUI views. It allows for inspecting a view hierarchy at runtime providing direct access to the underlying View structs.</p><h4>BDD test structure</h4><p>Here is a short example of the test structure with setup of initial view and check if the correct label is shown. We are using Behavior Driven Development (BDD) so the description is very verbose and could be read by a non-technical person as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06c52f14022ab3bc0523794cfd097535/href">https://medium.com/media/06c52f14022ab3bc0523794cfd097535/href</a></iframe><p>Now let’s spend some time understanding all elements.</p><p>The <strong><em>describe</em></strong> function is used to group related test cases and define a scope. Usually, each test file has one at the top level. The string parameter is for naming and will be combined with test cases to form the full name of the test. If you name them correctly, your specifications will be read as full sentences in the traditional BDD style.</p><figure><img alt="Example of BDD test description" src="https://cdn-images-1.medium.com/max/550/1*ds1RMuBDMJZm9ff-_nyOvQ.png" /></figure><p>The <strong><em>it</em></strong> function defines a single test case. The body should contain one or more expectations that test the state of the code. In our approach, <strong><em>it</em></strong> is the smallest atomic unit in the structure. So generally, we have one expectation per <strong><em>it</em></strong> or there could be more only if there is a strong connection between them. Why do we keep such rigor? Because we would like to have a verbose and accurate message when a test case fails. If there are one or two expectations, it is easy to figure out what failed. Also, during refactor or code changes you have a detailed list of what doesn’t work.</p><p>Expectations are built with the function <strong><em>expect</em></strong> which takes a value, called the actual. It is chained with a matcher function, which takes the expected value. If getting actual value requires more actions like invoking ViewInspector it should be moved to the separated function that returns the correct value. The benefit is that if You are refactoring the view You don’t have to adjust every test case, only one function, responsible for seeking elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06530e2eaa605ef5bb9083b5c69d7b8f/href">https://medium.com/media/06530e2eaa605ef5bb9083b5c69d7b8f/href</a></iframe><p>The <strong><em>beforeEach</em></strong> function is called before each <strong><em>it</em></strong>. We use it to create a view, set up all dependencies, and simulate the state for test context. Creating the SwiftUI views is very cheap so we can afford on creating a new view with dependencies before every test case, in runtime it takes only a few milliseconds per unit and brings the benefit that every test case is atomic and doesn’t have an impact on others, literally You can say that each test case has own runtime sandbox.</p><h4>Test first and see the view</h4><p>So now equipped with some knowledge let’s start our development. Following the TDD approach first, we need to create the specification and implement the first test case where we expect the station’s image on view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35587ea98e3de25baf574a934216ce7a/href">https://medium.com/media/35587ea98e3de25baf574a934216ce7a/href</a></iframe><p>To achieve the goal we are defining <em>ChargingStationView?</em>. The view might be empty because we are going to instantiate it afterward in the <em>beforeEach</em> section, just to have a new fresh instantiation for each test case. Eventually, we create well-described expectations. Seeking view element logic is moved to the private function <em>chargingStationImage()</em> because of two reasons. First, the expectation is more verbose, and second, it allows us to map the outcome from <em>ViewInspector</em> into an optional <em>String</em> value that contains the name of the image. That move helps check if the image is visible.</p><p>When the test case is done we need to write minimal code just to allow build and see the red stage. Generally, it means that we need to create <em>ChargingStationView </em>with empty <em>VStack</em> in the body and launch the test. This stage seems to be silly but it shows that our test case is valid and can be launched.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec423fb557b74d3071dc73b9721b4e1/href">https://medium.com/media/eec423fb557b74d3071dc73b9721b4e1/href</a></iframe><figure><img alt="Red stage in TDD" src="https://cdn-images-1.medium.com/max/1024/1*0bfVZNCsaPLPTOAxzuOFng.png" /></figure><p>Now is the time to write some code to satisfy our test case. According to the TDD rules, we should use minimal effort, just to have the green state as soon as possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dee5d425d68ec1dfbcfaa5bbc551c8dd/href">https://medium.com/media/dee5d425d68ec1dfbcfaa5bbc551c8dd/href</a></iframe><figure><img alt="Green state TDD" src="https://cdn-images-1.medium.com/max/428/1*-BwUaMCW5bIA4-DgYEF83g.png" /></figure><p>Now we are repeating the steps above until we have all elements on the screen.</p><h4>Appendix — how to seek view elements</h4><p>There are two ways of seeking view elements. The first one is done by using indexes of elements in the view hierarchy. In the below example, we are getting the value of <em>Text</em> struct which is placed in <em>VStack</em> at index 1 (At index 0 is an image of charging station). This solution is very prone to changes of view under tests. If we change the order of elements we will need to adjust indexes in our private methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26161b0b975f1f9e8310d522f2401808/href">https://medium.com/media/26161b0b975f1f9e8310d522f2401808/href</a></iframe><p>The second way of seeking is dynamic search. You can query for a specific view with <em>find</em> or <em>findAll</em> to get an array of all matching views of a given type. In this case, we can adjust the order of elements in view under test and this function will return still the same <em>Text</em> struct. The function below should find the first view of type <em>Text</em>, so we don’t have to care about views of different types like <em>Image</em> which is placed at index 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06530e2eaa605ef5bb9083b5c69d7b8f/href">https://medium.com/media/06530e2eaa605ef5bb9083b5c69d7b8f/href</a></iframe><p>When seeking specific elements of the view under the test, such as <em>Text</em> or <em>Button</em>, we recommend using a dynamic search. Thanks to this, our tests will be more resistant to all kinds of changes in the tested views and it also ease our job in the next stages.</p><h4>Summary</h4><p>In this article, we covered 4 Crossroads Technique foundations and we described the first stage (crossroad). In the next article, we will describe the remaining 3 stages.</p><p><strong>Links</strong></p><p>Quick — <a href="https://github.com/Quick/Quick">https://github.com/Quick/Quick</a><br>Nimble — <a href="https://github.com/Quick/Nimble">https://github.com/Quick/Nimble</a><br>ViewInspector — <a href="https://github.com/nalexn/ViewInspector">https://github.com/nalexn/ViewInspector</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a842ce11795" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/ios-testing-4-crossroads-technique-part-1-a842ce11795">iOS testing — 4 crossroads technique — Part 1</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 Things I Learned at Vattenfall]]></title>
            <link>https://medium.com/vattenfall-tech/6-things-i-learned-at-vattenfall-9f6fe67fe939?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/9f6fe67fe939</guid>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[company-values]]></category>
            <category><![CDATA[career-development]]></category>
            <dc:creator><![CDATA[Paweł Pluta]]></dc:creator>
            <pubDate>Thu, 27 May 2021 08:55:53 GMT</pubDate>
            <atom:updated>2021-05-27T08:55:53.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAsdeFznSZhJXNSSoHjPrg.jpeg" /><figcaption>Photo of Katowice by <a href="https://pixabay.com/pl/users/marcelwojcik-14557601/">MarcelWojcik</a> from <a href="https://pixabay.com/pl/photos/katowice-noc-night-polska-4682299/">Pixabay</a>.</figcaption></figure><p>A few years back, I was thinking about myself as a highly skilled software developer, which is underestimated and works below his qualifications. I decided to change company and started to work for Vattenfall IT Services Poland, and I could not be more wrong about my skills.</p><p>In this article, I will share my thoughts about working there for over three years. Today I am no longer working for Vattenfall, so this is more like a retrospective and, I hope, a little guidance for you regarding your career. You will not find any metrics or raw data about my personal growth. It is rather a light read with my personal thoughts. Take a cup of coffee and enjoy!</p><h3>Seek people better than you</h3><p>There is a mathematical joke known as “a claim of local geniuses”, which states that “for every mathematician, there is an environment in which he is most outstanding”. I think it may be transferred to any area. Around four years back, I thought that I’m highly skilled — not outstanding, but good enough to be way better than an average developer. First weeks at Vattenfall I was pretty convinced that this is true, but then I started to cooperate with other people. Suddenly my self-esteem was questioned, as their skills showed me, how wrong I was.</p><p>More amazing was that they were not bragging about their skills. People there were very keen on sharing the knowledge, guiding me and give advice. There was no mentoring program, and I think there was no need for such. Mentoring programs create a relationship in which one person is dominated by the other. In this case, it was more like cooperation, where we were challenging each other. Don&#39;t be afraid of admitting that you are not the best one, and look for people who may guide you to become better. If there are no such people, start thinking about some change or you will not develop yourself.</p><h3>Extreme programming on everyday basics</h3><p>Not talking here about TDD, that’s something that I find is a must for something more complex than a few lines of bash script. We were <a href="http://www.extremeprogramming.org/rules/pair.html">working in pairs</a>, which is great in the matter of knowledge and experience exchange. It also improves code quality, causes fewer comments during code review and limits the bus factor risk. Occasionally, while crashing a bigger feature, we used <a href="https://www.agilealliance.org/glossary/mob-programming">mob programming</a>.</p><p>Another habit that I had to get used to, was to switch from “big releases” to everyday ones. At first, this was stressful due to the tension related to releasing the application that I remembered from previous jobs. Often releases, backed by solid automated tests, are giving you the confidence to release and deploy the application. Releasing small changes reduces the stress, as there are not so many things that can break the application. In the end, we were <a href="https://www.atlassian.com/continuous-delivery/continuous-deployment">releasing automatically our services</a> multiple times a day — after every merge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1h9Jb0mAjyWce_JpLxkLUA.jpeg" /></figure><h3>Be responsible for your tools</h3><p>Nowadays it sounds weird to me when someone says that he needs to ask the manager/architect/anyone on a higher level when he wants to use some library or tool. When you as a developer are going to be responsible for an application, maintain it and develop, you should be able to choose the tools that will allow you to do that effectively.</p><p>In the first weeks at Vattenfall, I was working on a project that was made as PoC, and was needed to be developed into a mature application. There were no unit tests in the code at all. I decided to change that, I was collecting the arguments and data for writing them for a few days. When I felt ready, I went to talk to my manager and said “I want to introduce unit tests into a project”. I expected to have a long discussion with him about why it is beneficial. Instead of, I got a short answer: “OK”. It took me minutes to lift my jaw off the floor, as that was nothing I was used to.</p><p>This situation was very memorable for me. Giving developers the trust in their skills by something so simple as letting them choose the technology they want to use, makes them feel that they have an impact.</p><h3>Bottom-up initiative</h3><p>After few months in the company, I started to look for a more challenging project. There was one team that I really wanted to join, as they were using new technologies and their work was fascinating. After few talks by the coffee machine with the team members I decided to ask their Product Owner if he is willing to accept me. His answer was “if the team is fine with it, then I’m also fine”.</p><p>It was a clear signal, that the developers, who are going to work every day with a new team member should make a choice. Managers usually do not work with them on daily basics but rather ad-hoc. In case of communication issues, they will not be impacted so hard as the coworkers. It is very valuable to take the initiative by the team members, and not hesitate to talk with management about new ideas.</p><p>Another situation where bottom-up initiative produced good results, apart from selecting your new team members, was the recruitment process for a new manager. We selected a representative of each team that the new manager will be responsible for, and we, as developers, interviewed the candidates. That let us work with a person that we liked and knew that cooperation will be successful.</p><h3>Business people are valuable allies</h3><p>Since 2011, when I started my career, I had an opinion that the developer role is to produce code. Maybe also do a little bit of documentation. That&#39;s all. I was happy when the business analyst or manager gave me a clearly defined task, where everything was already agreed with the customer. I did not have to discuss anything with them. It was pretty often that later the customer was requesting changes as implemented feature was not exactly the thing that was needed.</p><p>Shortening the distance between business people and developer gives you a unique opportunity to have an impact on the solution. Everyone in the communication chain — the customer, an analyst or manager wants to make your work easier. That is nice but causes a lot of valuable information to be hidden from you. It impacts the solution you create and makes, as it is harder to introduce fixes or changes at a later stage. Just think about all the times that you designed a “perfect solution” for some problem, but later the customer wanted to change it because it was not working in the desired way.</p><p>Allowing the developers to consult the customer reduces the number of misunderstanding. You, as a developer, start to better understand the domain, which allows you to prepare better and simpler code. The customer on the other hand feels well cared for and understood. Together you are starting to <a href="https://martinfowler.com/bliki/UbiquitousLanguage.html">use the same language</a>. Shortening the distance between business and developer allows you to suggest other solutions than the ones that customers thought. You just have to leave your comfort zone and talk with them.</p><h3>Tackling the problems with event storming</h3><p>For the first time in my life, I was able to see another way of gathering requirements other than sitting in a room with a customer and asking questions like “what the application should do for you?”. <a href="https://www.eventstorming.com/book/">Event storming</a> answers that question in a very effective way. It engages everyone to work by giving them sticky notes that easily model the processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sX7UkRZLQw_ZBC9vMXhWPw.png" /><figcaption>Result of first few hours of event storming. Cooperation with business people can also be fun!</figcaption></figure><p>The joke about the customer not knowing what they want is no longer fun for me. It is your role, as a developer, to tell the customer, what they want. By understanding the business they are running you can help the customer understand his needs. You can help spot the places in the process that causes the most money loss, tackle it into a set of small problems and solve it. Believe me or not, but seeing the joy on the business people faces, when they realize what is the problem in the process is priceless.</p><h3>End of my work</h3><p>I left Vattenfall IT Services at the end of April 2021 in pursuit of challenges. Working in the company gave me a huge knowledge boost and changed my mentality. I learned that engagement of the team pushes them into delivering awesome stuff. Moreover, now I find that having an impact and being responsible for the solution at the same time is making the team engaged — not the other way.</p><h4>Personal thanks</h4><p>At this point, I’d like to say thanks to the people I’ve met and who helped me develop myself. Starting with my managers, Tomek and Kamila for pushing me forward. Sven, Abel and Mark, the Product Owners for putting trust in the teams. Marcin, the Agile Coach for questioning our approach, and most important, Mobile and The Forehand teams for great discussions, not only technical ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f6fe67fe939" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/6-things-i-learned-at-vattenfall-9f6fe67fe939">6 Things I Learned at Vattenfall</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tell, don’t ask —  learn to talk to your objects]]></title>
            <link>https://medium.com/vattenfall-tech/tell-dont-ask-learn-to-talk-to-your-objects-45d7c4aa61fe?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/45d7c4aa61fe</guid>
            <category><![CDATA[kata]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Paweł Pluta]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 14:51:46 GMT</pubDate>
            <atom:updated>2021-02-02T19:20:54.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tell, Don’t Ask — Learn to Talk to Your Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoUPg_phB7S1qWAlkEYrBQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/pl-pl/zdjecie/osoba-dowodzaca-grupa-mezczyzn-279991/">Pixabay</a> from <a href="https://www.pexels.com/">Pexels</a>.</figcaption></figure><p>Modifying data in a class where they reside is always a good thing. The Tell Don’t Ask principle guides us on how to follow such an approach. Unfortunately, it is widespread to obtain data from object and process it inside some service or manager class. After this article, you will know how to talk with objects and process data inside them instead of pulling their logic out of objects. You will be able to test your new skill with kata exercise.</p><h4>Benefits of Tell Don’t Ask principle</h4><p>At the first glance, obeying the Tell Don’t Ask principle might look like a cosmetic change for the code. In fact, it provides a lot more than just a simpler, less coupled clean code. By following this principle, you will follow OOP with ease by:</p><ul><li>The localisation of information — everything related to the object will be kept in one place — its data, ways of modifying it, its flow and ways of processing it</li><li>Limited code duplication, as operations with objects data will be kept in one place. You will not have to keep an eye on DRY principle, as it will be implemented naturally</li><li>Strong <a href="https://medium.com/vattenfall-tech/the-oop-has-been-explained-wrongly-to-me-db8e36f91bb2">object-oriented approach</a>, with a focus on abstraction</li><li>Simplified unit tests. Instead of preparing heavy service classes to test data processing, most of your code could be tested with lightweight unit tests</li></ul><h3>A little bit of theory</h3><p>The Tell Don’t Ask is about <a href="https://martinfowler.com/bliki/TellDontAsk.html">keeping the data where it belongs</a> — encapsulated inside the object. Encapsulation should prevent us from modifying object internal state without it knowing that. Modifying the object state with setter does not guarantee that, as such the object lacks abstraction. Service classes digging in objects internals are like trying to eat by putting food directly to your stomach, instead of putting the food into your mount.</p><p>The sample application used here will simulate a small farm, that has only a few responsibilities. The first task that it will fulfill is to water plants when they need that. The second will be gathering products from the plant, when they are ready, and the last one is to deliver packed products to the customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DicnchfRdLFPChrQ.png" /><figcaption>Sample service managing the data kept inside the objects.</figcaption></figure><p>With such an approach, we do not give objects any privacy. Tearing out their internals violates OOP and complicates the service logic. Let’s think about how we can refactor it to obey Tell Don’t Ask principle and achieve a clean code. Try to find the logic that has been taken out of classes. Spot for the places, where some decision is made. Found it? The first step would be to tell the Plant to water it using some WaterValve, instead of service doing that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*p66NpryG8QH9sCnT.png" /><figcaption>Tell don’t ask principle used to refactor code to more object oriented one.</figcaption></figure><p>By telling the Plant to water it with some WaterValve, we encapsulated its logic inside the class. We do not need to make condition outside of the Plant class, which simplifies service testing by reducing the number of interactions between objects and possible execution paths. Let&#39;s take a look into the practice.</p><h3>Modelling it in code</h3><p>Let’s look at the implementation that reflects the first diagram. It is digging deeply into objects internal, fetching plants from RaisedBed and getting internal properties from those plants. If that wasn&#39;t enough, it is implementing plant-related logic, asking the plant for its values and setting new ones, depending on the Plant state. Service has huge knowledge about other object internals.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe00283727361e099657de824aaf1c00/href">https://medium.com/media/fe00283727361e099657de824aaf1c00/href</a></iframe><p>Apart from asking for internal values, it also differentiates the logic depending on the type. Think a little bit about that, how you are going to test this solution? Are you going to check logic for every type of plant? Will you make different tests depending on plant soil moisture? What if there will be no raised bed or valve? Testing every possible path will require a lot of tests. Or, maybe you will decide to take a risk, have bugs and not test everything?</p><h4>Getting hands dirty</h4><p>Consider the same service, but respecting the Tell Don’t Ask principle. Let’s literally tell the raised bed to be watered with some valve, and let it delegate this work to its plants.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c6334493f6fb4052ada20f4a41000d1/href">https://medium.com/media/9c6334493f6fb4052ada20f4a41000d1/href</a></iframe><p>When we applied to Tell Don’t Ask principle, this service simply delegates the request to it. Its only responsibility is to orchestrate invocation and manage the repositories. Testing it will only limit to the integration with repositories, while logic that used to be in it can be checked easily with unit tests. You might struggle, where the logic is now? Take look at a part of refactored RaisedBed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c280cafe50e4dbde50f6cd22d7efec2/href">https://medium.com/media/3c280cafe50e4dbde50f6cd22d7efec2/href</a></iframe><p>Again, using Tell Don’t Ask, we are not using the internals of Plant in here - we are only managing specific plant watering, but we let the plant decide if it needs one. Again, there are not many cases to test in here, so writing unit tests should be easy. The next step with this refactoring will be to include the watering logic inside the plant itself. You can consider introducing a Strategy pattern to simplify logic even more.</p><h3>Dealing with dependencies</h3><p>Sometimes, to perform an action, you will need to call another service. In our application, this is a situation when we sell products. Plants after gathering are organized into crates. Crates can be packed for the customer, and such a package can be sent to it. However, sending a package is managed by another service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe324f0d9a5445f86e68f66d62e518b8/href">https://medium.com/media/fe324f0d9a5445f86e68f66d62e518b8/href</a></iframe><p>There are two most common approaches to refactor that into code obeying Tell Don’t Ask principle.</p><h4>Service orchestrating invocation</h4><p>The first discussed approach relies on a service (Sales in this case), that has the knowledge about that when the Package should be sent. Sales service is an orchestrator for the process. In this case, we simply pass the package to the delivery service so it will be processed by it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dc9483f8e74b188ba1c1a7b5012f849/href">https://medium.com/media/6dc9483f8e74b188ba1c1a7b5012f849/href</a></iframe><p>For most people, it is natural to code this way, so the benefit of this approach is the ease of understanding this solution. On the other hand, it creates a little bit of coupling between Sales service and a Package class - Sales does need to know when packaging was successful, and when it should be delivered.</p><h4>Disconnected Domain Model variation</h4><p>Disconnected Domain Model is was described in Vernon’s “Implementing Domain-Driven Design” book as a technique of injecting repositories into aggregates. Injecting repositories in every aggregate by constructor may cause problems with dependency injection mechanisms due to a large number of aggregates that should be fed with repository dependency. Instead of that, we might try to pass this dependency directly that need to use some service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32606276db64f98e8a51fd531948fb54/href">https://medium.com/media/32606276db64f98e8a51fd531948fb54/href</a></iframe><p>This technique limits the knowledge of Sales service about Package class implementation, so it simplifies testing of a service. It keeps the whole logic related to Package the inside class. On the other hand, it usually brings confusion to the developer, who is unfamiliar with it. While using this technique, carefully select services that are injected. Using those services only for invoking processing is usually not a threat, but using a value returned from injected service might lead to <a href="https://martinfowler.com/bliki/FlagArgument.html">Flag Argument</a> antipattern.</p><h3>Summary</h3><p>The Tell Don’t Ask principle promotes keeping logic inside objects instead of services. This increases their cohesion, making the code more maintainable and easier to test. Extracting the logic into service makes them unnecessarily big and complex. Try to speak with your objects, and tell them what to do.</p><h3>Code Kata</h3><p>If you feel, like you need some practice in adapting code according to Tell Don’t Ask principle, challenge yourself to do related <a href="https://github.com/pawelpluta/tell-dont-ask-kata">Code Kata</a>. You will find the description in the <a href="https://github.com/pawelpluta/tell-dont-ask-kata/blob/main/README.MD">Readme file</a>. Try to write as much as you can by yourself. There are some unit tests already written, but you will need much more of those. Sample solution can be found on <a href="https://github.com/pawelpluta/tell-dont-ask-kata/tree/sample-solution">this branch</a>, but remember, that it is just a sample, and there are multiple ways of doing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d7c4aa61fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/tell-dont-ask-learn-to-talk-to-your-objects-45d7c4aa61fe">Tell, don’t ask —  learn to talk to your objects</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid Public Keyword In Your Java Code]]></title>
            <link>https://medium.com/vattenfall-tech/avoid-public-keyword-in-your-java-code-b616e2a2993b?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/b616e2a2993b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[abstraction]]></category>
            <dc:creator><![CDATA[Paweł Otorowski]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 05:45:18 GMT</pubDate>
            <atom:updated>2021-02-02T17:10:57.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zg6FafV5ezQ1R3WbKLBC8g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thepaintedsquare">Jessica Lewis</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>After a couple of years working as a software engineer, looking mostly on the Java code, I can now say that many developers overuse public keyword on daily basis.</p><p>There might be many reasons for such an approach like wrongly defined default IDE settings or lack of knowledge of how and why the language was designed. Nevertheless, there is always a good opportunity to take a step back and rethink how to use features provided by the language itself.</p><p>In this article, I would like to show how overusing public keyword, especially in big projects, may decrease the productivity of the team and how to prevent it. Examples will be written in pure Java, so knowledge of any framework is not needed. In the end, you will find a few tips on how to teach the IntelliJ IDEA to follow “no public” rules.</p><h3>Scopes in Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NrPyt9Ue6P5WAOK8aP2oQ.png" /><figcaption>Comparison between the scopes available in Java.</figcaption></figure><p>Default (also known as package-private) will be the main topic in the article. This scope is in opposition to the public, required if any class, method, or field should not be visible outside the package. The name speaks for itself, this is the default scope in Java!</p><h3>Why not public?</h3><p>There is a couple of reasons why I think we should put more attention when it comes to choosing the right scope for our fields, methods, and classes. In this paragraph, I would like you to take a look at the few examples I created based on the code I have seen in the past. They are pretty simple, but I hope you will visualize how painful it may become letting your IDE decide what should be the right scope for your classes.</p><h4>Wrong class organization</h4><p>When everything is public, it is possible to organize all the classes by their responsibility. In the example below, you can find the tree of classes from the project written for some restaurants. There are few packages that describe layers of the application like repository, service or web. In each of these packages, there are classes that fit into them. For example, DB repositories are in the repository package and REST/MVC controllers are in the web package.</p><p>In the beginning, it might seem like a good solution, because with such a packaging strategy it should be easy to find a particular endpoint by looking for the class in the web package or to change the query to another one by looking for the class to change in the repository package. On the other hand, the logic spreads between different places, making code harder to understand, especially when focus only on the particular feature is required. When some new functionality has to be added, each package needs to be analyzed to find the right place to implement it. And of course, these packages contain classes written not only for the new feature but also for many more, so the whole project must fit into the developer’s head when the feature is implemented.</p><p>Please take a look at the example below. Every class that has open the green padlock is public in this project. Adding a new feature to the existing classes requires going through all of them to find the right place. Also adding a brand new functionality to this project requires going through most of these packages or even all of them to put new classes in the right place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQuJKcyUdGixLR3nGE9mTw.png" /><figcaption>An example of the project with packages organized by layer.</figcaption></figure><p>This problem can be solved by creating packages organized by the functionality and treat them as separate modules. Inside them, all the classes should have a default scope. Thanks to such an approach every time adding a new feature will be required, only a single package needs to be touched or a new one needs to be created. It also gives an easier way to extract any functionality out of the project i.e. to deploy as a separate application to scale it or transfer to a different team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqqNT7Ot-sIy8718Zy9YRQ.png" /><figcaption>An example of the project with packages organized by modules.</figcaption></figure><h4>Problem with finding a class</h4><p>Modern Java IDEs prompt a class that needs to be imported just by the name typed in the code. It is a really powerful feature that increases developers’ productivity. Unfortunately, it does not work well when all the classes are public. Especially in huge projects, there is a big chance, that more classes have the same name, and only by the package name, it is possible to discover which one is the valid one in each case. It becomes even harder when there is a bug in the code due to the wrongly chosen class and it needs to be found.</p><p>In the example below, you can find the tree of classes from the project written for some restaurants. This time modules like client or employee are in place, but inside them, there are still classes organized by their responsibilities: model, repository, web and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oC_hccTUzPXbLU75_9mvTw.png" /><figcaption>An example of the project with packages organized by modules with layers as sub-packages.</figcaption></figure><p>Because of such a packaging strategy, it is possible to create classes with the same names. Below there is a prompted list of them that fit the typed part of the class name. As not only employees have an address, but also clients, suppliers, and orders that sometimes need to be delivered, there are multiple AddressRepository classes to select.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hudrxV33yMeA-Rwmvowh6A.png" /><figcaption>An example of class hints to import based on the partial name entered.</figcaption></figure><p>This problem can be solved by keeping all the classes from each module in a single separate package with the default scope. With such an approach every time there will be a requirement to add a new dependency to the class, only classes from the same package will be prompted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyNDUBaW4-OxV-MhmruKoQ.png" /><figcaption>An example of exactly one class hint to import based on the partial name entered thanks to the package-private scope.</figcaption></figure><h4>Spaghetti code</h4><p>By creating a public class, we make it possible to use it anywhere in the project. There is nothing wrong with it, but only if the decision was conscious. The problem starts in a situation when classes are made public, but they should not be. This leads to the moment in which classes written for functionality A are used for functionalities B and C. The problem with mixing concepts makes providing any changes in the project harder, especially when it comes to extracting any functionality outside the module or application. Unfortunately, it is really easy to introduce, because every public class is available in every place in the project. Check the imports section in the following screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mzpEwIx2ShZNIzCSeuFqg.png" /><figcaption>An example of using OrderRepository from package order in the ClientService from package client.</figcaption></figure><p>This issue can be also solved by keeping all the classes from each module in a single separate package with the default scope.</p><h4>Problem with finding a method</h4><p>The beauty of the IDEs is that they prompt methods that are available in the API of the class. This is another powerful feature, used on the daily basis by developers all around the world. If there is only one or even a few methods exposed, there should be no issue with using them. This is in line with Abstraction, one of the most important concepts in the OOP (object-oriented programming).</p><p>The problem starts when methods that are used for the internal purpose and should not be available outside, are also public. This may lead to confusion about which method should be used and decreases productivity. And of course, there is always a chance that such a method will be used outside the class. It may not only produce various bugs but also make further refactoring harder or even impossible to do.</p><p>In the example below there is a lot of methods available in the EmployeeService. Two of them should be public for sure: findBy() and save(). The rest of them seems to be intended to be used only by the public methods of the service itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlmBQ9M1UOKs99WxoBuVjw.png" /><figcaption>An example of method hints available in the API of the EmployeeService class.</figcaption></figure><h3>What if communication between modules is needed?</h3><p>Developing in Java, there might be only one reason to use public in the code - when the point of accessing the module is required. Then the facade pattern can be used to expose any features implemented in the module.</p><h3>Set up IntelliJ to stop putting public keywords everywhere</h3><p>The default configuration in the IntelliJ hides visibility of the classes in the project. It also adds a public keyword in almost every generated part of the code. These few steps can help you to start generating code that is consistent with the Java language design. It might also allow you to see what are the visibility scopes in every class of the package without looking into them.</p><h4>Visibility scope in the project tree</h4><p>By default, there is no overview of the visibility scopes in the project. The first option is to open each class and see its definition. There is also a better way to achieve this with less effort and it works globally. This option is named Show Visibility Icons. You can find it in the dropdown that is available under the settings button of the project window tool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuuZAM8gdWNoJyN1FV4KXw.png" /><figcaption>Dropdown with a selected option that is responsible for displaying the visibility scope of every class in the project tree.</figcaption></figure><h4>Generated classes</h4><p>Every generated class is public by default. It can be easily changed in the IntelliJ settings under Editor &gt; File and Code Templates. To achieve the goal, “public” keyword needs to be removed from Class, Interface, and Enum files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUrutZlgWzxtl_LBky8L0Q.png" /><figcaption>The class template defines that every auto-generated class should have a default scope.</figcaption></figure><h4>Generated constructors</h4><p>Constructors generated by the IntelliJ are public by default. It is configurable in the Code Generation tab that is under the Editor &gt; Code Style &gt; Java settings. Default (package-private) scope is named Package local in that case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfArU9bUr6iwwYdD6OhfHg.png" /><figcaption>Code Generation tab that contains an option to change the default visibility of the generated constructors.</figcaption></figure><h3>Summary</h3><p>The approach I described in this article was not invented by me. It is just a reminder of how the Java language was designed from the very beginning.</p><p>Package-private seems to be a very good scope for every newly created class and method in the project. It raises the decision which of them should be visible in our hands. This gives us an opportunity to keep the API of our classes easier to use and understand for everyone.</p><p>Thanks for reading and see you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b616e2a2993b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/avoid-public-keyword-in-your-java-code-b616e2a2993b">Avoid Public Keyword In Your Java Code</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Up Your Fronted Tests: Part 4]]></title>
            <link>https://medium.com/vattenfall-tech/clean-up-your-fronted-tests-part-4-bf826fc8d134?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/bf826fc8d134</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[jasmine]]></category>
            <category><![CDATA[frontend-testing]]></category>
            <category><![CDATA[karma]]></category>
            <category><![CDATA[page-object]]></category>
            <dc:creator><![CDATA[Stawiarski Jakub]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 12:53:27 GMT</pubDate>
            <atom:updated>2021-09-15T14:50:23.868Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Page Objects to manage complexity</h4><p>This article is a part of a cycle. All parts are:</p><ol><li><a href="https://medium.com/vattenfall-tech/clean-up-your-frontend-tests-part-1-ba4961ec72f9">Why we focus on integration tests for UI components.</a></li><li><a href="https://medium.com/vattenfall-tech/clean-up-your-frontend-tests-part-2-ba4e1dcab893">Tips &amp; Tricks.</a></li><li><a href="https://medium.com/vattenfall-tech/clean-up-your-frontend-tests-part-3-37f656f0e8f7">Reusable testing modules.</a></li><li>Using Page Objects to manage complexity.</li></ol><p><strong><em>Credits to </em></strong><a href="https://medium.com/@paaweel01"><strong><em>Paweł Nowakowski</em></strong></a><strong><em>, co-creator of the series.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3w7F-B8tcsjKJ9smneMkQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@negativespace?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Negative Space</a> from <a href="https://www.pexels.com/photo/grayscale-photo-of-computer-laptop-near-white-notebook-and-ceramic-mug-on-table-169573/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>Issues with raising complexity</h4><p>As the complexity of features you are implementing grows, so will your test files. More and more cases need to be covered, which is fine. What is worse with the number of cases the file will also fill up with a lot of “plumbing” code. You will need more and more references to the DOM elements to simulate user behavior and assert results. This may clutter your test files and make them hard to read.</p><p>If you decide to go with the integration tests route you may <br>also need to build more complex testing modules and pass them toTestBed#configureTestingModule(..). Heavier modules will probably mean there might be more moving parts and dependencies like services you need to observe. This will again make your initialization heavier, and the files will again become larger and harder to read.</p><p>It may also be an issue if you reach a critical mass and decide to split tests<br>for a component into separate files. You will now need to move the initialization logic somewhere to avoid duplicating it.</p><h4>Solving the mess</h4><p>One pattern that could help with splitting up and managing the complexity is the page object. It’s not a new pattern at all, as it is used with multiple testing technologies already. <a href="https://martinfowler.com/bliki/PageObject.html">Martin Fowler has a great write up on it</a>. The <a href="https://angular.io/guide/testing-components-scenarios#use-a-page-object">Angular guide mentions this pattern as well</a>.</p><p>The example shown in the Angular guide would help to move out all the DOM queries out of the testing files. This can be a great improvement already. The queries can be quite verbose, even in simpler cases.</p><p>It does not solve the issue of initialization, as the page object accepts an instance of a ComponentFixture. You still need to configure a testing module and call the TestBed.createComponent(..) somewhere.</p><p>A solution to that could be to use a static factory method. Such a method could configure the testing module, create the component to test and return a Page object that allows the tests to interact with it.</p><h4>Example</h4><p>Say we are implementing a simple component called (quite verbosely) the number selector. It should be something simple, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*4GOh7sX4j9zdf6IJY9rp5Q.png" /></figure><p>Of course, this is a very simple component, so implementing a page object is probably overkill. Let’s still do it, as even in this case you should ask questions like:</p><ul><li>Should there be any initial value?</li><li>Should the value go below zero?</li><li>Should it go below some specific minimal value?</li><li>Can the user click the value and type it instead of clicking the buttons?</li></ul><p>The more of those you will need to implement, the more test cases you will need.</p><p>First, let’s create a method that will configure the testing module and create the page object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4946f5ed474ebd585cb83a9d27e3817/href">https://medium.com/media/f4946f5ed474ebd585cb83a9d27e3817/href</a></iframe><p>Note, that the method has been marked as async. That is because the TestBed#compileComponents() is asynchronous too, and we may need to wait for its completion. <a href="https://angular.io/guide/testing-components-scenarios#calling-compilecomponents">If you are using Ivy, you may not need to call this method, though</a>.</p><p>If you need to spy on some calls to shared services or provide some additional initialization, this method would be a good place to do it.</p><p>Once this method is in place we can initialize our testing environments in the test file by simply calling this method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e2758660f9fb682e23453ef2af9adf/href">https://medium.com/media/15e2758660f9fb682e23453ef2af9adf/href</a></iframe><p>With such simple initialization, separating tests for validation or keyboard input into their own files will be a breeze. For now, let’s focus on the basics. With properly named helper methods we can test the basic functionality in a quick and readable way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2a2e90683cc2d4cfcdd1830ae68551/href">https://medium.com/media/2b2a2e90683cc2d4cfcdd1830ae68551/href</a></iframe><h4>Good practices when designing page objects</h4><p>You may have noticed that we did not explicitly trigger the change detection in the test. The page object exposes methods for all interactions with the page.<br>Such methods can call change detection instead. This removes even more chatter from the test files and makes them more readable.</p><p>In more complex cases you may also want to move the code to wait for or simulate asynchronous operations to the page object. This can be useful when the component needs to trigger routing, for example. One way to do it is to use the fakeAsync function and to immediately call the returned function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5f8ac6830aa274e78c1554b4526cc26/href">https://medium.com/media/f5f8ac6830aa274e78c1554b4526cc26/href</a></iframe><p>The page object can become big itself if you are not careful. Try to provide an interface that is both readable and easy to maintain. Sometimes it’s worth to provide a single method to click any button based on the label, instead of a separate method for each button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ea14b32d68514d4bea8290f4277aab4/href">https://medium.com/media/3ea14b32d68514d4bea8290f4277aab4/href</a></iframe><p>The page object can throw helpful error messages when something unexpected happens. One example is that an expected button has not been found, or that there were more buttons than expected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/772e9fd2d45c3b04a2228a5acf5a1226/href">https://medium.com/media/772e9fd2d45c3b04a2228a5acf5a1226/href</a></iframe><p>You may consider extracting such helpers somewhere out of your page object to not repeat such logic. Maybe you need an abstract class for all your page objects to inherit? Maybe a simple function that you can import will do?</p><p>The factory method can accept parameters. This might be handy when you need to test that the component behaves differently under certain conditions.<br>In our example, this could be used if we had to provide minimal value.</p><h4>Live demo</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-testing-page-object%3Fembed%3D1%26file%3Dapp%252Fnumber-selector%252Fnumber-selector-page.ts&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-testing-page-object%3Ffile%3Dapp%252Fnumber-selector%252Fnumber-selector-page.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-03bbb9acbba813917725387f46e5df03a95d232be240e910ce5f946a973b3f86.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6657d15c57e3007c73bc6a5c84b3282b/href">https://medium.com/media/6657d15c57e3007c73bc6a5c84b3282b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf826fc8d134" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/clean-up-your-fronted-tests-part-4-bf826fc8d134">Clean Up Your Fronted Tests: Part 4</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Should You Return HTTP 422?]]></title>
            <link>https://medium.com/vattenfall-tech/why-you-should-return-http-422-82835e086db?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/82835e086db</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Paweł Pluta]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 12:39:30 GMT</pubDate>
            <atom:updated>2020-12-23T12:39:30.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fLL6XfOv6BoTpwkRaatMA.jpeg" /></figure><p>Developers are lazy. While reviewing an API, I’ve seen a lot of cases, that the only response codes returned were 500 (aka “backend is not working”) and 400 (broadly known as “frontend messed up”). “Better” APIs were also returning 404 and authentication/authorization failure codes. Such an approach is fast to implement and covers most of the use cases. But have you ever wonder, what will happen if developers have the possibility and time to experiment? They will delve into it.</p><p>This article has to make you pay attention to the quality of messages returned by your API, with the biggest focus on status codes. Selecting them carefully will make your API more descriptive and easier to use, reducing feedback loop time needed for root cause analysis.</p><h3>The need for proper status</h3><p>One day in my work, we were implementing some API, that was consuming JSON. Nothing special, but there was some logic behind two fields sent in a message payload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23d768da2d0ec634d547ff51d1bfb45/href">https://medium.com/media/f23d768da2d0ec634d547ff51d1bfb45/href</a></iframe><p>Generally, the time difference between dates could not be bigger than some period. Tests, that we wrote for this endpoint, were checking if HTTP 400 Bad Request was returned in case of the too-broad time range. Looked solid, but during the code review, we got a comment, if is this a good status code, as request syntax is perfectly valid, but semantics is here a problem. Well, that started a very long discussion.</p><h4>Word on Client Error codes</h4><p>In general, response codes classes start with very broad information. For Client Error codes it is <a href="https://tools.ietf.org/html/rfc2616#section-10.4.1">HTTP 400 Bad request</a>, originally meaning “request sent by client has a malformed syntax”, which was very strict about the reason behind this status. Later, in updating <a href="https://tools.ietf.org/html/rfc7231#section-6.5.1">RFC 7231</a>, the definition of 400 was defined less restrictive. Since 2014, it is just information about a potential client problem, that sent an invalid request. Neither specific nor descriptive. Hopefully, there are a lot of other status codes, that could be used. Looking at a list published on <a href="https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml">IANA</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">Mozilla Developer Center</a>, we can see that they are more and more specific, from authorization issues, through invalid header values, to legal problems, so probably there is an error code that will fit our needs. In our case, we got a suggestion that <a href="https://tools.ietf.org/html/rfc4918#section-11.2">422 Unprocessable Entity</a> could be used.</p><h4>Doubts about 422</h4><p>The request that we sent was perfectly fine in the matter of syntax, as the content type was understood by the server, and its body was successfully parsed. The problem was just in data that was provided within the body, which made our case a perfect situation for Unprocessable Entity status. Such a situation might happen for some reasons, e.g. because of logic behind command processing, like a requirement that the selected period cannot be bigger than 60 days. That could be achieved by changing userRegisteredTo field value to out of the defined range.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa62ef30550160c1a99ef437a7a933c0/href">https://medium.com/media/aa62ef30550160c1a99ef437a7a933c0/href</a></iframe><p>Even if the requested command syntax was correct, the data inside it was not. It can also happen in other scenarios, that check the quality of provided data, like in one below, where a user wants to set prices for shipping packages to some country but is trying to use the currency that cannot be used within it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb154db4aed9533eeb26b2523462bacb/href">https://medium.com/media/eb154db4aed9533eeb26b2523462bacb/href</a></iframe><p>Even if our cases looked like a perfect match for the 422 status code, we still had concerns regarding if it should be used. It is not a part of the standard HTTP protocol but is a part of its extension called <a href="https://tools.ietf.org/html/rfc4918">WebDAV</a>. WebDAV is used for managing resources, usually files, directories, and their properties. As we were not implementing anything related to WebDAV, it looked like an overhead. We were going to use only one response code defined in whole, over 120 pages of documentation. We liked the response code, but we needed proof that we can use it.</p><p>To get an argument for using code from extension to plain HTTP, we need to take a step back and check the original documentation one more time. Fortunately, in a <a href="https://tools.ietf.org/html/rfc7231#section-6">section that is describing status codes</a> there is one, very important sentence for us:</p><pre>HTTP status codes are extensible.</pre><p>This opens a lot of doors for using available extensions. There is a huge benefit in using specific response codes, as it provides information about the root cause of the problem. Knowing what was wrong, API clients can perform retry, tell users to fix the data, or authorize again, depending on retrieved status. It could not be possible with returning general HTTP 400 Bad Request in response.</p><p>Take the benefit of various response codes, and inform clients about the source of a problem. If no code matches your need, remember that <a href="https://tools.ietf.org/html/rfc7231#section-6">HTTP statuses are extensible</a>, so look for the best one also within extensions, or as a last resort — create your own one. If that is not enough for your case, consider implementing <a href="https://tools.ietf.org/html/rfc7807">Problem Details</a> for your API. Problem details can give huge insight for a user that is using your API, e.g. when requested setting price for shipping in invalid currency, apart from status code, it could provide response body like:</p><pre>{<br>    &quot;type&quot;: &quot;/errors/currency-is-not-supported-in-country&quot;,<br>    &quot;title&quot;: &quot;Requested currency cannot be used in this country.&quot;,<br>    &quot;status&quot;: 422,<br>    &quot;detail&quot;: &quot;Germany supports only currencies: EUR, BTC&quot;,<br>    &quot;instance&quot;: &quot;/errors/currency-is-not-supported-in-country/7291562&quot;,<br>    &quot;requestedCountry&quot;: &quot;Germany&quot;,<br>    &quot;requestedCurrency&quot;: &quot;USD&quot;<br>}</pre><p>The format of the response is standardized, if you are interested in it, please refer to the <a href="https://tools.ietf.org/html/rfc7807">documentation</a>.</p><h3>Security consideration</h3><p>Descriptive responses from your API may accidentally expose valuable information for attackers. You should not expose information about your infrastructure (webserver implementation, database version), or used language and its version. Make sure to never return any stack trace within your response body. All this information can allow malicious users to use exploits and break your application. You can also perform some additional steps to protect yourself, as not always returning detail is desirable behavior.</p><h4>Hiding what should not be visible</h4><p>One of the things, that can improve your API security, is hiding details from a user that do not have access to a resource. Let’s visualize it with resource providing business deal details under /api/contracts/32167. Who should be able to see those details? Probably only allowed users. Even more, probably not allowed users should even not know if such resource exists. Therefore, if an unauthorized user A would request this contract details, it could get a response 404 Not Found (instead of 403 Forbidden), which will hide from him even the existence of such agreement.</p><p>A similar situation should happen for a user that is not logged in. Instead of returning 403 Forbidden for protected resources and 404 Not Found for not existing ones, it might be valuable to return 401 Unauthorized for all non-public resources. Usually, users, who are not authorized, are not consumers of API, so they should not retrieve detailed reasons.</p><h3>Design API responsibly</h3><p>Meaningful responses are simplifying communication, leaving no room for guesses that may lead to long hours for analyzing the root cause. Being strict and precise in responses will cause your API more discoverable and easier to use for your clients. Just make sure, that you will not tell them too much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82835e086db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/why-you-should-return-http-422-82835e086db">Why Should You Return HTTP 422?</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The OOP Has Been Explained Wrongly to Me]]></title>
            <link>https://medium.com/vattenfall-tech/the-oop-has-been-explained-wrongly-to-me-db8e36f91bb2?source=rss----4240c54ef437---4</link>
            <guid isPermaLink="false">https://medium.com/p/db8e36f91bb2</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Paweł Pluta]]></dc:creator>
            <pubDate>Wed, 23 Dec 2020 12:34:19 GMT</pubDate>
            <atom:updated>2020-12-23T12:34:19.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEyCXrmzOIuBqH-6gNH-WA.jpeg" /><figcaption>Featured photo by <a href="https://www.pexels.com/pl-pl/@adrienne-andersen-1174503?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Adrienne Andersen</strong></a> from <a href="https://www.pexels.com/pl-pl/zdjecie/automatyczny-beben-biznes-czarno-bialy-2254065/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Pexels</strong></a>.</figcaption></figure><p>Object-Oriented Programming is a paradigm that instructs us, how to organize data and function into objects. Those objects are structures that should be designed to reflect the real-world object. Fortunately, we have four principles defined: abstraction, polymorphism, inheritance, and encapsulation, which will lead us towards good code quality. Unfortunately, for years I understood them improperly, even if I was really convinced that I know them well. This article has to shorten your way to an understatement of the OOP paradigm.</p><p>During this article, we will focus mostly on practice with a little theoretical background. Even if all code samples are included, you can clone <a href="https://github.com/pawelpluta/oop-kata">GIT repository with sources</a> and follow each change. At the end of the article, you can continue learning by doing kata. To simplify work, we will skip unit testing. Let&#39;s check, what are we going to work on.</p><h3>The Washing Machine</h3><p>The application, that we are working on, is a representation of a washing machine. Seems like it is nothing special, just put clothes inside and start it, so the laundry is being done. On the other hand, when we start to gather requirements that an ordinary washing machine has to do, it grows into at least a few point list.</p><ul><li>It must wash any laundry that we have</li><li>Must provide dedicated programs for a different type of fabric</li><li>Programs for fabrics must be adjustable in the matter of temperature and spin speed</li><li>It should not be possible to insert too many laundries into the washer</li></ul><p>We could add more and more requirements to the list, but let&#39;s stop for now, and make those four a little bit more precise.</p><ul><li>Supported fabrics are wool, cotton, and silk</li><li>Wool can be washed only in temperature up to 40°C, with spin speed between 100 and 400 rounds per minute</li><li>Cotton can be washed at a temperature between 30 and 95°C, with spin speed up to 1200 RPM</li><li>The maximum temperature for silk is 30°C and up to 300 RPM</li><li>The default value for temperature and spin speed will be its maximum value</li><li>The washer should have protection for putting over 7 kilograms of laundries</li></ul><h4>Development of the first version of the application</h4><p>We are going to code the application in a way that some controller will provide laundry to the core of the application — the Washing Service. Washing Service will use the Washing Machine to perform wash. This version of the code will be a base for applying OOP principles. On purpose, we are going to design and implement it in a way that I have seen in multiple projects and companies. Writing Object-Oriented code is not only about using classes, but we also need to model it in a very precise way. For now, we will start with the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZ6oFEPi4FS1urlG.png" /><figcaption>Simplified diagram for our application that violates OOP. It is composed of few classes.</figcaption></figure><p>We will start with defining two, the most valuable elements of the whole application: Laundry and WashingMachine. They are mentioned multiple times in the requirements, so let&#39;s take a look at the code that we are going, to begin with. You can also clone the GitHub repo and follow all the changes in your favorite IDE.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/569a845a314a212f99e449a330f98616/href">https://medium.com/media/569a845a314a212f99e449a330f98616/href</a></iframe><p>Supported fabric types are defined in the requirements, so we decided to keep them as an enum and hope it will not change pretty often.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f49d97ca2f224f2d43e7ca173eb47a78/href">https://medium.com/media/f49d97ca2f224f2d43e7ca173eb47a78/href</a></iframe><p>The last thing from model classes is the washing machine itself. From the description, we may conclude that it will spin at different speeds and will do laundry at different temperatures. Also, it will, of course, perform wash and clean up the laundry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25caa3c34061e70d4459d6e608ffbeb2/href">https://medium.com/media/25caa3c34061e70d4459d6e608ffbeb2/href</a></iframe><p>Model classes are fairly simple and represent object attributes pretty well. What we do not have here is the logic described in the requirements for the application. We are going to implement it as a WashingService. The logic that will manage the washing process is represented by three wash methods.</p><p>We will focus on one of the methods, let’s say, washWool and later will duplicate the solution of all of the programs. Wool should be by default wash at a temperature of 40 degrees and with the spin speed set up to 400 RPM. Before we set up our laundry, we also have to sort it by fabric type and get only the ones that we are currently interested in. We need to remember also required check for each of the parameters, so we will not exceed values defined for a program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/731cdfb61e5f0f1dd3acedf71b2efa43/href">https://medium.com/media/731cdfb61e5f0f1dd3acedf71b2efa43/href</a></iframe><p>Having washing logic in place, we need the last piece of the puzzle — something that will invoke the washing process. The controller here is responsible for obtaining all laundry and providing it to the WashingService so it will do the laundry. This part of the application can be changed, depending on the presentation layer, so we are not going to keep here any logic. Keeping logic apart from this class ensures us that all possible controllers will use the same process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e497f580574f02afc5f64bca3470cd17/href">https://medium.com/media/e497f580574f02afc5f64bca3470cd17/href</a></iframe><h3>How hard we broke OOP?</h3><p>Even if you do not see it yet, we already violated Object-Oriented Principles pretty hard. A lot of logic is now in the service, which is very specific to washer programmes. In the matter of encapsulation, we are taking out the internals of the washing machine and perform some operations on it. It is equivalent to pouring water with a bucket into the washer, instead of letting the washing machine take up the right amount — it is clearly violating OOP’s principles. What would happen, if new requirements would appear, like no drain function or double rinse? Adding such features to the service will quickly make it hard to maintain. Pretty easily we will reach a dead-end when code becomes unmaintainable.</p><h4>Problems with lack of Object-Oriented approach</h4><p>Till now, we have implemented an application that does not follow OOP principles, even if it might look to do. Ours WashingService is on a good way to become a big class that handles all washing-related logic. It is visible, that we are facing some problems:</p><ul><li>Moving value checks from Washing Machine to Service may lead to inconsistency. All services using Washing Machine needs to know, what are its limitations. What will happen, if we will have another, smaller Washing Machine, that may operate only on a maximum of 5 kg of laundry? We would have to update all services that are using it.</li><li>Adding a new service will require implementing exactly the same checks. If we would need to add a DryingService, then it is needed to duplicate the code. Logic centralized in service instead of the object makes it hard to be reused.</li><li>Extensive code is not easy to test. A lot of possible ways of execution for every method makes automated tests heavy (a lot of preparation) and overlapping (a common part of methods is tested by multiple tests)</li></ul><p>Without following OOP, classes and tests may become heavy. Right now, to fully test all paths within washWool the method, we will need up to 32 unit tests — just for this one method. I find it one of the core reasons for developers not writing unit tests — they are too big and require a lot of data preparation. Now we know, what is the problem with our code, and we do know how it should work. Time to make this code Object-Oriented!</p><h3>Inheritance of clothes</h3><p>While going into a clothing store, you can choose from multiple fabrics that clothes are made, yet all clothes have the same abilities — they can be put on, worn, stained, and cleaned. Depending on the way you are looking at clothes, they can be categorized by different characteristics. You can distinguish them by type of clothes (shirts, jackets, trousers), but they are still clothes.</p><p>Inheritance is something, that allows for the generalization of specific things. Depending on that who you are talking to, you might need to be more specific, or perform conversation on a general level. For example, imagine a situation when you are walking into a store, and a shop assistant approaches you. It would be more valuable to say that you need a pair of trousers than saying you need some clothes. On the other hand, while talking to a friend that you meet on a street, it is perfectly fine to say that you are going to buy some clothes. Inheritance allows you to refer to jackets and trousers as clothes.</p><h4>Inheritance vs polymorphism</h4><p>While inheritance is about copying behaviors and attributes, polymorphism is about changing behavior in subclasses. In Java, they are strictly connected — if Clothes has a cleanUp() method, to change its behavior we have to extend Clothes in Jacket class. So, in Java, the OOP polymorphism is fulfilled by extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODe_sP55gE1ZLxb-kzXJJA.png" /><figcaption>Polymorphism is using inheritance in Java.</figcaption></figure><h4>Applying inheritance to washing elements</h4><p>Inheritance is clear is-a relation. If Jacket extends Clothes, then Jacket is-a Clothes. While thinking of laundry, we usually do not care if we are washing jackets or anything else. More important is the type of fabric - in our case they were distinguished by enum property. It works, but it is promoting direct access to the internals of the object. This may lead to breaking the encapsulation and gives the possibility to put the object into an invalid state. Having it in a property inside class requires you to search for this information inside the object - it is like looking for a clothes tag and reading it every time you want to wash this piece of clothes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t7KZPOQubKBC3Bb6.jpg" /><figcaption>To know how to wash clothes you have to always look inside it. Photo by <a href="https://commons.wikimedia.org/wiki/User:Roland_Russwurm">Roland Russwurm</a>.</figcaption></figure><p>Let’s change our code. To make LaundryElement class more OOP focused, we will have to do multiple things. Let&#39;s start with making it an abstract class, so it will become the base for inheritance. Another small, but important step is making fields immutable where possible. This will prevent instances of this class being vulnerable to direct field changes. The only field that is mutating is the dirty flag.</p><p>To modify dirty flag, we will not use set method. Instead of that, we will hide it behind a little abstraction of dirty() and clean() methods. It promotes hiding the internals of objects and protects its data integrity by preventing anyone from directly providing value for object internals. This change will simplify future changes - in the case if it would be needed for clothes to keep information about how dirty it is (instead of just boolean flag), it will be only needed to change dirty() method - all its calls will remain unchanged. Another change that we will introduce, is Creation Methods, as described by Joshua Kerievsky in “Refactoring to Patterns” (chapter 6).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8440e260b64a9fa7df5f33aa0ca1b2de/href">https://medium.com/media/8440e260b64a9fa7df5f33aa0ca1b2de/href</a></iframe><p>The final step for this class is to apply OOP inheritance. We will extend LaundryElement with three, dedicated classes, one for each fabric type. Because they are really small ones, they are implemented as <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html">nested classes</a>. When classes are named, we can remove the enum totally - now it contains obsolete information about the type of fabric. Before that, we need to replace all usages of Fabric, e.g. in Washing Controller.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2beb0f50d03060abe583e3e0c704731f/href">https://medium.com/media/2beb0f50d03060abe583e3e0c704731f/href</a></iframe><h4>Where the laundry comes from?</h4><p>While modeling the real world with OOP in mind, we are trying to reflect reality the best we can. Right now, our laundry is represented by List of LaundryElements, but it is taken from nowhere. It is equivalent to clothes laying all over the apartment, and please, tell me you do not do that in real life! Usually, they are kept in some basket, from which we are taking laundry to be washed. Let&#39;s model that!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3617b55bc86356c29cc512a57c9500fa/href">https://medium.com/media/3617b55bc86356c29cc512a57c9500fa/href</a></iframe><p>Starting from Laundry, as a term that we used a lot in this article, we defined something that is a group of laundry, with the possibility of its modification. Having <a href="https://martinfowler.com/bliki/UbiquitousLanguage.html">real-word terms that are commonly used</a> is a great way of simplifying code and documenting it. The second object, that we are going to introduce, is Basket which we decided to be a good place for storing laundry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01892efb5db2113416640f97133d8d1f/href">https://medium.com/media/01892efb5db2113416640f97133d8d1f/href</a></iframe><p>Having those types defined, we can refactor existing code (controller and washing machine) to use it. In the beginning, while learning the OOP approach, it might seem overcomplicated to create so many types. Many questions might be raised, like “Why cannot I use List directly in the Basket?” or “Why objects are immutable?” or “Where are the getters?”.</p><p>We are doing it for few reasons, like concept separation (classes are small, methods are trivial), documentation (the new person reading code is learning naming and processes in the business), or maintainability (small classes with simple methods are very easily testable). Imagine, if someone reports the bug, and describes it as “I cannot take out the laundry from a basket” — you already know, where you should look for it. To learn more about naming and separating objects, take a look into Vaughn Vernons “Implementing Domain-Driven Design”, especially on chapters regarding Value Objects and Standard Types.</p><h4>Wrap up: inheritance vs polymorphism</h4><p>By now, we discussed OOP inheritance and polymorphism principles. We also started a talk regarding encapsulation. From this part, you should remember:</p><ul><li>inheritance is about copying behaviors and attributes</li><li><a href="https://www.thoughtworks.com/insights/blog/composition-vs-inheritance-how-choose">inheritance might be not the best choice</a>, especially if you need has-a instead of is-a relation</li><li>polymorphism is about changing behaviors in subclasses</li><li>you should try to reflect real-world when modeling classes, focusing on their behavior</li><li>wrap meaningful information into well-named Value Objects</li></ul><h3>The encapsulation that we were taught</h3><p>Encapsulation is one of the OOP principles, that has to protect the integrity of the data. In multiple sources usually, it is told, that encapsulation is achieved by hiding the data in a small, single unit, like class. We can think of integrity as a consistent state of object internals, so no one can change it without letting the object knowing it. It is usually told to expose getters/setters and change the visibility of fields to private. Does it help to keep object integrity?</p><p>Let&#39;s think about the imaginary type HomeAddress. It is composed of few fields, including city and zipCode. All fields are private and encapsulated with getters and setters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_lZ9sPc_w4tqCusS.png" /><figcaption>Even if fields are hidden behind setters and getters, the object can be inconsistent for some time.</figcaption></figure><p>Between the invocation of methods, there is a small interval, during which the object will remain inconsistent. Encapsulation from OOP is not only hiding data but also <strong>how</strong> the object achieves some desired state. We should not even know, that to update the address we have to change two properties. It would be much better if this code will contain an City value object with properties name and zipCode that is provided HomeAddress as a single object in a single method call. It will allow HomeAddress changing its internal state according to the provided data, without exposing information on how it should be done. That is really an object internal business.</p><h4>Applying encapsulation to the Washing Machine</h4><p>Encapsulation in OOP is focusing that <strong>how</strong> the object is working, therefore we should try to hide internal logic to protect its consistency. The best place to start will be setting up temperature and spin speed. Right now, Washing Service is responsible for setting those values individually. Similarly to the Laundry and Basket, we will create a dedicated class called Programme that will store temperature and spinSpeed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4db96071af8f6d9755a45838f6988539/href">https://medium.com/media/4db96071af8f6d9755a45838f6988539/href</a></iframe><p>Note, that for simplicity we skipped checks for minimal and maximum values (your task will be to implement those checks while doing kata). With this approach, Washing Service has one responsibility less to maintain, as its code will be simplified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f09c098b70c9e40669c3b24659e31e8/href">https://medium.com/media/9f09c098b70c9e40669c3b24659e31e8/href</a></iframe><h4>Abstraction on top of encapsulation</h4><p>The final step is to understand abstraction, the last Object-Oriented Principle that we are going to cover. Similar to encapsulation, it secures the object from leaking its internals. The main difference is the level that it covers — encapsulation works more on the internals of object and that, <strong>how</strong> it works on data. Abstraction on the other hand focuses on <strong>what</strong> the object can do.</p><p>Applying this definition into the washing machine, encapsulation hides, how temperature is stored, and how it is set up in the washing program. While using a washing machine, we are more focused on what it can do, like adding laundry, selecting a program, or starting it. Those are clearly behaviors, that washing machine offers. Applying abstraction on the washing machine will hide all the complexity behind it. This time, we will not have a lot of work in implementing. Let’s rename some methods to reflect the real world.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdf78b3599466c8ec28d90b93e1e274f/href">https://medium.com/media/fdf78b3599466c8ec28d90b93e1e274f/href</a></iframe><p>Change is really small, but it focuses on the user of a washing machine on its behaviors and capabilities. Literally, the user does not have to know anything, how complex the washing process is — it can be composed of supplying water, heating, spinning, rinsing, and draining, but while we are standing in front of the washing machine — it is just happening.</p><h4>Wrap up: encapsulation vs abstraction</h4><p>Summing up what we learned about OOP’s encapsulation and abstraction:</p><ul><li>Both are hiding internal of object</li><li>encapsulation focuses more on <strong>how</strong> the object is working</li><li>hiding private fields behind simple setters and getters does not protect their integrity</li><li>abstraction focuses on <strong>what</strong> the object can do</li><li>abstraction can be perceived as a perspective of the user that is going to interact with the object</li><li>abstraction is often achieved by interfaces, as those allow to focus on behaviors</li></ul><h3>Train your skills</h3><p>Till now, you should gain a solid background for understanding Object-Oriented Principles, but it is just a theory. Without practice you will quickly forget about those principles, so you need additional training. You can use kata based on this article, starting from the clean Washing Machine project. Below you will find steps that you can perform to apply OOP to this project. You can also find a sample solution on <a href="https://github.com/pawelpluta/oop-kata/tree/sample-solution">this branch</a>. Remember, that your solution does not need to look exactly the same, as there are multiple ways of implementing it.</p><h3>Steps to follow</h3><ul><li>Create a class for each type of clothing</li><li>Add method that will allow changing state of clothes (clean/dirty)</li><li>Create a class for basket and laundry</li><li>Make a new class for representation of each program and add validation to it</li><li>Rename methods from WashingMachine so they will reflect real-world action</li></ul><p>After those steps, you should have a similar structure to the one used in this article. For better training, you should also make further changes:</p><ul><li>Try to remove all direct passing of List as method parameter - List should be only used internally inside of a class</li><li>Extend Programme class so it will contain behaviors to adjust parameters</li><li>Temperature can be changed only every 5 degrees</li><li>The spin speed can be changed only every 100</li><li>The program can be set up to perform an additional rinse</li><li>Create dedicated classes for temperature and spin speed</li><li>Move check if the value is in a valid range to Temperature and SpinSpeed classes</li><li>Laundry, that does not fit into Washing Machine should be put back into Basket</li><li>Try to remove Service class or name it properly — naming class with ‘Service’ suffix promotes adding all, barely connected code into this class instead of splitting responsibilities</li></ul><p>Remember, writing OOP code is constant work, that you have to train all the time. At every step, you need to think, if principles are fulfilled and take care of proper naming. This additional work will pay back with easier maintenance of the codebase. Code kept in good shape will shorten the time needed for developing new features.</p><h3>Resources referenced in this article</h3><ul><li><a href="https://github.com/pawelpluta/oop-kata">Sources for a code kata</a></li><li><a href="https://github.com/pawelpluta/oop-kata/tree/sample-solution">Sample solved code kata</a></li><li><a href="https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html">Nested classes explained</a></li><li><a href="https://martinfowler.com/bliki/UbiquitousLanguage.html">Ubiquitous language</a></li><li><a href="https://www.thoughtworks.com/insights/blog/composition-vs-inheritance-how-choose">Composition and inheritance</a></li><li>Book: “Refactoring to Patterns” by Joshua Kerievsky</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db8e36f91bb2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/the-oop-has-been-explained-wrongly-to-me-db8e36f91bb2">The OOP Has Been Explained Wrongly to Me</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>