<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Milan Brankovic on Medium]]></title>
        <description><![CDATA[Stories by Milan Brankovic on Medium]]></description>
        <link>https://medium.com/@milanbrankovic?source=rss-bee1178242------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9J03c5Kvp0OX2u0XTSzi2A.jpeg</url>
            <title>Stories by Milan Brankovic on Medium</title>
            <link>https://medium.com/@milanbrankovic?source=rss-bee1178242------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:14:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milanbrankovic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simplifying systems]]></title>
            <link>https://milanbrankovic.medium.com/simplifying-systems-24763323494c?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/24763323494c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 06:21:07 GMT</pubDate>
            <atom:updated>2022-07-19T06:21:07.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deADk5Gk5jW_8Ddx-FtZdQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@kellysikkema?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When you start developing, software systems are small and easy to maintain. But they (almost) always grow in time. Human beings hope that they can hold average sized system in their heads at once. This can be only achieved by reducing complexity to simplicity.</p><p><em>A good software engineer will do everything in his power to make what his own work for other programmers (and his future self) simple enough to use and comprehend.</em></p><p>While working on the systems (small or large) we must bear in mind that the <strong>purpose of the product is to help people</strong>. By following this premise you will share strong connection with your users and will write better software. So whenever a new list of feature request come in, ask yourself how will this feature help users? If it want, or it will help only a small percentage of users you can use this metric to prioritize those features.</p><p>Software systems evolve over time. In order not to make them rot, and obsolete when planning about the future we must take the following factors:</p><ul><li>value: represents the degree to which this change helps anybody anywhere</li><li>effort</li><li>maintainability</li></ul><p>To calculate cost-effectiveness we can use the following equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*weHvpXP1qHKO66XDBigZCw.png" /></figure><p>which means: The desirability of a change is directly proportional to the value now plus the future value, and inversely proportional to the effort of implementation now plus the effort of maintenance. This can even be simplified to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*4kRCNpNpXBcp4PzxwoNruQ.png" /></figure><p>as future value and effort of maintenance depend on time. Having this in mind we can conclude that <em>it is more important to reduce the effort of maintenance that to reduce the effort of implementation</em>.</p><p>Looking at the future you can not foresee it and thus why <em>the most common and disastrous errors are made because of trying to predict something about the future</em>.</p><p>We can not predict the future, but what can we do? As we know that <em>the longer the program exists, the more probable it is that any piece of it will have to be changed</em>. This means that we should focus on present by following these principles:</p><ul><li>don&#39;t write code until you actually need it (<strong>Y</strong>ou <strong>A</strong>in&#39;t <strong>G</strong>onna <strong>N</strong>eed <strong>I</strong>t)</li><li>code should be designed on what you know right now</li><li>be only as generic as it needs right now</li><li>build system one piece at the time</li></ul><p>No human is perfect, and this goes for engineers as well. Good software engineer will introduce 1 defect for every 100 lines, the best engineer will introduce 1 defect for every 1000 lines of code they write. <em>It&#39;s inevitable to introduce defect(s) at some point and this probability is proportional to the size of the change which is going to be made</em>. It&#39;s important to understand this as defects violate the purpose of product (helping people) and therefore should be avoided. Also by fixing defect(s) we increase the cost of maintainability. Then we can say:</p><p><em>the best design is the one that allows for the most change in the environment with the least change in the software.</em></p><p>In order to minimize the probability of introducing defect(s) we should:</p><ul><li>never &quot;fix&quot;anything unless it&#39;s a problem and you have evidence that shows that the problem really exists (if it ain&#39;t broken, don&#39;t touch it)</li><li>ideally one piece of information should exist only once (<strong>D</strong>on&#39;t <strong>R</strong>epeat <strong>Y</strong>ourself)</li></ul><p>If we don&#39;t change the system we can not introduce new defects, but if we don&#39;t change the system it will become obsolete. So how can we minimize number of defects, but still keep system evolving over time?</p><p><em>The ease of maintenance of any piece of software is proportional to the simplicity of it&#39;s individual pieces</em>. We can achieve this by:</p><ul><li>keeping everything dumb, dumb simple</li><li>being consistent</li><li>keeping code readable</li><li>naming things the proper way</li><li>commenting only when necessary</li></ul><p>Unfortunately people do not naturally build simple systems. Never forget they can be guided to do so!</p><p>But what is number one reason why legacy systems are hard to maintain, improve and extend? It&#39;s <strong>complexity</strong>! Complexity can be added in many ways (and these are some of them):</p><ul><li>complex requirements at the very beginning (so they don&#39;t even launch)</li><li>expanding the purpose of software</li><li>adding inexperienced programmers with tight time-to-market</li><li>changing things which do not need to be changed</li><li>misunderstanding of user needs</li><li>poor or no design</li><li>choosing inappropriate/bad technology</li><li>no proper testing</li></ul><p>To handle these complex systems we can either (a) start simplifying things piece by piece (using small steps), or (b) rewrite the whole system. The first one works in all cases except for the case when you have proven that rewriting the old system has less cost than keeping it (and also you have a lot time to spare!).</p><p>So, don&#39;t forget, the real problem is not the software, technology, requirements, etc. but <em>complexity</em>! Always aim for simple solutions that work now, and strive for easy to use and maintain code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24763323494c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dissolving the Monolith: Patterns]]></title>
            <link>https://milanbrankovic.medium.com/dissolving-the-monolith-patterns-bf4b06c96fd6?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf4b06c96fd6</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 06:22:21 GMT</pubDate>
            <atom:updated>2022-07-12T06:22:21.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVVUakuV_Pb21Yhzna9Ytw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fletcher_pride?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fletcher Pride</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Monolith is not bad per se. Here are the benefits of monolithic architecture:</p><ul><li>simple to develop</li><li>easy to make radical changes to the application</li><li>straightforward to test</li><li>straightforward to deploy</li><li>easy to scale</li></ul><p>On contrary these are some of the biggest limitations:</p><ul><li>complexity</li><li>slow development</li><li>path to deploy is arduous</li><li>delivering reliable monolith is hard</li><li>locked to (obsolete) tech stack</li></ul><p>To escape monolithic hell, migration to some other form is necessary. One of the new architecture styles is microservice architecture style. Here are the benefits of using this architecture style:</p><ul><li>it enables continuous delivery and deployment of large, complex applications</li><li>services are small and easily maintained</li><li>services are independently deployable</li><li>it enables teams to be autonomous</li><li>it allows easy experimenting and adoption of new technologies</li><li>it has better fault isolation</li></ul><p>but, it does not come without drawbacks. These are some of them:</p><ul><li>finding the right service is challenging</li><li>distributed systems are complex (this makes development, testing and deployment difficult)</li><li>deploying feature that span multiple services require careful coordination</li><li>deciding when to adopt this kind of architecture is difficult</li></ul><p>That being said, you must keep in mind that microservice architecture is not a sliver bullet. Depending on the situation, sometimes it&#39;s even better to go with different architecture style (even the monolithic).</p><p>By migrating to microservice, or when starting to create/integrate a new one you should always consult best practices. As there are Gang of Four patterns available for software development, there are also some patterns for microservice architecture. There are several groups of patterns depending on the problem which needs to be solved. Those groups are:</p><ul><li>application patters — solve problems faced by developers</li><li>application infrastructure patterns — cover infrastructure issues that also impact development</li><li>infrastructure patterns — solve problems that are mostly infrastructure issues outside of development</li></ul><p>The first step in defining application&#39;s architecture is to define the system operations. You should start from system requirements. Then we should sketch out a high-level domain model. Once this is done we should identify the requests that application must handle. There are two types of operations: <em>commands</em> (Create, Update, Delete) and <em>queries</em> (Read). Lastly we need to identify the services.</p><p>If we are breaking monolith apart, there are two patterns for decomposition:</p><ul><li>decompose by business capability</li><li>decompose by subdomain (DDD decomposition)</li></ul><p>keep in mind that these strategies can be used even when you are starting development of a new microservice.</p><p>On the surface decomposition looks straightforward, however you may encounter several obstacles on the way:</p><ul><li>network latency</li><li>reduced availability (due to synchronous communication)</li><li>maintaining data consistency across services</li><li>obtaining a consistent view of the data</li><li>god classes preventing decomposition</li></ul><p>There are lots of different IPC (Inter Process Communication) technologies which can be chosen. Services can communicate synchronously by using request/response communication based mechanisms (e.g. HTTP REST or gRPC), or asynchronously (e.g. AMQP or STOMP). Additionally interaction between services can be one-to-one or one-to-many. During communication services are exchanging messages, which can also be in various formats: text based (JSON, XML) or binary (Protocol buffers).</p><p>Let&#39;s look at the trade-offs of mostly used communication types:</p><p><strong>REST</strong> <br>pros:</p><ul><li>simple and familiar</li><li>easy to be tested (browser, postman, curl)</li><li>directly supports request/response communication style</li><li>HTTP is firewall friendly</li><li>doesn&#39;t require an intermediate broker (simplifies architecture)</li></ul><p>cons:</p><ul><li>only supports request/response communication style</li><li>reduced availability</li><li>clients must know exact URL of the service</li><li>fetching multiple resources in a request is challenging</li><li>can be difficult to map multiple update operations to HTTP verbs</li></ul><p><strong>gRPC</strong></p><p>pros:</p><ul><li>straightforward to design an API that has a rich set of update operations</li><li>has an efficient, compact IPC mechanism, especially when exchanging large messages</li><li>bidirectional streaming</li><li>enables interoperability between clients and servers</li></ul><p>cons:</p><ul><li>more work on JavaScript clients to consume gRPC</li><li>older firewalls might not support HTTP/2</li></ul><p><strong>Broker-based messaging</strong></p><p>pros:</p><ul><li>loose coupling</li><li>message buffering</li><li>flexible communication</li><li>explicit interprocess communication</li></ul><p>cons:</p><ul><li>potential performance bottleneck</li><li>potential single point of failure</li><li>additional operational complexity</li></ul><p>In order to prevent failures from cascading through the system, services which use synchronous communication must be designed to handle partial failures (invoking service down or exhibiting high latency). To do so service should use timeouts, limiting the number of requests, and circuit breaker pattern. Each of these techniques can be used independently or in combination.</p><p>Whenever a synchronous communication is used there should be a service discovery mechanism included in order to enable clients to determine the network location of a service instance. This mechanism can be implemented on both server (deployment platform) and client (application) side. The simplest approach is to have it on deployment side (server-side discovery and 3rd party registration patterns), but it&#39;s not that complex to implement it on application side (client-side discovery and self registration patterns).</p><p>There are several impediments when using asynchronous communication with messaging. One challenge is competing consumers and message ordering. To overcome this you can use sharded (partitioned) channels (Apache Kafka or AWS Kinesis are already providing it out-of-the-box). Another challenge is handling of duplicate messages. Most message brokers promise to deliver message at least once, as guaranteeing exactly-once messaging is too costly. The ways to handle duplicate messages are:</p><ul><li>idempotent message handlers</li><li>track messages and discard duplicates</li></ul><p>But the biggest key challenge when using asynchronous communication is atomically updating the database and publishing a message. A good solution is transactional outbox pattern (write the message to the database first). On the other side a process which is retrieving the message can use either pooling publisher pattern or transactional log trailing pattern.</p><p>In monolithic systems every request is executed within a database transaction. Transaction management is more challenging in complex monolithic applications which use multiple databases and/or message brokers. And in a microservice architecture transactions span multiple services, where each of the services has its own database. In this situation we need to use specific mechanism to manage distributed transaction(s).</p><p>Traditional XA/2PC-based distributed transactions aren&#39;t a good fit for modern applications. A better approach is to use <em>Saga</em> pattern. Saga represents a sequence of local transactions that are coordinated using messages. Each local transaction is bound to a specific service. If there is a failure during saga, a compensating transactions must be executed to explicitly undo the changes.</p><p>There are two types of sagas: choreography and orchestration saga. In the choreography saga, a local transaction publishes events that trigger other saga participants to execute their local transaction. Decision making and sequencing is distributed among participants. This approach is better for simple sagas. In orchestration saga, a centralized orchestrator sends command messages to participants. By modeling saga orchestrator as state machine development of it can be drastically simplified. This type of saga is usually better for complex sagas.</p><p>Let’s look at the trade-offs between these two types of sagas.</p><p><strong>Choreography based saga</strong></p><p>pros:</p><ul><li>simple to develop</li><li>provides loose coupling</li></ul><p>cons:</p><ul><li>more difficult to understand</li><li>can introduce cyclic dependencies between services</li><li>risks of tight coupling</li></ul><p><strong>Orchestration based saga</strong></p><p>pros:</p><ul><li>simpler dependencies (no cyclic dependencies)</li><li>less coupling</li><li>improves separation of concerns and simplifies the business logic</li></ul><p>cons:</p><ul><li>risk of centralizing too much business logic in the orchestrator</li></ul><p>Designing sagas can be challenging as unlike ACID transactions, sagas aren&#39;t isolated from one another. The problems that can be introduced are: lost updates, dirty reads and non-repeatable reads. In order to bypass accessing other sagas data some of the countermeasures need to be implemented. You can choose between:</p><ul><li>semantic locks: set a flag in any record which needs to be created/altered. This flag indicates that the record is not commited and can be altered</li><li>commutative updates: make saga operations commutative to eliminate lost updates</li><li>pessimistic view: reorder saga steps in another saga to eliminate possibility of dirty reads</li><li>reread value: reread record, verify that it&#39;s unchanged and update it. This prevents lost updates</li><li>version file: records operations which are performed on a record. This enables to turn non-commutative into commutative operations</li><li>by value: strategy for selecting concurrency mechanism based on business risk. It uses properties of each request to decide between using sagas and distributed transactions.</li></ul><p>The procedural Transaction script is a good way to implement a simple business logic. The business logic will be organized as a collection of procedural transaction scripts (one for each type of request). Don&#39;t be ashamed to use procedural type of programming where necessary.</p><p>A complex business logic is a totally different story. This is really challenging task to implement in microservice architecture where the logic spans over multiple services. The best approach to use here is object-oriented Domain model pattern, where the business logic is organized as an object model consisting of several classes which have state and behavior.</p><p>A good way to organize a service&#39;s business logic is by grouping it in a collections of DDD aggregates. Each collection can be represented as a graph of objects treated as a unit. DDD aggregates are quite useful as they modularize the domain model, eliminate the possibility of object references between services and ensure that each ACID transaction is executed within service.</p><p>Identifying an aggregate is the most complex a key task in the process, as it requires designing a domain model(s) as aggregate(s), identifying their boundaries and their roots. There are some rules which ensure that an aggregate is self-contained unit that can enforce its invariants:</p><ul><li>reference only the aggregate root</li><li>inter-aggregate references must use primary keys</li><li>one transaction creates or updates one aggregate</li></ul><p>An aggregate should publish domain event(s) when it&#39;s created or updated. Domain event subscribers can also notify users and other applications, and publish WebSocket messages to user&#39;s browsers.</p><p>The traditional approach to persistence maps classes to database tables (using ORM). Composite entities (entities with children) are usually mapped to two different tables. Persisting parent entry, with children, persists rows in both tables. This approach works well because most enterprise applications store data this way, but it has several limitations:</p><ul><li>object-relational impedance mismatch</li><li>lack of aggregate history</li><li>auditing is tedious and error prone</li><li>event publishing is bound to the business logic</li></ul><p>As always, there is a solution for this problem: event sourcing.</p><p>Event sourcing is a way of structuring the business logic and persisting aggregates. The aggregate is persisted as a sequence of events, where each event represents either creation or state change of the aggregate. An application can recreate current state of the aggregate by replaying the events. Event sourcing preserves the history of domain object, providing an accurate audit log and reliably publishes domain events.</p><p>During application lifecycle there can me more than one request to simultaneously update the same aggregate. With traditional persistence approach optimistic locking is used to prevent one transaction overwriting another&#39;s changes. As we already know by now to overcome this problem in microservice architecture we can use polling and transaction log tailing.</p><p>To improve performance of long-lived aggregates, we can use snapshots to reduce the number of events which need to be replayed.</p><p>Most of the services consume messages from other services, thus it&#39;s important to build idempotent message consumer. Event sourcing-based business logic must also implement the same idempotent behavior. The concrete implementation depends on whether the event store users a RDBMS or a NoSQL database. As events are stored in an event store (which represents a hybrid of a database and message broker). Once a service stores event in event store, it automatically delivers an event to subscribers.</p><p>One of the challenges with event sourcing approach is evolution of events. The application must be capable of handling multiple event versions when replaying events. A good solution is to use upcasting, which upgrades events to the latest version when they are loaded from the event store. The other tricky problem is data deletion. Encryption and pseudonymization must be used in order to comply with e.g. GDPR.</p><p>Event sourcing is a simple way to implement choreography-based saga. Services have event handlers that listen to the events published by event sourcing based aggregates. Also this approach is good way to implement orchestration-based saga.</p><p>Let&#39;s compare the pros and cons of event sourcing:</p><p><strong>pros:</strong></p><ul><li>reliably publishes domain events</li><li>preserves the history of aggregates</li><li>(mostly) avoids O/R impedance mismatch problem</li><li>provides a time machine to developers</li></ul><p><strong>cons:</strong></p><ul><li>different programming model with a learning curve</li><li>evolving events can be challenging</li><li>deleting data can be tricky</li><li>querying event store is chanllenging</li></ul><p>In the monolithic application querying for data is an easy task as the data resides in one place. On contrary in microservice architecture each service owns it&#39;s data, and querying for it is challenging as data is scattered. There are two patterns for implementing query operation:</p><ul><li><em>API composition pattern</em>: gathers the data from multiple services. It makes clients of the service that own the data responsible for invoking the service and combining the result. This is the simplest approach and it should be used whenever possible</li><li><em>Command query responsibility segregation (CQRS) pattern</em>: maintains one or more view databases whose sole purpose is to support queries. It is more powerful than API composition pattern, but also more complex.</li></ul><p>Each of the above mentioned patterns has it&#39;s own issues which should be taken into consideration:</p><p>API composition pattern:</p><ul><li>which component should be API composer?</li><li>how to write efficient aggregation logic?</li><li>increases overhead</li><li>introduces risk of reduced availability</li><li>lack of transactional data consistency</li></ul><p>CQRS pattern:</p><ul><li>more complex architecture</li><li>dealing with replication lags</li><li>dealing with concurrent updates as well as detecting and dismissing duplicate events</li><li>handling consistency of CQRS views (moved to client)</li></ul><p>After all this being said, depending on the problem which needs to be solved you will choose appropriate pattern. API composition pattern should be the first choice (whenever possible due to simplicity), and CQRS is more robust solution (efficient implementation of queries in microservice architecture, efficient implementation of diverse queries, improves separation of concerns…)</p><p>The task of designing API is challenging if there is more than one client as different client types require different data. Consequently, one-size-fits-all API doesn&#39;t make sense to expose.</p><p>There are numerous drawbacks of using one-size-fits-all API, let&#39;s mention some of them:</p><ul><li>poor user experience due to numerous requests (mobile)</li><li>lack of encapsulation requires frontend developers to change their code in parallel with backend developers (mobile)</li><li>services might use client-unfriendly protocols (mobile)</li><li>network latency (web)</li><li>firewall (web)</li><li>API stability and maintainability for third-party consumers (web, mobile, other)</li></ul><p>To overcome these problems API gateway pattern can be used. An API gateway is a service that&#39;s an entry point for the outside world. It provides each client with a custom API, it&#39;s responsible for request routing, API composition, protocol translation and implementation of edge functions (such as authentication, authorization, rate limiting, caching, metrics collection and request logging).</p><p>An API gateway has a layered, modular architecture. It can be designed in a way of a single API gateway or it can use backends for frontends (BFF) pattern (defines a gateway fro each client type). The BFF pattern gives developer teams greater autonomy, because they can develop, deploy and operate on their own API gateway.</p><p>Let’s compare the pros and cons of event sourcing:</p><p><strong>pros:</strong></p><ul><li>encapsulates internal structure of the application</li><li>clients talk to the gateway instead of invoking specific service(s)</li><li>provides client-specific API</li><li>simplifies client code</li></ul><p><strong>cons:</strong></p><ul><li>another component which needs to be developed, deployed and managed</li><li>risk of becoming a bottleneck</li><li>must be updated every time when new API (from internal services) needs to be exposed</li></ul><p>There are numerous technologies which can be used to implement API gateway, either off-the-shelf product or developing your own using a framework. If you decide for custom implementation you must bear in mind the following things when designing an API gateway: (a) performance and scalability, (b) writing maintainable code by using reactive programming abstractions, (c) handling partial failures and (d) being a good citizen in microservice architecture (discovery and observability).</p><p>It is outmost important to have automated tests in the system. Automated tests are the key factor of rapid and safe delivery of software. The purpose of test is to verify the behavior of the system under test (SUT), where by system you can refer to any software element under test (from class method to entire application).</p><p>To speed up and simplify the tests you can use test doubles. A test double is an object which simulates the behavior of SUT&#39;s dependency. There are two types of test doubles: stubs (returns a value to the SUT) and mocks (verifies that SUT is invoking correct dependency).</p><p>Use the test pyramid to facilitate testing efforts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ge97gibdUoJmhZuCiGaIDA.jpeg" /></figure><p>Use contracts to drive testing of interactions between services. This way we can write tests which verify that the adapters of multiple services in action conform to the contract. By using this approach test will run faster and will eliminate transitive dependencies.</p><p>To verify the behavior of service via its API, component test should be written. As mentioned earlier for these type of tests stubs should be used.</p><p>At the end you could write end-to-end tests. In order to minimize the number of end-to-end tests, which are slow, brittle and time-consuming, end-to-end test can be combined in user journey tests. A user journey test simulates the journey through the application and verifies high-level behavior of (relatively) large part of application&#39;s functionality. By having these type of test, the amount of overhead (setup) per test is minimized, which speeds up the test. There should be a few tests which will cover a wide range of application&#39;s functionalities.</p><p>It&#39;s not enough that a service implements only functional requirements, it must also ensure that it satisfies three critically important quality attributes: security, configurability and observability.</p><p>Security in a microservice architecture is not different than in a monolithic architecture. The responsibility of every application developer is to implement the following aspects of security: authentication, authorization, auditing and secure interprocess communication. The majority of security aspects can be easily replicated to microservice architecture, but there are some aspects which are necessarily different:</p><ul><li>how user identity is passed between API gateway and the services</li><li>who is responsible for authentication and authorization</li></ul><p>A commonly used approach is for the API gateway to authenticate the clients, by including transparent token (e.g. JWT) in each request to a service. The token contains the identity of the principal and their roles. The services then use the information from the token to authorize access to resource(s). OAuth 2.0 is a good foundation for security.</p><p>A service typically uses one or more external services (e.g. database, message broker…). The location of these services, as well as credentials for each, almost always depend on the environment that the service is running in. The externalized configuration pattern must be applied and a mechanism that provides a service with configuration properties (at runtime) must be implemented. There are two main approaches:</p><ul><li>push model where the deployment infrastructure passes the configuration properties to the service instance using environment variables or configuration file</li><li>pull model where the service instance reads its configuration properties from a configuration server</li></ul><p>Developers and operations share responsibility for implementing observability in a system. Operations is responsible for infrastructure (handling log aggregations, metrics, exception tracking and distributed tracing), and developers are responsible for ensuring that the services are observable. Services must have health check API endpoint, generate log entries, collect and expose metrics, report exceptions to an exception tracking service and implement distributed tracing.</p><p>In order to simplify and accelerate development, you can use microservices chassis and develop services on top of it. A chassis is a framework, or set of frameworks, that handles various cross-cutting concerns. Over time most likely majority of the network related functions of a microservice chassis will migrate into service mesh: a layer of infrastructure software through which all of the service&#39;s network traffic flows.</p><p>When it comes to deployment of microservice(s) you should choose the most lightweighted pattern that supports service&#39;s requirements. In order to choose the best one, evaluate the options in the following order: serverless, containers, virtual machines and language-specific packages.</p><p>A serverless deployment is a the best option as it eliminates the need to administer operating system and runtimes and provides automated elastic provisioning and request-based pricing. But this deployment pattern is not a good fit for every service, because of long-tail latencies and the requirement to use an event/request-based programming model.</p><p>Docker containers are more flexible than serverless deployment and have more predictable latency. It&#39;s best to use Docker orchestration framework (e.g. Kubernetes) which manages containers on a cluster of machines. The drawback of this approach is that you must administer the operating system and runtimes and (most likely) Docker orchestration framework and VMs that it runs on. Benefits of this approach are: encapsulation of technology stack, isolated service instances and constrained service instance resources; and the drawbacks are: administration of the container infrastructure and possibly the VM infrastructure it runs on.</p><p>Virtual machines are a heavyweight deployment option, and it infuluences deployment time as well as resources. On the other hand, modern clouds (e.g. Amazon EC2) are highly automated and provide rich set of features. Having this in mind, it can be easier to deploy simple application using VMs than using Docker orchestration framework. Benefits of this approach are: VM image encapsulates technology stack, isolated service instances and usage of mature cloud infrastructure; and the drawbacks are: less-efficient resource utilization, relatively slow deployments and system administration overhead.</p><p>Deploying services as language-specific packages is generally best avoided, unless there is a small number of services. This approach is most likely be used to deploy monolithic application, but once there is something in place you should consider setting up a sophisticated deployment infrastructure. Benefits of this approach are: fast deployment and efficient resource utilization (when running multiple instances on the same machine or within the same process); and the drawbacks are: lack of encapsulation of technology stack, no ability to constrain the resources consumed by service instance, lack of isolation when running multiple service instances on the same machine and automatically determining where to place service instances can be challenging.</p><p>By using service mesh you can deploy a service to production, test it, and only then route production traffic to it. Separating deployment from release improves the reliability of rolling out new version of services.</p><p>Now we know which patterns to use when dissolving the monolith, but is it the right time to move to microservice architecture? To answer that ask if delivery process is slow or you have buggy software releases or you have poor scalability or … If there are multiple yes answers, then it&#39;s right time to move away from monolithic hell.</p><p>It&#39;s important to migrate to microservice by incrementally developing a strangler application: a new microservice application built around the existing monolithic application. Once a progress is made, demonstrating its value early and often will ensure business to support the migration effect. All changes to the monolithic application should be minimized as making changes can be time consuming, costly and risky. And after all we want to migrate them all to microservice(s). Deployment infrastructure is not needed as prerequisite, invest as minimal as possible in it, after the migration is done, then it will be clear what is actually needed to support the process.</p><p>There are three main strategies for strangling the monolith and incrementally replace it with microservices:</p><ul><li>implement new feature as service: by doing so it enables you to quickly and easily develop a feature using modern technology (or different freamework). It&#39;s a good way to demonstrate the value of migrating to microservice</li><li>separate presentation tier and backend: this results in two &quot;smaller&quot; applications. Although it&#39;s not a huge improvement, it will enable deployment of these two monoliths independently</li><li>break up the monolith by extracting functionality into services: for which it&#39;s important to focus on the services which will provide the most benefit (e.g. most in use, number of bugs is low, …)</li></ul><p>Newly developed service almost always needs to interact with the monolith (e.g. service needs monolith&#39;s data and functionality and vice versa). By developing integration glue, which consists of inbound and outbound adapters, we will enable this type of collaboration. But we must be aware of data model pollution, and to overcome this integration glue must implement anti-corruption layer, which is a layer of software that translates between domain models.</p><p>One way to minimize impact of the extraction monolithic functionality to a microservice is to replicate the data, that was moved to the service, back to the monolith&#39;s database. As monolith&#39;s database remains unchanged this will eliminate the need to make potentially widespread changes to the monolith&#39;s code base.</p><p>Extracting a microservice or developing a new one can require to implement sagas in which monolith needs to take part. It can be a challenging to implement a compensatable transaction that requires widespreaded changes in the monolith. Consequently, you need to be careful when extracting functionalities to microservice to avoid implementing of compensatable transactions in the monolith. Always check the sequence of steps and if they can be reoreded or if something else makes more sense to be extracted first.</p><p>When refactoring to a microservice architecture you need to simultaneously support the monolithic application&#39;s existing security mechanism. But there is a simple solution which can be used to modify the monolithic&#39;s login handler to generate a cookie containing a security token, which is then forwarded to the service by the API gateway.</p><p>Now that we are aware of all the patterns and how to migrate to microservice architecture it&#39;s your turn to take this path. Bare in mind that can be a bumpy road, with lot&#39;s of challenges but it will be rewarding. Before making a definitive decision to go for microservice architecture, stop and ask yourself: is this the best way to go and will it accelerate delivery of my company&#39;s software?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf4b06c96fd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Productively operating on legacy code]]></title>
            <link>https://milanbrankovic.medium.com/productively-operating-on-legacy-code-b03df1a7e0c6?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03df1a7e0c6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 06:17:12 GMT</pubDate>
            <atom:updated>2022-07-05T06:17:12.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnGrivimft-QCpuq7pAkiQ.jpeg" /></figure><p>What is legacy code? Is this the code which we changed couple of months ago, or is it the part of the code where nobody has the ambition to go? There is no definite answer, but one thing is sure, software changes daily! There are several reasons why: adding a feature, fixing bug, improving the design or optimizing resource usage. These changes influence either structure, functionality or resource usage.</p><p>It&#39;s easy to go down the &quot;if it works, don&#39;t touch it&quot; path, but this is not the right attitude. If you want to have a good, easy to extend and adapt system, you need to embrace the system as is, and tackle all the problems nobody else wants. In order to make your life easier you need to have tests which will help you on this journey. If there are no tests, this is the best time to start writing them! Nevertheless, when you need to make a change in the codebase you should follow these simple steps:</p><ul><li>identify change points</li><li>find test cases</li><li>break dependencies</li><li>write tests</li><li>make changes and refactor</li></ul><h4>Breaking changes</h4><p>Depending on the situation, making a simple change can vary. The main factor you need to consider when making changes is understanding of the code. Beside this, you should also consider the time between a change made and the real feedback about the change (lag time). The faster the feedback is the more rapid the change process is.</p><p>Dependencies can be problematic, but we can break them. In object-oriented programming we can break dependencies by introducing an interface. When we introduce more interfaces to break dependencies, rebuild time can go up slightly, but the benefit of extraction can be extraordinary.</p><p>To break dependencies the best collaborators would be fakes (stubs and mocks). Besides this “logical” helpers you also have “physical” helpers at hand: xUnit, IDEs, test coverage…</p><h4>Test-driven development (TDD)</h4><p>Adding a new feature to the legacy system might look intimidating, but with the test in place you can do this flawlessly. TDD is the most powerful feature-addition technique. The algorithm looks like this:</p><ul><li>write failing test</li><li>get it to compile</li><li>make it pass</li><li>remove duplication</li><li>repeat</li></ul><p>Note that TDD is not tied only to object-oriented programming, and it should be used as much as possible as it gives you confidence that something is working as expected even if you don&#39;t understand the code completely or you add a new feature without breaking the existing functionality.</p><h4>Programming by difference</h4><p>This technique allows us to make changes quickly, and we can use test to move to a cleaner design. The algorithm looks like this:</p><ul><li>Add new behavior (add new method to derived class)</li><li>Replace behavior (override base class method)</li><li>Re-use behavior (do nothing, defaulting to inherited behavior)</li><li>Only changes in behavior require changes in program code</li><li><em>is_a</em> relationship</li></ul><p>Although this technique breaks Liskov substitution principle, it’s good to think about how far classes are from normalized form every once in a while. Programming by difference lets you introduce variations quickly. When it’s done, we can use our tests to pin down the new behavior and move to more appropriate structure(s) when we need to.</p><p>There are multiple different techniques which can help us when we have to make a change. Let&#39;s look at them one by one.</p><h4>Sprout method</h4><p>When we need to add a feature to the system and we have identified it as a new code, write the code in a new method. Call it from the places where this new functionality needs to reside.</p><p>The advantage of it is you got your new code under test, the disadvantages is that you are not working on getting the entire code in test due to hard to break dependency or other reason that you may have and you might just not get it under test at all.</p><h4>Sprout class</h4><p>When you need to make changes to a class, but there is no way that you are going to be able to create objects of that class in a test in a reasonable amount of time, the best way would be to create another class to hold changes and use it from the source class.</p><p>The main advantage is that it allows you to move forward with the work with the confidence that there are no invasive changes done. The disadvantage is conceptual complexity.</p><h4>Wrap method</h4><p>There is additional possibility to add behavior which can be useful as well. Wrap method is a great way to introduce seams (places in your code where you can plug in different functionality) while adding new feature.</p><p>Advantages are: getting new tested functionality into application when we can&#39;t easily write tests for the calling code, it explicitly makes new functionality independent of existing functionality. On the contrary it can lead to poor names.</p><h4>Wrap class</h4><p>By using wrap class we can add behavior to a system without adding it to an existing class. This technique is called decorator pattern.</p><h4>Characterization tests</h4><p>There are two ways to find out what a method does: (a) dig into documentation and system requirements and (b) write tests and figure out based on the result. The first is time consuming, and also might lead to different understanding as not all of the requirements are preserved. The second approach can be use to characterize the actual behavior of code. These tests can be used as supporting tests for better understanding, but can also be used as real tests to validate system behavior, once we actually understand what the method is supposed to do.</p><p>The algorithm for writing this kind of test goes like this:</p><ul><li>use a method which we want to understand</li><li>write an assertion that you know it will fail</li><li>let the failure tell you what is the correct behavior</li><li>change the test so that it expects the behavior code produces</li><li>repeat</li></ul><h4>Characterization classes</h4><p>This approach is extension of previous one where we want to figure out on the class level.</p><h4>Skin and wrap API</h4><p>If your application is all API calls, then we can use a technique to make interfaces that mirror the API as close as possible and then create wrappers around API. To minimize the chances of mistakes, it&#39;s advised to preserve signatures. The end result is: wrappers can delegate to the real API in production code and to fakes during testing.</p><h4>Responsibility-based extraction</h4><p>With the help of refactoring tools we can use this technique to identify responsibilities in the code and extract method(s) for them. This approach can be applied to API hell as well, when API is more complicated.</p><h4>Scratch refactoring</h4><p>One of the best way to learn how legacy code works is to do some refactoring: extract methods, move things around, do whatever you want. This is a throwaway code which is helping you to understand what a method or a class do, and there is no need to write tests for it. But this approach has risk on its own: it may lead you to think that the system is doing something that it isn&#39;t, so be aware!</p><h4>Sensing variable</h4><p>When we are refactoring we want to preserve current behavior, but it does not mean that we cannot add any code. Sometimes it helps to add a variable to a class and use it to sense a condition(s) in method which we want to refactor. Once we are done with refactoring, we can get rid of the (introduced) variable.</p><h4>Preserve signatures</h4><p>Refactoring is an error-prone process, because during it we can: misspell things, use wrong data type, using one variable instead of another… (just to name a few). In order to make fewer mistakes, we can use cut/copy and paste, to break dependencies, keeping the entire method signature(s). Then we can work on the newly extracted method(s).</p><h4>Lean on the compiler</h4><p>The primary purpose of the compiler is to translate source code (written in any programming language) into another form. In statically typed languages, compiler can help even more. You can use its type checking to identify changes you want to make. The benefit of this technique is that you are letting the compiler guide you toward the changes you need to make.</p><h4>Adapt parameter</h4><p>Sometimes it can be hard to create the parameter for the method under test, and the outcome of the test relies of the &quot;state&quot; of parameter passed. We can do it in two ways: by extracting interface or by adapting parameter. By adapting parameter we are introducing a new interface that will wrap the parameter, or more specifically the behavior which we need. Then we can use it to update production code and add tests for it (with fakes).</p><h4>Break out method object</h4><p>Long methods are hard to work with. The simple idea to make it easier for test and maintenance is to move long method to a new class. Local variables in the old method can become instance variables in the new class, which often makes it easier to break dependencies and move code to cleaner state.</p><h4>Encapsulate global references</h4><p>This technique is extremely powerful when you are trying to break problematic dependencies on globals. The process is simple:</p><ul><li>identify globals for encapsulation</li><li>create a class with globals moved to it</li><li>comment out original declaration of globals and declare a global instance of the new class</li><li>exchange unresolved references with the name of global instance</li></ul><h4>Expose static method</h4><p>Sometimes we are dealing with the classes that cannot be instantiated in test, but there are some methods which does not use instance data or methods, we can turn those methods into static methods ad get them under test.</p><h4>Extract and override call</h4><p>Sporadically, there might be dependencies which are localized, but are getting in the way of testing. We can break that dependency, by extracting it, and prevent side effects in our tests. The steps we need to take are:</p><ul><li>identification and creation of a substitute method</li><li>replacing the call to a new method</li></ul><h4>Extract and override factory method</h4><p>Hard-coded initialization working in constructor can be very hard to work around in testing. If the creation was somewhere else, we can introduce some separations more easily. One of the options is extraction and overriding factory method, which takes care of extracting object creation sequence into a factory method (of the object).</p><h4>Extract and override getter</h4><p>Extract and override factory method has one flow, it does not work if it&#39;s not available (e.g. C++). In C++ you cannot call a virtual function in a derived class from base class&#39;s constructor. The idea on overcoming this issue is to introduce a getter for the instance variable that you want to replace with a fake object. Then refactor the code to use this getter everywhere, and also subclass the class and override getter to provide fake object for testing.</p><h4>Extract interface</h4><p>This technique is one of the safest techniques for dependency breaking, as it is supported by the compiler. The steps are pretty straightforward:</p><ul><li>create new interface</li><li>make the class implement the newly added interface</li><li>exchange the class with interface</li><li>introduce methods in the interface wherever there is a compiler warning</li></ul><h4>Extract implementer</h4><p>Extract interface is a handy technique, but it comes with the downside, which is naming. There is an opposite way, instead of extracting superclass/interface we can go the opposite way: extract subclass/implementer. Then we can turn the source class into an interface and move all non-public methods and variables to implementer.</p><h4>Introduce instance delegator</h4><p>If there are static methods in the project, chances are that you can work with them without major problems, unless they contain something that is difficult to depend on it a test. To overcome this problem is to replace the static call with the method call on an object, where static call is called from method call.</p><h4>Introduce static setter</h4><p>How to test global mutable data? How to test singleton? These things are hard to get under test, but there are some ways. The best would be not to have globals and/or singletons, but if there is an explicit need you can use the following approach:</p><ul><li>for globals: you can replace them with an object if they are sitting outside a class or are purely public static variables</li><li>for singletons: add a static setter (which will be used to replace the instance), and make constructor protected. Then you can create a subclass of singleton, create fresh object, and pass it to the setter</li></ul><h4>Parametrize constructor</h4><p>There are cases where dependency is hidden inside constructor. This situation is really hard to test, as dependency is tightly coupled inside the body. The best way to do resolve this situation is to externalize the dependency by passing it into the constructor.</p><h4>Construction of object with annoying parameter</h4><p>The best way to see if there are some constructor parameters which cause side effects upon object creation is to create a test which calls no-args constructor. If this is not possible, then use the constructor with the least number of parameters and set them all to null. By doing so we can inspect possible side effects. If we identified a tightly coupled or heavy weight object, we can introduce an interface and create fake test class to facilitate this.</p><h4>Parametrize method</h4><p>This technique is a counterpart of parametrize constructor, where extraction of the object created inside a method is passed as an argument.</p><h4>Pull up feature</h4><p>Sometimes you need to work with a cluster of methods which don&#39;t (in-)directly reference any of the bad dependencies. In this situation, this cluster of methods can be abstracted to superclass.</p><h4>Push down dependency</h4><p>Some classes have only few problematic dependencies, which can be removed by separating it from the rest of the code. In order to do this we make the class abstract and push down problematic things into a newly created class which extends this, now abstract, class.</p><h4>Subclass and override method</h4><p>This is one of the core techniques for breaking dependencies in object-oriented programs. The idea behind this approach is to use inheritance in the context of a test to nullify the behavior that you don&#39;t care about, or get access to behavior that you do care about.</p><p>To subclass and override method, do the following:</p><ul><li>identified the smallest set of methods you want to separate</li><li>make each of the methods overridable and adjust their visibility</li><li>create a new subclass that overrides the methods</li></ul><h4>Supersede instance variable</h4><p>Object creation in constructor can be problematic, but in most cases we can use some of the methods listed above. However, in some languages (e.g. C++), this is not possible. The steps look like this:</p><ul><li>identify the instance variable you want to supersede</li><li>create new supersede method (e.g. <em>supersedeInstanceA</em>, where InstanceA is the name of the variable you want to supersede)</li><li>in this method write the code to destroy previous instance and set the new value</li></ul><h4>Extract method</h4><p>The idea behind this refactoring is to systematically break up large existing methods into smaller ones. When this is done, our code becomes easier to understand</p><p>Other methods which can help you significantly:</p><ul><li>deletion of unused code</li><li>notes and/or sketching</li><li>explaining method/class/part of a system to a colleague and checking your mutual understanding</li><li>using unified naming</li><li>using heuristics to distinguish responsibilities (grouping methods, check for hidden methods, internal relationships, primary responsibility…)</li><li>pair programming</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03df1a7e0c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing web APIs]]></title>
            <link>https://milanbrankovic.medium.com/designing-web-apis-c67665bd288b?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/c67665bd288b</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 18:18:11 GMT</pubDate>
            <atom:updated>2022-06-29T18:18:11.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Rlb9pV2Vx7YfEs3FlEPRQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@larskienle?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lars Kienle</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Today you can hear API word used everywhere. But what exactly is API? If you check wiki page you will see:</p><blockquote>An <strong>application programming interface</strong> (<strong>API</strong>) is a connection between computers or between computer programs</blockquote><p>Simply speaking API is a contract provided to the outside world which guarantees specific outcome, and thus it is important that API is well designed.</p><p>In order to expose a good contract one must consider the following questions:</p><ul><li>who are the users?</li><li>what can they do?</li><li>how do they do it?</li><li>what do they need to do it?</li><li>what do they get in return?</li><li>where do the inputs come from?</li><li>how are the outputs used?</li></ul><p>Besides those questions, good API design is not influenced by different provider perspectives (data, code, business logic, software architecture and human organization).</p><p>Web API is an API which can be accessed over the web using the HTTP protocol. It is a framework that helps you create and develop HTTP based RESTful services.</p><p>In order to describe API you can use API description format. The OpenAPI specification (<a href="https://www.openapis.org/">OAS</a>) is one of the programming language-agnostic REST API description formats. The OAS is community driven and can be contributed to through its github repository. This format provides a simple and structured way to describe and share a programming interface. An API description format is a machine-readable document that can be used in numerous ways, including to generate API reference documentation. Always explore documentation in order to use the format efficiently.</p><h3>Designing usable APIs</h3><p>The easy-to-use APIs are understandable by people and programs, they tend to be as informative as possible, and both success and error feedback provide enough information to understand what has been done and/or fix the problem. To design totally straightforward flows, you must follow these rules:</p><ul><li>ensure that each goal provides a straightforward interaction</li><li>ensure that inputs and outputs are consistent between goals</li><li>when possible, prevent errors by adding data to existing goals to create new goals</li><li>when possible, aggregate goals but only if it makes sense for the consumer from a functional perspective</li><li>each goal of the chain must be stateless</li></ul><p>A well guessed API operations are created by defining conventions and following common practices and standards. Being consistent in API design makes the API easier to use and design process simpler. It is a good idea to have localization and internationalization features integrated in your API, so you should always check if it&#39;s needed. For each goal dealing with lists consider whether paging, filtering and sorting features will facilitate in use. An easy-to-use API is always guiding consumers, thus why you should consider providing as much metadata as possible (e.g. hypermedia links).</p><p>The API should return structured data. Data properties should be arranged properly. This can be done by: grouping properties in data structures, naming them by using patterns and/or sorting them. Also, you should pay attention on keeping the number of properties and depth levels as low as possible.</p><p>A well-organized API provides well-organized feedback. The feedback should be categorized and sorted by importance.</p><p>Last, but not least, goals need to be organized. Group goals by focusing on functionality and not representation. Besides, don&#39;t be tempted to create does-it-all goals, it&#39;s always better to have straightforward goals, without side-effects.</p><p>Always aim to split data structures, goals and even APIs into smaller but functionally significant elements when possible.</p><h4>Securing API</h4><p>API security is not something which can be neglected in the beginning and assumed that it will be handled later. Regularly, there are news about a company having been &quot;hacked&quot; through their APIs. This is why designer of API should contribute heavily to API security by minimizing attack surface.</p><p>To have API secured, operations should only expose and request what is actually needed, On the other hand consumers should only be allowed to use what they really need. Every API design should be done from the user&#39;s perspective, keeping in mind what is needed to control access.</p><p>In general, in software world, we must always check what can be requested, provided or done through API, as API involves sensitive material. Sensitive data controls a wide range; exactly what should be considered sensitive might not be obvious and should be identified with the help of tech, security, business and legal experts.</p><p>API designers must be aware of potential leaks due to the underlying protocol or architecture in order to fully secure the API design.</p><h4>Evolving API</h4><p>As every software which is heavily used, API also evolves. Each API evolution must be carefully designed in order to avoid breaking changes, which can cause problems not only on the consumer&#39;s but also the provider&#39;s side. Breaking changes can be introduced on the following:</p><ul><li>output data</li><li>input data</li><li>parameters</li><li>feedback (both success and error)</li><li>flows</li><li>security level</li></ul><p>Depending on the context, breaking changes might be acceptable (e.g. private APIs with consumers inside organization).</p><p>Both designers and developers of the API will have to live with previous poor design choices in order to avoid introducing benevolent but breaking changes. To evolve the design API versioning should be introduced. API versioning is design + implementation + product management matter.</p><p>Designing APIs with extensibility in mind eases the design for evolutions, lessens the risk of breaking changes and favors API reusability.</p><h4>Network-efficient API</h4><p>Network communication efficiency if an important topic that any API designer must be aware of. Network communication efficiency is important even in our day-to-day life, imagine that you need to setup &quot;smart&quot; kitchen with ADSL bandwidth… On mobile phones, network-inefficient APIs can have significant impact on user experience.</p><p>When designing network-efficient APIs you should take into consideration that optimization should be done first on protocol level, and then you can revisit the design level. Some ways that can be used in order to ensure network communication efficiency are:</p><ul><li>activating compression</li><li>persisting connections</li><li>enable caching</li><li>conditional requests</li></ul><p>On contrary, the ways to make network communication efficient on design level, one can design API with the following things in mind:</p><ul><li>enabling filtering</li><li>choosing relevant data for list representation</li><li>aggregating data</li><li>proposing different data representation</li><li>enabling expansion</li><li>enabling querying (by using GraphQL)</li><li>providing more relevant data</li><li>creating different API layers</li></ul><h4>Contextual API</h4><p>Consumer-to-provider communication is not the only way of communication. You can also design asynchronous goals, notify consumers of events, stream data and process multiple elements in a single call.</p><p>API designers need to be aware of consumers&#39; context(s) (including their network environments, habits and limitations). But we need also to carefully consider provider&#39;s limitations.</p><p>Personal preferences, fashion trends and cutting-edge technologies should be ignored and/or questioned in order to design ideal solution for all API design matters.</p><h4>API documentation</h4><p>Even the simple things need documentation. Everyday objects can come with various types of documentation to help users how to build them, as well as to help the people in charge of building these objects to actually build them.</p><p>For each type of documentation which needs to be delivered, API designers should participate in their creation. A detailed reference documentation is a good thing, but it&#39;s not enough. User guide must be there as well; it will provide all needed information on how to use API, including how to obtain credentials and tokens. Each of the documentation mentioned should be exhaustive in examples.</p><p>Leveraging an API description language can be of great help when creating documentation. A good documentation also helps to test API design, so by providing exhaustive information for each goal should lead to use API correctly.</p><p>When API evolves, it&#39;s crucial to keep track of modification and inform users of changes.</p><p>API documentation is vital for end user, but we must think about the people who will evolve and maintain the API. During API design process we need to stick to some guidelines. These guidelines will help during building and validating new APIs to be exposed. There are different types of guidelines:</p><ul><li>reference guidelines: a minimum API design guidelines that need to be created</li><li>use-case guidelines: ready-to-use &quot;recipes&quot; or solutions</li><li>design process guidelines: cover methods, tools and processes</li></ul><p>Those guidelines require us not only to write them, but also to evolve them and make people aware of them. Once guidelines are available our work is not finished! We need to review it from time to time, evolve it and fix it.</p><p>In order to design effective and useful APIs, API designers must challenge and deeply analyze the needs their API needs to fulfill. The design process must not be done alone, it&#39;s recommended to work with others on reviews.</p><h3>Conclusion</h3><p>API design process is hard, but rewarding. This article provides a guideline for establishing a path to well-design APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c67665bd288b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Storing images in database]]></title>
            <link>https://milanbrankovic.medium.com/storing-images-in-database-64c162e8fcf8?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/64c162e8fcf8</guid>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Thu, 29 Jul 2021 05:57:31 GMT</pubDate>
            <atom:updated>2021-07-29T05:57:31.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJPiAdoc9HypWyQVsxBaFw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hanzlog?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jisun Han</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Lazy loading images from database</h3><p>When it comes to storing content (images, documents, videos,…) inside the database we all know of BLOB (<strong>B</strong>inary <strong>L</strong>arge <strong>Ob</strong>ject), CLOB (<strong>C</strong>haracter <strong>L</strong>arge <strong>Ob</strong>ject), VARBINARY, etc. data types. They are used for storing large amount of data. They basically represent a binary string of variable length, stored as a sequence of bytes or octets.</p><p>By using some of the ORM frameworks (like Hibernate) the property of the entity class related to the mapping of file content would look like this:</p><pre>@Lob<br>@Column(name = &quot;file_content&quot;, columnDefinition = &quot;LONGBLOB&quot;)<br>private byte[] content;</pre><p>This is perfectly fine, and it will work for small files, but it comes with performance cost. If file content is large and you are querying for multiple files which satisfy some conditions, you can easily get the timeout on the client side, or OutOfMemoryException, or some other exception; as holding large volume of data in Hibernate comes with a cost.</p><p>The solution would be to lazy load the content, which will fetch the content only when it&#39;s actually needed. Hibernate supports the lazy fetching of individual properties.</p><p>There are several different techniques to mitigate this problem and depending on the database vendor some of them will work and some will not.</p><h4>Solution #1</h4><p>@Lob annotation works as lazy loading out-of-the-box and you don&#39;t need to do anything.</p><h4>Solution #1.1</h4><p>If the solution with only @Lob annotation does not work out-of-the-box, a little help from javaassits is necessary. Add the dependency</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.javassist&lt;/groupId&gt;<br>   &lt;artifactId&gt;javassist&lt;/artifactId&gt;<br>   &lt;version&gt;${javassist.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h4>Solution #2</h4><p>For some database vendors @Lob annotation does not work as it should. This depends on the Hibernate version (≥ 3.5) used in the project. The solution in this case should be to use @Type(type = &quot;org.hibernate.type.MaterializedBlobType&quot;)</p><h4>Solution #2.1</h4><p>If some solutions mentioned above do not work, with some additional specific annotations, like the ones below, the solutions would work</p><pre>@Lob<br>@Column(name = &quot;file_content&quot;, columnDefinition = &quot;LONGBLOB&quot;)<br>@Fetch(FetchMode.SELECT)<br>@Type(type=&quot;org.hibernate.type.MaterializedBlobType&quot;)<br>private byte[] content;</pre><h4>Solution #3</h4><p>By using @Basic(fetch=FetchType.LAZY) on the property itself. This solution requires activation of Hibernate <em>BytecodeEnhancement</em></p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.hibernate.orm.tooling&lt;/groupId&gt;<br>    &lt;artifactId&gt;hibernate-enhance-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;${hibernate.version}&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;configuration&gt;<br>                <strong>&lt;enableLazyInitialization&gt;true&lt;/enableLazyInitialization&gt;</strong><br>            &lt;/configuration&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;enhance&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>The goal of the Hibernate Enhance plugin is to instrument the JPA entity bytecode in order to improve the effectiveness and efficiency of the associated data access operations. By setting the enableLazyInitialization to true, Hibernate changes the bytecode of the getter and setter methods to intercept the call and trigger the property initialization on demand.</p><h4>Solution #4</h4><p>Instead of doing equilibristics with hibernate annotations, one may just try converting the field from String/byte[] into Clob (or Blob):</p><pre>@Lob  <br>@Basic(fetch=FetchType.LAZY)  <br>@Column(name = &quot;file_content&quot;, columnDefinition = &quot;LONGBLOB&quot;)<br>public Blob getFieldBlob() {  <br>  return content;  <br>}  </pre><pre>public void setFieldBlob(final Blob blobContent) {  <br>  this.content = blobContent;  <br>}  </pre><pre>@Transient  <br>public String getField() {  <br>  if (getFieldBlob() == null){  <br>    return null;  <br>  } <br> <br>  try {  <br>    return MyOwnUtils.readStream(getFieldBlob().getCharacterStream());  <br>  } catch (Exception e) {  <br>    e.printStackTrace();  <br>  }  </pre><pre>  return null;  <br>}  </pre><pre>public void setField(final String field)  <br>{  <br>  this.fieldBlob = Hibernate.createBlob(field);  <br>}</pre><h4>Solution #5</h4><p>This solution is the way to go and works for all db vendors. The core of the implementation lies in mapping of multiple sub-entities to the same database table.</p><pre>@MappedSuperclass<br>public class BaseAttachment {<br><br>    @Id<br>    @GeneratedValue(generator = &quot;uuid&quot;)<br>    @GenericGenerator(name = &quot;uuid&quot;, strategy = &quot;uuid2&quot;)<br>    @Column(name = &quot;id&quot;)<br>    private String id;<br><br>    @NotBlank<br>    @Column(name = &quot;name&quot;, nullable = false)<br>    private String name;<br><br>    @NotBlank<br>    @Column(name = &quot;file_type&quot;, nullable = false)<br>    private String fileType;<br>}</pre><pre>@Entity<br>@Table(name = &quot;attachment&quot;)<br>public class AttachmentSummary extends BaseAttachment {<br>}</pre><pre>@Entity<br>@Table(name = &quot;attachment&quot;)<br>public class Attachment extends BaseAttachment {<br><br>    @Lob<br>    @Column(name = &quot;data&quot;, nullable = false, columnDefinition = &quot;LONGBLOB&quot;)<br>    private byte[] data;<br>}</pre><h4>Solution #5.1</h4><p>The similar solution to this is extracting file content to one-to-one relationship which will be lazy loaded.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64c162e8fcf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java application performance management]]></title>
            <link>https://milanbrankovic.medium.com/java-application-performance-management-3d1ea3a5719?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d1ea3a5719</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 06:01:08 GMT</pubDate>
            <atom:updated>2021-07-22T06:01:08.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlka2FuTC3NgSgSAaTSIWw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@standsome?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Standsome Worklifestyle</a> on <a href="https://unsplash.com/s/photos/managment?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Building application and writing code is one thing. It is challenging, but also rewarding. Once you have your application finished you often forget to pay attention how does it behave under real world pressure. There are times when you wish to optimize some workflows or check why application is using so much memory or examine why application is becoming unresponsive; thus you start with performance management. There are two main influence factors:</p><ul><li>memory consumption</li><li>total program runtime/application speed</li></ul><p>The performance of a compiled Java program depends on how optimally its given tasks are managed by the host Java virtual machine (JVM), and how well the JVM exploits the features of the computer hardware and operating system in doing so. Thus, any Java performance test or comparison has to always report the version, vendor, OS and hardware architecture of the used JVM.</p><p>Let&#39;s check the different aspects how to asses and improve application performance.</p><h3><strong>Code compilation</strong></h3><p>It is quite revealing to watch the JIT compiler work while a Java application is running. By setting the flag -XX:+PrintCompilation we can enable some simple output regarding the bytecode to native code compilation.</p><p>Whenever a method is compiled, a line is printed to the output. Each line consists of (1) a number of milliseconds since VM started, (2) order in which method/code block is compiled, (3) compilation level cache, (4) method name.</p><p>If you want to see the same information on some remote machine where you cannot see the console output you can use the following command:</p><pre>java -XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation &lt;class name&gt;</pre><p>which will produce log file with compilation results in it.</p><p>One of the interesting things is to find the size of the code cache. This can be done by using -XX:+PrintCodeCache. The maximum number of code cache is dependent on which version of java you are using. We can change the code cache size with these flags:</p><ul><li>-XX:InitialCodeCacheSize=n: initial size</li><li>-XX:ReservedCodeCacheSize=n: max size</li><li>-XX:CodeCacheExpansionSize=n: how quickly the cache can grow</li></ul><p>the size can be in bytes, kilobytes (by adding suffix k), megabytes (by adding suffix m),…</p><p>There is also an application support for monitoring the code cache size. By using JConsole application you will get quite nice graph representation.</p><p>Additionally, there are two types of compiler optimizations which are part of JDK — a client-side offering (-client), and a VM tuned for server applications (-server). Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers.</p><p>By typing -XX:+PrintFlagsFinal the command will print the values of all of the jvm configuration parameters and/or values. This list is rather huge, so you can pipe this command with grep in order to find the configuration you are interested in.</p><p>By running previous command you can see how many threads can be used for compilation (check CICompilerCount configuration property). You can increase or decrease the number of threads by setting CICompilerCount property. Minimum number of threads is two. There is one additional flag CompileThreshold which is quite interesting. The value set for this flag says it will need to do x number of calls to a method, in order to get it compiled. You can decrease this value and tweak it for your purposes.</p><h3>How is memory organized?</h3><p>Java separates its memory into two areas: <em>heap</em> and <em>stack</em>.</p><h4>Heap</h4><p>New objects are created and placed on the heap. Once your application has no reference anymore to an object the Java garbage collector is allowed to delete this object and remove the memory so that your application can use this memory again. The heap is logically divided in three spaces:</p><ul><li><em>young generation</em>: eden &amp; survivor. All the new objects are allocated in this part of the memory. Whenever this memory gets filled, the garbage collection is performed</li><li><em>old generation</em><strong>: </strong>all of the long lived objects which have survived many rounds of minor garbage collection (cleanup of young generation space) are stored in this area. Whenever this memory gets filled, the garbage collection is performed.</li><li><em>PermGen/metaspace</em>: special heap space separated from the main memory heap. The JVM keeps track of loaded class metadata in the PermGen alongside with all static content. This space is replaced with Metaspace from Java 1.8</li></ul><h4>Stack</h4><p>Stack is where the method invocations and the local variables are stored. If a method is called then its stack frame is put onto the top of the call stack. The stack frame holds the state of the method and the values of all local variables. The method on the top of the stack is always the current running method for that stack. Threads have their own call stack.</p><h4>Garbage collector</h4><p>The JVM automatically re-collects the memory which is not used any more. The memory for objects which are not referenced any more will be automatically released by the garbage collector. The garbage collector is doing sweeping from time to time automatically.</p><h3>Memory settings</h3><p>The PermGen space size can be set with the following flags:</p><pre>-XX:PermSize=n<br>-XX:MaxPermSize=n</pre><p>Strings are placed inside the string pool (which is part of the heap). The string pool is implemented as hash map. If the size of the bucket is too small or too big, querying for specific string can be inefficient. We can use -XX:+PrintStringTableStatistics flag to see the usage of string pool. In order to change string pool size we can use the following option -XX:StringTableSize=n which will set how big string table will be (how many buckets will be there). The value which should be set should be prime number. But as string pool lives on the heap we must ensure that the heap size is big enough to hold other objects (except strings) as well. We can set heap size with</p><pre>-XX:InitialHeapSize=n   (alternative -Xms)<br>-XX:MaxHeapSize=n       (alternative -Xmx)</pre><p>In order to see the graphical representation and monitor heap size usage over time you can use (J)VisualVM.</p><p>Another useful properties which can be set are:</p><pre>-XX:+HeapDumpOnOutOfMemoryException<br>-XX:HeapDumpPath=/path/to/file</pre><p>This will generate heap dump, and write it to the file, once OutOfMemoryException is thrown. This is useful when checking memory leaks. The same dump can be fetched from VisualVM tool. In order to analyze heap dump you can use this <a href="http://www.eclipse.org/mat/">tool</a>.</p><h3>Garbage collector tuning</h3><p>In order to monitor how often the garbage collection is taking place you can use the following argument:</p><pre>-verbose:gc</pre><p>As mentioned previously heap is separated in several spaces which are dynamically sized. There is an argument which can turn off automated heap allocation sizing</p><pre>-XX:-UseAdaptiveSizePolicy</pre><p>This flag is enabled by default.</p><p>You can use the following flags to fine tune the heap size</p><ul><li>setting how much bigger old generation will be compared to young generation space</li></ul><pre>-XX:NewRatio=n</pre><ul><li>setting how much of the young generation space should be taken up by survivor spaces</li></ul><pre>-XX:SurvivorRatio=n</pre><ul><li>setting how many generation the object needs to survive before becoming part of the old generation space (max value is 15)</li></ul><pre>-XX:MaxTenuringThreshold=n</pre><p>There are three types of garbage collectors:</p><ul><li><strong>serial</strong>: all of the threads are paused in order to enable garbage collection to run</li></ul><pre>-XX:+UseSerialGC</pre><ul><li><strong>parallel</strong>: will perform garbage collection in parallel. This is the default option for Java8 and below</li></ul><pre>-XX:+UseParallelGC</pre><ul><li><strong>mostly concurrent</strong>: close to real-time garbage collection where the application is not paused while the garbage collection is taking place. There are two sub-types of this type:</li></ul><pre>-XX:+UseConcMarkSweepGC<br>-XX:+UseG1GC </pre><p>In Java9 MarkSweepGC was used as default, and from Java10 G1GC is chosen as default. This garbage collector has been available in Java8, but the performance of it was drastically improved in Java10.</p><h3>Assessing performance</h3><p><a href="https://github.com/openjdk/jmc">openjdk/jmc</a></p><p><a href="https://github.com/openjdk/jmh">https://github.com/openjdk/jmh</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d1ea3a5719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software testing]]></title>
            <link>https://milanbrankovic.medium.com/software-testing-330e22bb9c9c?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/330e22bb9c9c</guid>
            <category><![CDATA[testing-techniques]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 06:58:57 GMT</pubDate>
            <atom:updated>2021-07-15T06:58:57.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rXejhcKLorK7JiXnQH-tg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Software testing is an important thing when building a product. It can find out issues before it reaches customer, it can also reduce cost of fixing the issue if found early enough. Let&#39;s dive deep in ways of testing. We will use picture which are powerful enough to express the meaning of testing strategy.</p><h3>Boundary value testing</h3><h4># Normal boundary value testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Br0RTCDq-LllXuxuhzsRUg.png" /></figure><h4># Robust boundary value testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xL8hfF7BSZNQJETd5BZPFw.png" /></figure><h4># Worst-case boundary value testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIaRh7CaS089SNyYHbPNsA.png" /></figure><h4># Robust worst-case boundary value testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZrZ1FEP0HaK5Cou5ZBCKg.png" /></figure><h4># Random testing</h4><h3>Equivalence class testing</h3><h4># Traditional equivalence class testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7eZtK060NcxWf4ak3ZceyQ.png" /></figure><h4># Weak normal equivalence class testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQg6I4p17PbDm5g3n5CXAw.png" /></figure><h4># Strong normal equivalence class testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71lz6a7-U34avpDeTOd50A.png" /></figure><h4># Weak robust equivalence class testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FswjJYPAWz1mAkB8yFrvVA.png" /></figure><h4># Strong robust equivalence class testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QKYexMOAV7iToOVJnJzEg.png" /></figure><h4># Edge testing</h4><p>Hybrid of boundary value analysis and equivalence class testing</p><h3>Decision table-based testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*q_EgvMt64K91q1jUSCF2Lg.jpeg" /></figure><h3>Path testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*HfNuAikpuDfJXSatkr_Qzg.jpeg" /></figure><h4># Statement testing</h4><h4># DD (decision-to-decision) path testing</h4><h4># Simple loop coverage</h4><h4># Predicate outcome testing</h4><h4># Dependent pairs of DD-paths</h4><h4># Complex loop coverage</h4><h4># Multiple condition coverage</h4><h4># Statistically significant coverage</h4><h4># All possible paths coverage</h4><h3>Data flow testing</h3><p>Similar to path testing, but with the difference that it is focused on data. Data flow testing refers to forms of structural testing that focus on the points at which variables receive values and the points at which these values are user (or referenced).</p><h4># Slice testing</h4><h3>Life cycle-based testing</h3><h4># Traditional waterfall life cycle testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*1SETyZAFgnV1JarzwtUaew.jpeg" /></figure><h4># V model waterfall life cycle testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*aL_etuLKlsPJRtLoJ16e0w.jpeg" /></figure><h4># Agile testing</h4><ul><li>Extreme programming (XP)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*-xQItsild0JBLFJ0jYqKiw.png" /></figure><ul><li>Test-driven development (TDD)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*xKhtBq1_zvL_WVEIl1hQgw.png" /></figure><ul><li>Scrum</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VPHi09nVf7DjM-ehromUg.png" /></figure><h3>Model based testing</h3><p>The essence of this type is summarized in the following steps:</p><ol><li>model the system</li><li>identify threads of system behavior in the model</li><li>transform these threads into test cases</li><li>execute test cases and record results</li><li>revise the model as needed and repeat the process</li></ol><h3>Integration testing</h3><h4># Decomposition based testing</h4><ul><li>top-down integration testing</li><li>bottom-up integration testing</li><li>sandwich integration testing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*qwVOqCCWcWtGCCjeOhyyrA.png" /></figure><h4># Call graph based testing</h4><ul><li>pairwise integration testing</li><li>neighborhood integration testing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*3yr0eH1xA6UBHxH50_bLSQ.jpeg" /></figure><h4># Path based integration testing</h4><h3>System testing</h3><h4># Operational profiles</h4><h4># Risk-based testing</h4><h4># Stress testing</h4><h3>Exploratory testing</h3><p>This is just a high level overview of different types of software testing. In order to explore more and get better understanding of each and every one you can find a lot of great books and articles online. Also you can find good courses and certifications online (if you to become certified tester).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330e22bb9c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things to consider when designing objects]]></title>
            <link>https://milanbrankovic.medium.com/things-to-consider-when-designing-objects-cc30a3d5857?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc30a3d5857</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 07:32:49 GMT</pubDate>
            <atom:updated>2021-03-09T07:32:49.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxsWFVsApD_x-EVp4ujY-g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jamesponddotco?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Pond</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>It is very simple to learn how to code, but it is very hard to make the code readable/understandable, clean and robust. Let&#39;s try to mention some principles in making this easier.</p><h4>#1 Inject dependencies and configuration values as constructor arguments</h4><pre>public interface Worker {<br>    public void work();<br>}<br>    <br>public class ConstructionWorker implements Worker {<br>    private List&lt;Tool&gt; tools;<br>        <br>    public ConstructionWorker(final List&lt;Tool&gt; tools) {<br>        this.tools = tools;<br>    }<br>        <br>    <a href="http://twitter.com/Override">@Override</a><br>    public void work() {<br>       // use tools<br>    }<br>}</pre><h4>#2 Keep configuration properties together</h4><p>before:</p><pre>public class ApiClient {<br>    private String username;<br>    private String password;<br>        <br>    public ApiClient(final String username, final String password) {<br>       this.username = username;<br>       this.password = password;<br>    }<br>}</pre><p>after:</p><pre>class Credentials {<br>    private String username;<br>    private String password;</pre><pre>    // constructor and getters</pre><pre>}</pre><pre>public class ApiClient {<br>    private Credentials credentials;<br>        <br>    public ApiClient(final Credentials credentials) {<br>       this.credentials = credentials;<br>    }<br>}</pre><h4>#3 Inject what you need (nothing more/nothing less)</h4><h4>#4 All constructor arguments should be required</h4><p>before:</p><pre>class Credentials {<br>    private String username;<br>    private String password;</pre><pre>// constructor and getters</pre><pre>}</pre><pre>public class ApiClient {<br>    private Optional&lt;Credentials&gt; credentials;<br>    private RestTemplate restTemplate;<br>        <br>    public ApiClient(final Optional&lt;Credentials&gt; credentials, <br>                     final RestTemplate restTemplate) {<br>       this.credentials = credentials;<br>       this.restTemplate = restTemplate;<br>    }</pre><pre>    public String fetchData() {<br>        // if credentials are present add to HttpHeader<br>        // perform work<br>    }</pre><pre>}</pre><p>after:</p><pre>class Credentials {<br>    private String username;<br>    private String password;</pre><pre>// constructor and getters</pre><pre>}</pre><pre>public class ApiClient {<br>    private Credentials credentials;<br>    private RestTemplate restTemplate;<br>        <br>    public ApiClient(final Credentials credentials, <br>                     final RestTemplate restTemplate) {<br>       this.credentials = credentials;<br>       this.restTemplate = restTemplate;<br>    }</pre><pre>    public String fetchData() {<br>        // add credentials to HttpHeader<br>        // perform work<br>    }</pre><pre>}</pre><h4>#5 Only use constructor injection</h4><h4><strong>#6 Turn static dependency into object dependency</strong></h4><p>before:</p><pre>class StaticClass {<br>    public static void staticMethod() {}<br>}</pre><pre>public class MyClass {<br>    // constructor and getters</pre><pre>    public String doWork() {<br>        StaticClass.staticMethod();<br>        // do some other work<br>    }<br>}</pre><p>after:</p><pre>class StaticClass {<br>    public static void staticMethod() {}<br>}</pre><pre>public class MyClass {<br>    private StaticClass dependency;</pre><pre>    // constructor and getters</pre><pre>    public String doWork() {<br>        this.dependency.staticMethod();<br>        // do some other work<br>    }<br>}</pre><h4>#7 Turn complicated functions into object dependencies</h4><p>before:</p><pre>public class Resource {<br>    // constructor and getters</pre><pre>    public String getDataById(final String id) {<br>        // fetch data by id<br>        return jsonEncode(data);<br>    }</pre><pre>    public String jsonEncode(final Object data) {<br>        // compicated work<br>    }<br>}</pre><p>after:</p><pre>public interface Encoder {<br>    public String encode(final Object data);<br>}</pre><pre>public class JsonEncoder implementes Encoder {<br>    @Override<br>    public String encode(final Object data) {<br>        // encode as json<br>    }<br>}</pre><pre><br>public class Resource {<br>    private final Encoder encoder;<br>    <br>    // constructor and getters</pre><pre>    public String getDataById(final String id) {<br>        // fetch data by id<br>        return encoder.encode(data);<br>    }<br>}</pre><h4>#8 Make system calls explicit</h4><p>before:</p><pre>public class Service {<br>    // constructor and getters</pre><pre>    public List&lt;Object&gt; getData() {<br>        final Calendar calendar = new GregorianCalendar(pdt);</pre><pre>        return findDataInWeek(calendar.get(Calendar.WEEK_OF_YEAR))<br>    }</pre><pre>    public List&lt;Object&gt; findDataInWeek(int weekNum) {<br>    }</pre><pre>}</pre><p>after:</p><pre>public class Service {<br>    private Calendar calendar;</pre><pre>    // constructor and getters</pre><pre>    public List&lt;Object&gt; getData() {<br>        return findDataInWeek(calendar.get(Calendar.WEEK_OF_YEAR))<br>    }</pre><pre>    public List&lt;Object&gt; findDataInWeek(int weekNum) {<br>    }</pre><pre>}</pre><h4>#9 Task related data should be passed as method argument</h4><h4>#10 Prevent changing behavior of a service after instantiation</h4><pre>public class Service {</pre><pre>    private boolean shouldReportErrors = true;</pre><pre>    // constructor and getters<br>    // only setter for shouldReportErrors </pre><pre>    public String doWork() {<br>        // ...<br>        if (shouldReportErrors) { &lt;- changes behavior based on value<br>            // report error(s)<br>        }<br>        // ...<br>    }<br>}</pre><h4>#11 Constructor should be used only for properties assignment</h4><h4>#12 Throw invalid argument exception when constructing object if an argument is invalid</h4><pre>public class Fighter {<br>    private final int rank;</pre><pre>    public Fighter(final int rank) {<br>        if (rank &lt; 0) {<br>            throw new InvalidArgumentException(&#39;Fighter rank should be positive&#39;);<br>        }<br>        this.rank = rank;<br>    }<br>}</pre><h4>#13 Don&#39;t use custom exception class for invalid argument when constructing an object</h4><h4>#14 Define as little as possible service entry points</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*LkFLOdIAtGBMlVGJjEhHvw.png" /><figcaption>A &amp; B may produce different results if both have exposed the same operation for fetching common data through A1 &amp; B1</figcaption></figure><h4>#15 Extract object when validation is performed on multiple places</h4><p>before:</p><pre>public class FileDownloadService {<br>    private final String protocol;<br>    private final String host;<br>    private final String port;</pre><pre>    public FileDownloadService(final String protocol, final String host, final String port) {<br>        if (!isProtocolValid(protocol)) {<br>            throw new InvalidArgumentException(&#39;...&#39;);<br>        }<br>        if (!isHostValid(host)) {<br>            throw new InvalidArgumentException(&#39;...&#39;);<br>        }<br>        if (!isPortValid(port)) {<br>            throw new InvalidArgumentException(&#39;...&#39;);<br>        }</pre><pre>        this.protocol = protocol;<br>        this.host = host;<br>        this.port = port;<br>    }<br>}</pre><p>after:</p><pre>public class FileServer {<br>    private final String protocol;<br>    private final String host;<br>    private final String port;</pre><pre>    public FileServer(final String protocol, final String host, final String port) {<br>        if (!isProtocolValid(protocol)) {<br>            throw new InvalidArgumentException(&#39;...&#39;);<br>        }<br>        if (!isHostValid(host)) {<br>            throw new InvalidArgumentException(&#39;...&#39;);<br>        }<br>        if (!isPortValid(port)) {<br>            throw new InvalidArgumentException(&#39;...&#39;);<br>        }</pre><pre>        this.protocol = protocol;<br>        this.host = host;<br>        this.port = port;<br>    }<br>}<br></pre><pre>public class FileDownloadService {<br>    private final FileServer fileServer;</pre><pre>    public FileDownloadService(final FileServer fileServer) {<br>        this.fileServer = fileServer;<br>    }<br>}</pre><h4>#16 Extract new object to represent composite value</h4><p>before:</p><pre>public class Product {<br>    private final BigDecimal amount;<br>    private final String currency;<br>    // other properties</pre><pre>    public Product(final BigDecimal amount, final String currency, // other properties) {<br>        <br>    }<br>}</pre><p>after:</p><pre>public class Money {<br>    private final BigDecimal amount;<br>    private final String currency;<br>}</pre><pre>public class Product {<br>    private final Money money;<br>    // other properties</pre><pre>    public Product(final Money money, // other properties) {<br>        <br>    }<br>}</pre><h4>#17 Use assertions to validate constructor arguments</h4><h4>#18 Pass dependencies as method arguments instead of injecting them</h4><p>before:</p><pre>public interface Encoder {<br>    public String encode(final Object data);<br>}</pre><pre>public class JsonEncoder implementes Encoder {<br>    @Override<br>    public String encode(final Object data) {<br>        // encode as json<br>    }<br>}</pre><pre>public class Resource {<br>    private final Encoder encoder;<br>    <br>    // constructor and getters</pre><pre>    public String encodeData(final Object data) {<br>        // fetch data by id<br>        return encoder.encode(data);<br>    }<br>}</pre><p>after:</p><pre>public interface Encoder {<br>    public String encode(final Object data);<br>}</pre><pre>public class JsonEncoder implementes Encoder {<br>    @Override<br>    public String encode(final Object data) {<br>        // encode as json<br>    }<br>}</pre><pre>public class Resource {<br>    <br>    // constructor and getters</pre><pre>    public String encodeData(final Encoder encoder, final Object data) {<br>        // fetch data by id<br>        return encoder.encode(data);<br>    }<br>}</pre><h4>#19 Create methods to construct object from primitive type</h4><pre>public class LocalDate {<br>    public static parse(final String date) { ... }<br>}</pre><p>see more: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html</a></p><h4>#20 Use private constructor to enforce constraints</h4><p>see details of: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html</a></p><h4>#21 Don&#39;t test constructors</h4><h4>#22 Use replaceable, anonymous and immutable values when creating value objects</h4><h4>#23 Replace values instead of modifying them</h4><p>see details of: <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html#minus(long,java.time.temporal.TemporalUnit)">https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html#minus(long,java.time.temporal.TemporalUnit)</a></p><h4>#24 On a mutable object modifier methods should be command methods</h4><pre>public class Fighter {<br>    private final int rank;<br>    private final Position position</pre><pre>    public Fighter(final int rank, final Position position) {<br>        if (rank &lt; 0) {<br>            throw new InvalidArgumentException(&#39;Fighter rank should be positive&#39;);<br>        }<br>        this.rank = rank;<br>        this.position = position;<br>    }</pre><pre>    public void move(final Direction direction) {<br>        this.position = this.position.move(direction);<br>    }</pre><pre>    public Position currentPosition() {<br>        return this.position;<br>    }</pre><pre> }</pre><h4>#25 Properties and methods should have declarative names</h4><h4>#26 When comparing two objects they should be fully compared (all properties)</h4><h4>#27 When calling modifier on an object it should leave it in a valid state</h4><pre>public class Money {<br>    private final BigDecimal amount;<br>    private final String currency;</pre><pre>    // constructor and getters</pre><pre>    public Money withdraw(final BigDecimal amount) {<br>        if (this.amount - amount &lt; 0) {<br>            // throw InvalidWithdrawalException<br>        }<br>        <br>        // process withdrawal <br>    }<br>}</pre><h4>#28 When calling modifier on an object have a precondition check</h4><h4>#29 When throwing exception on a check failure add detailed message</h4><h4>#30 Query methods should return single-type value</h4><h4>#31 Object should have proper boundaries set</h4><p>before:</p><pre>public class Money {<br>    private final BigDecimal amount;<br>    private final String currency;<br>}</pre><pre>public class Product {<br>    public Money amount;</pre><pre>    public boolean shouldApplyDiscount() { // ...<br>    } </pre><pre>    public Money fixedDiscountAmount() { // ...<br>    }<br>}</pre><pre>amount = new Money();<br>if (product.shouldApplyDiscount()) {<br>    amount = product.getAmount().substract(product.fixedDiscountAmount());<br>}</pre><p>after:</p><pre>public class Money {<br>    private final BigDecimal amount;<br>    private final String currency;<br>}</pre><pre>public class Product {<br>    public Money amount;</pre><pre>    private boolean shouldApplyDiscount() { // ...<br>    }</pre><pre>    private Percentage discount() { // ...<br>    }</pre><pre>    public Money getNetAmount() {<br>        if (shouldApplyDiscount()) {<br>             return this.discount().applyTo(this.amount);<br>        }<br>    }<br>}</pre><pre>amount = product.getNetAmount();</pre><h4>#32 Query methods should not issue commands</h4><h4>#33 Use queries to collect information and commands to take next steps</h4><h4>#34 Use mocks to verify calls to command methods</h4><h4>#35 Separate read from write objects</h4><h4>#36 Compose abstraction to achieve complicated behavior</h4><pre>public interface Encoder {<br>    public List&lt;String&gt; encode(final Object data);<br>}</pre><pre>public class JsonEncoder implementes Encoder {<br>    @Override<br>    public List&lt;String&gt; encode(final Object data) {<br>        // encode as json<br>    }<br>}</pre><pre>public class MultipleTypeEncoder implementes Encoder {<br>    private final List&lt;Encoder&gt; encoders;</pre><pre>    // constructor and getters</pre><pre>    @Override<br>    public List&lt;String&gt; encode(final Object data) {<br>        final List&lt;String&gt; result = new ArrayList&lt;&gt;();<br>        for(final Encoder encoder : encoders) {<br>            result.add(encoder.encode(data));<br>        }<br>        return result;<br>    }<br>}</pre><h4>#37 Don&#39;t use inheritance to change an object behavior</h4><h4>#38 Mark classes as final whenever possible</h4><h4>#39 Mark method as private whenever possible</h4><h4>#40 Mark properties as private as default</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc30a3d5857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring microservices]]></title>
            <link>https://milanbrankovic.medium.com/monitoring-microservices-e0f89496fa9e?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f89496fa9e</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 07:32:28 GMT</pubDate>
            <atom:updated>2021-03-02T07:32:28.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkYqlKBmIecZBGzOIDOFKA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ibrahimboran?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ibrahim Boran</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Microservices: monitoring and observability</h3><p>Observing system is a crucial thing for having robust system running in production. You need to be able to know how the components are interaction and how the infrastructure is behaving. It&#39;s fundamental to know as early as possible when something is not operating as expected.</p><p>A robust monitoring system allows gathering metrics from services and infrastructure and using those metrics to gather insights from the operation of a system. Monitoring system should provide a way to collect data and store, display and analyze it. Monitoring does not only allows you to react to issues, it can be used to predict system behavior or to provide data for business analytic purposes (by using collected metric).</p><p>Monitoring stack is constructed out of:</p><ul><li><em>metrics</em></li><li><em>logs</em></li><li><em>traces</em></li></ul><p>Each of these components feeds aggregated data from multiple services into its own dashboard. Monitoring individual service will be of little to no use because services provide isolation, but they are acting as an organism. They are dependent on each other and on the infrastructure layer (databases, caches, queues, network…).</p><h4>Metrics</h4><p>Monitoring system should allow you to know what is broken and why. With it it should be easy to quickly reveal any symptom and use the available monitors to determine causes. Found symptoms and causes vary depending on the observation point, so you must be sure that you are looking from the correct place.</p><p>There are four signals one should focus on while collecting metrics from any system:</p><ul><li><strong>latency</strong>: the time which passes between a request is made to a given service and when the service completes it</li><li><strong>errors</strong>: number or request that don&#39;t result in a successful outcome</li><li><strong>traffic</strong>: the demand of a system</li><li><strong>saturation</strong>: measurement of the service capacity (usually CPU, memory and network)</li></ul><p>It is important to determine which type of metric is the best suited for a given observed resource. There are several different types:</p><ul><li><strong>counters</strong>: single numerical value representing cumulative metric (e.g. number of requests, number of errors, bytes transmitted, …)</li><li><strong>gauges</strong>: single numerical value that can go up or down on a given scale (e.g. number of connections to a database, memory used, CPU used, average load,… )</li><li><strong>histograms</strong>: sample observations categorized in buckets (per type, time,…) (e.g. I/O latency, latency of request,…)</li></ul><p>Once a monitoring system is in place you should be able to determine when somebody needs to be alerted when a certain condition(s) in the system is met. Moreover alerts need to be prioritized and categorized because most likely the service(s) or infrastructure will trigger multiple alerts.</p><h4>Logs</h4><p>As mentioned earlier, multiple services will be involved in providing functionality to a user. Without central access point to data it is hard to understand what is going on inside the system. To be able to achieve observability data must be collected from multiple sources; not only from the running service but also from the infrastructure.</p><p>To effectively store and make log data searchable, there must be a consistent format (agreed on an engineering team) which will guarantee that it can be stored and processed effectively. There can be data from multiple sources which you may collect and use (e.g. application logs, database logs, network logs…), and for some of them you want be able to control the format, so you need to cope with their specifications.</p><p>In order to understand the behavior in the system, logs need to include certain information:</p><ul><li><em>timestamps</em></li><li><em>identifiers</em></li><li><em>source</em></li><li><em>level/category</em></li></ul><p>Each of the log entries needs to be human-readable, but at the same time easily parseable by a machine. One of the most used formats is JSON.</p><p>Once the structure is in place you need to carefully decide which information will be included in the logs which will be sent. Things like passwords, credit card numbers, medical IDs, and other potentially sensitive personal data need to be excluded in order to comply with General Data Protection Regulation (GDPR). General rule would be to log as little information as possible, avoiding any personal data in logs, and taking extra care with reviewing the data which will be sent out from the service.</p><h4>Traces</h4><p>All services should propagate an ID field which will allow you to follow execution path of a request through the system. With this set up, logs can be grouped under the same context.</p><p>To better reconstruct the journey of a request through the system you can set up distributed tracing which will allow visualization of the flow of execution between services. This will provide insights on how long each operation takes, and how the services are related to each other while performing the request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f89496fa9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices: low-impact feature release]]></title>
            <link>https://milanbrankovic.medium.com/microservices-low-impact-feature-release-d37d7a7d359d?source=rss-bee1178242------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37d7a7d359d</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Milan Brankovic]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 07:33:52 GMT</pubDate>
            <atom:updated>2021-02-23T07:33:52.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lj-304POJRaK4lbi-X3jUw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@stphnwlkr?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Stephen Walker</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Releasing a new feature to production is crucial to successful market-impact. Unlike a monolith application, where you need to optimize deployment for that particular case, microservice deployment practices are different. Here you need to scale to multiple services, where each of them has its own dependencies and where each service can be written in a different language.</p><p>Choosing the right tools and infrastructure will make deployment easier. Reliable microservice releases can be achieved by applying continuous delivery/ continuous deployment principles. A deployment pipeline is the main piece of continuous delivery.</p><p>Sometimes it is crucial to deploy and test new feature to production in order to verify if it is stable, or just to test it prior to making it available to customers. There are two techniques how this can be achieved:</p><ul><li><em>dark launches: </em>this is the practice of deploying a service to production significantly prior to making it available to end users. Doing this allows you to perform exploratory testing, check the behavior of the service, test it against production traffic…</li><li><em>feature flags</em>: whit this approach, you can enable new/experimental features to subset of users. Unlike dark launches, this approach can be used at any point of microservice lifecycle. By controlling which features can be seen by the user, feature flags can assist in minimizing potential breakage(s) in the system. Just by enabling/disabling a feature you can do a rapid recovery.</li></ul><p>Both of these techniques will allow you to deploy a new feature(s) without impacting customers and provide a flexible mechanism to rollback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37d7a7d359d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>