Unexpected bad practiceshttps://cleverlance.de/en/blog/Pages/unexpected-bad-practices.aspxUnexpected bad practices<p>​​Some programming practices are so familiar to us that we use them automatically without much thought. Sometimes these techniques become obsolete; sometimes they are applied in the wrong context. Addressing such poorly experienced habits is often met with revolt. Especially by those who use them and perceive the topic as useful, so let's do exactly that!</p><h3>Marks<br></h3><p>Programming IDEs often recognize specific types of comments to help navigate across the codebase. Xcode’s <em>FIXME</em> lets other developers know that a piece of code deserves more attention. <em>TODO</em> is helpful when something is, well, to be done. <em>MARK</em> differs from the previous cases; it serves a documentation purpose. The same feature in IntelliJ IDEA/Android Studio is called r​egion.<br></p><p>Marks divide the source code into multiple parts using headings. That can make the code appear broken into logical units. If you are a reader familiar with the former Objective-C era of iOS development,​ know that this is just an updated <em>#pragma mark</em> directive.<br></p><p>Typical usage is in files with a large number of lines. <em>Marks</em> create the illusion of clarity by breaking them into pieces that supposedly belong together.<br></p><p>The usage of marks in such cases is a bad practice. Developers often abuse them to justify a file being too big. One should not depend on Xcode to make the code comprehensive and readable. Small and well-decomposed classes are more straightforward to reason about and navigate without IDE features. Especially for pull request reviewers using the web interface where those features are absent.<br></p><h3>Extensions</h3><p>Modern programming languages such as Kotlin or Swift allow you to extend classes, interfaces/protocols, structs, or enums to provide an additional implementation. You can divide your code into multiple pieces using extensions to outline what belongs closer together. Another usage is to make a convenience extension around another type you might not even own to make its use more intuitive. The possibilities are almost limitless. This isn't always a good thing, but first, a peek into history.<br></p><p>Extensions existed way back in Objective-C as well. If you're not blessed with experience with programming in such a language and had to guess the name for extensions, you'd likely be surprised. It's Categories! Another surprise is that Extensions are a thing in Objective-C too, but serve different purposes. What's interesting is the difference between both languages. Categories in Objective-C forced the developer to come up with the name. That's why files named in style <em>Class+CategoryName.swift</em> are often used even for Swift extensions. And more importantly, to use Categories, you had to import them explicitly.<br></p><p>Extensions in Swift are an unnamed piece of code. Such code may be more complicated for the reader to grasp. If multiple extensions of the same type exist, adding a name to the code and wrapping it in a type might help readability immensely.<br></p><p>Improper extension of widely used types causes namespace pollution. It's critical, before creating extensions, to ask whether all instances of the type should have such an ability. Should all UIViews have access to a blinking method? Does one specific subclass of UIView make more sense?<br></p><p>Some developers use extensions to break down the implementation of multiple protocols: which might also be a warning sign. If a class implements many protocols, it may be time to consider splitting it into smaller classes.<br></p><p>For trolls out there: you can make your co-workers mad by extending <em>UIView</em> with <em>translatesAutoresizingMasksIntoConstraints and watch them compare it with translatesAutoresizingMaskIntoConstraints.</em><br></p><p>But don't.</p><h3>Comments<br></h3><p>The ability to write comments might lead undisciplined programmers to create code of poor quality. Unfortunately, it's easier to neglect to name a variable and describe what's going on in my head with a complicated but not-so-clear comment. Easy should not be our goal. Brevity and clarity should.<br></p><p>Great comment for poorly written code is still a code smell. Don't just take my word for it. Robert Martin states: "A comment is a failure to express yourself in code. If you fail, then write a comment; but try not to fail."<br></p><p>Another reason is as the code lives in the repository and is modified and refactored, its behavior might change, and its name can express it everywhere it is called. But its comment is rarely updated and may become more confusing than helpful.<br></p><p>Documentation comments serve their purpose very well when you're designing an API for others to use. Remember that the API needs to stand by itself, and clarity is the priority. Don't use the documentation comments as an excuse for a lousy design.<br></p><h3>Structure</h3><p>The structure of a project is one of the first things you see when you check out a codebase, and it should outline the app's purpose at first sight. However, it is not an exception that some projects have folder structures inspired by the layers of architecture, e.g., View, ViewModel, Model.</p><p>Project ​struc​ture based on architecture layers is a bad practice. It makes reusability effectively impossible. Navigating through such a structure is unnecessarily complicated and becomes harder to maintain as the scope increases. It doesn't scale. Folders inspired by the architecture might have their place, not just at the top level. It should not be the first thing you see.<br></p><p><img src="/de/blog/PublishingImages/Articles/MobileIt/unexpected-bad-practices-01-01.png" data-themekey="#" alt="" style="margin:5px;" /><br></p><p>See for yourself, what structure tells you more about the application?<br></p><h3>Dependencies</h3><p>Open source offers many libraries to simplify life, from UI components through networking to dependency injection solutions. It can often save a great deal of time and effort. On the other hand, this carries various dangers and limitations; using third-party libraries requires discipline, order, and balance.<br></p><p>Randomly scattered third-party dependencies significantly reduce robustness. Shielding the core of the application and using the libraries from the outer parts of the architecture helps mitigate the risk. Abstraction eases the process of replacing one library with another.<br></p><p>It's OK to utilize 3rd party dependencies, but with caution. Ask yourselves: How much time will it save me? How much effort will it take to replace? Can I install enough defense mechanisms to protect the application?<br></p><p>The silver bullet to protect your app, though sometimes tricky or impractical, is to have the import of the dependency in only one place.</p><p>We've had the pleasure of taking over multiple apps that were impossible to maintain anymore due to this problem. Without abstraction, no longer supported (or closed sourced) libraries disintegrated the codebase. External dependencies should never hold your product hostage.<br></p><h3>Tests</h3><p>Test-driven development is a programmer's good manners, a discipline overflowing with benefits. Technical impacts are a blog post by itself, if not a series. Non-technical impacts such as easy onboarding of new team members and executable documentation that cannot become obsolete speak for themselves.<br></p><p>Yet they are often neglected. A complete absence of tests is the apparent first and most common violation, followed by writing tests after the production code, which mitigates all the benefits and introduces other obstacles.<br></p><p>You must write unit tests first - before production code. Testing first will prevent you from creating code that's too complex. It will guide you through building components of the right size. The big classes are challenging to test, and the tests will direct you to decompose them into smaller ones.<br></p><p>Tests written after production code are inherently lower quality and can even be misleading. Unless you write the production code as proof of the first failing test, it is impossible to say whether the tests assert what they declare. It is then questionable how well such tests protect the system under test.<br></p><p>If you write tests after implementation, you may find a component challenging to test, which is impossible with a test-first approach. You can't create untestable code!<br></p><h3>The devil's in the detail</h3><p>Even the mundane can be harmful if we do something too automatically and with less attention. Challenge the ordinary and seek bad practices that you wouldn't expect.​​<br></p>
Apple thinks about the security of its usershttps://cleverlance.de/en/blog/Pages/apple-account-deletion.aspxApple thinks about the security of its users<p>​​​Mobile apps are becoming increasingly popular among users. Thousands of them are downloaded every day from <strong>Google Play</strong> and the<strong> Apple App Store</strong>. However, not all apps are completely secure for their users and not all manage the personal data of their users correctly. The above-mentioned companies try to make sure that only apps which “play fair” with users get into their stores.<br></p><p>In order to protect the privacy of iOS app users, Apple has issued a <a href="https://developer.apple.com/support/offering-account-deletion-in-your-app" target="_blank">regulationstating</a> that: “Starting June 30, 2022, apps submitted to the App Store that support account creation must also let users initiate deletion of their account within the app.”</p><p>Originally, this guideline was supposed to apply from the end of January 2022, but the deadline was postponed by 5 months due to pressure from developers and app companies. This is due to the fact that updating apps is not always a simple procedure. Apple has clear rules for deletion of an account: </p><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px;"><p>• The process of deleting the account must be clear, intuitive and transparent, easy to find in the application (e.g. a button to take you to the user profile or account management).</p><p>• We must offer complete deletion of the entire account record, including associated personal data. Merely offering to deactivate (temporarily disable) the account is not enough. </p><p>• If users have visit the website to complete deletion of their account, we should add a direct link to the page on the website where they can complete the process. </p><p>• Users must be well informed. If the deletion request is going to take longer to complete, we need to let users know. </p><p>• If the app supports in-app purchases, we need to clearly explain to people how subsequent billing and account cancellation will take place. </p><p>• All apps must include an easily accessible link to the privacy policy in the description on App Store Connect within the app. </p><p>• Last but not least, it is necessary to comply with the applicable legal requirements for the processing and storage of the client’s personal data. And also its deletion. This includes compliance with local laws - in our case, the applicable GDPR directive.</p></blockquote><p><a href="/en/" target="_blank">Cleverlance</a> in its capacity as a technology company, helps its customers address these requirements. As a supplier of mobile applications, we have successfully resolved this issue, for example in the mobile application for <a href="https://apps.apple.com/cz/app/my%C5%A1koda/id1161648654?l=cs" target="_blank">MyŠkoda</a> ŠKODA AUTO a.s. Exactly according to the GDPR directive, here customers can completely delete their account in their profile, including their personal data. However, they must first disco​nnect their cars, which they control via the app. </p><p>In banking, the situation is slightly different. Although users can delete their accounts and access to the mobile app, their products remain untouched in the bank. Just like their personal data which must remain in the systems because of the legitimate interest of processing personal data and fulfilling a legal obligation. Users can cancel their account in the app and in doing so stop using the app. But they remain full-fledged customers of the bank.</p><h3>What does Google say?</h3><p>And how does another giant, Google, feel about this? The rules for displaying apps in Google Play state that the app must be transparent and inform the user how it processes their personal data. They prohibit outright fraudulent or dishonest conduct. However, Google has not yet taken the step of dictating that every app, if it creates a user account, must also allow the deletion of that account. </p><p>This move by Apple will certainly improve the transparency and fairness of apps as regards their users. It is a good step in the right direction towards a more honest electronic world. </p><h3>Recommendations for developers </h3><p>For the implementation of the new account deletion functionality, I recommend scheduling a separate release after the specified date. This is to say that Apple is likely to be rigorously testing the functionality and this may lead to a delay in release of the new version. This could have a detrimental effect on other important new functionality of the app if released alongside this release. And users don’t like to wait.​<br></p>
Development of multi-platform mobile and web appshttps://cleverlance.de/en/blog/Pages/Multiplatform.aspxDevelopment of multi-platform mobile and web apps<p>​​​Do you want your own mobile app? Nowadays it’s a given that one needs to do one for Android as well as for iOS; one is not enough. And more often than not, one also wants a web interface. However, essentially right from the introduction of mobile devices to the market, we’ve heard it said again and again that developing things separately for individual platforms is expensive. That is why various companies tried to introduce alternatives in the form of multi-platform solutions, however none of these really managed to become widely adopted. They had their shortcomings, were unnecessarily complex and held companies which wanted to develop their mobile apps flexibly in a kind of “cage” with limited possibilities. That is why for B2C apps it is often preferred to develop natively; there are no limitations as far as UX, animations and other details are concerned, and these things can be very important for the target group.<br></p><p>However, in the past years we see corporate mobile apps for which a perfect user interface and design is no longer a priority; emphasis is placed on functionality, utility, expedited delivery and flexible adjustments. And that’s where we can make use of selected technologies that can be used in a multi-platform setting. Of course, assuming we adhere to certain rules.​<br></p><p>At Cleverlance, we found success with three approaches to implementation. To put it in really simple terms, right from the very beginning we need to decide whether there’s a robust back-end with a MOA (<a href="https://en.wikipedia.org/wiki/Microservices">Microservice Oriented Architecture</a>) is available or whether we’d need to create one, and then whether the app will need a lot of business logic or rather will be just a presentation layer. In this case, it is good to use <a href="https://flutter.dev/">Flutter</a>. If we need the app to include synchronization queues, business logic and we’re implementing some kind of complexity and not just forms, we had good experiences with <a href="https://kotlinlang.org/docs/multiplatform.html">Kotlin Multiplatform</a>. And then there’s a third option = PWA (<a href="https://en.wikipedia.org/wiki/Progressive_web_application">Progressive Web Applications​</a>), which makes use of the strong foundation provided by modern browsers.<br></p><h2>Flutter​<br></h2><p>We consider Flutter to really be a multi-channel display layer which allows us to create not just mobile but also web and desktop apps. It’s a flexible solution that allows us to efficiently design B2B, and under certain conditions even B2C apps. One example here is the mobile app for BMW. But if we don’t want to deal with problems, it’s better to rely on the back-end and push all the “thinking” there.​<br></p><h2>Kotlin Multiplatform</h2><p>Kotlin Multiplatform is another option. Its advantage is that it allows you program a native app for Android, and then use a part of it for iOS. This usually applies to business logics and the integration layer, which leads to significant time savings in the QA phase later. The visualization layer is programmed natively for iOS and Android, meaning that one can have the “look & feel” of the platform while making use of just one code base for the part of the application that is not visible for users. For some projects, this allows up to 70-80% of the code to be reused.<br></p><h2>PWA</h2><p>​Progressive Web Applications is one of the latest trends in the area of web application development. To a certain extent, these shatter the boundaries between web and native mobile apps thanks to the ability to work offline, access a device’s hardware and even handle push notifications. They represent a combination of the best of both worlds; we are only limited by the capabilities of web browsers. This opens up a wide range of functionalities; for instance, the use of a phone’s camera or fingerprint reader are among the most basic ones. A request for using deeper device functions can be efficiently handled via a native “envelope” that can make them available. PWA apps can be distributed via all major app stores (Google Play, Apple Store, Huawei AppGallery as well as Microsoft Store) and can run on all Android, iOS and Windows devices.<br></p><h2>Where was this used?</h2><p>As a supplier, we of course want to offer not just standard technologies but also the “new” ones, and that was another reason we were happy to see customers approach us who right from the very beginning wanted a solution based on Kotlin Multiplatform. As an example, we can mention the U.S. based Globstar for which we, as part of the Aricoma Group, deliver mobile apps used to configure and manage modems for satellite internet connections. The use of Kotlin Multiplatform really paid off in this case, because the app was highly demanding as far as data transmission and integration were concerned. Integration additionally takes place via a BLE (Bluetooth Low Energy) interface, which can service dozens of devices simultaneously to, e.g., update their firmware. The technology was not only convincing for the customer, but also for us as the supplier; when developing the app we established a well-working business partnership.<br></p><p>We made successful use of PWA technology for instance in the online self-service app for SAZKAmobile customers. Its main advantage is an extremely short Time-To-Market (i.e., the time required to introduce new functions to the market) and a wide range of developers who already know the technology. In addition, PWA is best applied in areas without a large emphasis on using the device’s components, for instance in internal company apps for employees in the field or in production.​<br></p><div><p>If you’re interested in the technical details, feel free to read <a href="https://www.mobileit.cz/Blog/Pages/kotlin-multiplatform-first-year.aspx">this article</a> on our mobile it blog; it’ll <a href="https://www.mobileit.cz/Blog/Pages/choosing-mobile-app-technology.aspx">tell you ​</a>what to pay attention to when choosing the right technology for developing a mobile app.<br></p></div>
Development rules for better productivityhttps://cleverlance.de/en/blog/Pages/development_rules_for_better_productivity.aspxDevelopment rules for better productivity<p>​Each project has its own rules for development. Most often, these rules describe development practices and work with a version control system (VCS) that outlines how to test and deploy the product, the structure, the architecture of the project, and the code style, but the rules can also include the basics of secure development and more.<br></p><p>These rules can be unwritten but are usually defined and recorded in a shared space where everyone has access to them. Yet more important is how these rules are applied and enforced in practice.<br></p><h3>Wise men know it best</h3><p>Some people believe that pair programming or code review is an appropriate platform for rules revision. Participants can agree on the application of the rules or change them based on context. When developers approach this conscientiously, the result can be a project that may not be consistent, but its individual parts will be in the best possible shape.<br></p><p>This approach may lead to better results for a short period of time at the start of a project, but its shortcomings will start to become apparent over time. Even experienced developers and technical leads are just people. They can occasionally get tired or simply overlook something. Thus, minor deviations from the agreed-upon rules pile up and begin to form so-called technical debt.<br></p><h3>Time trial</h3><p>The next aspect that reflects in time is the expansion of the project, and this is on two levels.<br></p><p>The first is the expansion of the product itself. As the product becomes successful, it receives new and more sophisticated features that begin to connect previously simpler and independent features. This is where the small deviations and inconsistencies that at first seemed good for the functionality start to show up. The problem is that now more of these functions need to be compatible with each other, but they are not ready for it.<br></p><p>This is not just a problem of incompatibility of features. Often, well-intentioned developers try to reuse existing components as much as possible to avoid code duplication. They forget the rule that we can reuse a component when we expect the same behavior but also have the same reasons to change. If this condition is not met, the Single Responsibility Principle is violated and the project has low flexibility for future development.<br></p><p>The second level of project expansion is the development team itself. Once the product becomes successful, sooner or later it leads to the expansion of the development team. The new team members do not know the whole genesis of the project and thus do not have the same understanding of the rules as the older members who set the rules themselves. This leads to misunderstandings and yet another minor deviation from the agreed rules, which again increases the technical debt. A side effect is an increased need for communication during pair programming and code review, which reduces the overall productivity of the team.<br></p><p>These problems in project expansion are not limited to large development teams, but also happen to smaller ones. For example, when a two-person team introduces two new developers, the productivity of the team may hardly change. And all this is due to the circumstances described above. Without knowing the cause of the problem, it can lead to further blind "strengthening" of the team and make it even worse.<br></p><h3>Tripping comes before a fall</h3><p>When a development team repeatedly fails to finish agreed features or is unable to release a new version of a product for technical reasons, one of the critical scenarios occurs. At this point, people outside the standard development team get involved in discovering the cause and solving the problem. Together, they all work under stress and with a lot of human effort to get the development back under control. It is only at this point that a retrospective analysis takes place to uncover the true causes of the problems.<br></p><p>Yet the accompanying symptoms and spring of these problems have been manifesting themselves for a long time in advance. A few subtle situations as examples:</p><ul><li>A developer repeatedly receives feedback on misnaming during code review.<br></li><li>A ticket in the project issue tracker does not contain a reference to the implementation due to a typo in the project source code.<br></li><li>A feature that is still under development is enabled in the test version of the application.<br></li></ul><p>Often they just look like minor ambiguities, individual mistakes, or accidents that sometimes happen during development. When these situations recur, their negative impact on team productivity and the project's error rate quickly increases. But if we look closely at them, we can see blank spaces in the way we work that are actually easy to fill and solve the problem once and for all.<br></p><h3>Live rules</h3><p>To avoid the problems mentioned above, we need to have clearly specified development rules. Their content should reflect the individual needs of each project. For some projects, it will be critical to clearly define collaboration with the QA team and describe the release management of the product, while other teams will focus more on collaboration between developers within the development itself.<br></p><p>The more detailed and specific the rules are, the better their effect on the team's work will be. Therefore, it is not possible to start from a general template, but each team must define these rules themselves.<br></p><p>Sometimes we see cases where a team defines a few basic rules of a more general nature at the start of a project but does not develop them over time. Thus, the rules never accurately represent how the team works, and even the little they contain becomes meaningless over time.<br></p><p>Nothing is set in stone, and even an established team changes the tools it uses or discovers new ways of working over time. All these natural changes have an impact on the team rules. They remain alive and valid.<br></p><h3>Automate everything</h3><p>In the introduction, we briefly discussed the form the rules can take and the possible ways of applying them. To be most effective, rules must be applied automatically without the need for manual control. Likewise, we must think about the productivity of the team, which can be reduced by the influence of a large number of repressive rules. Therefore, tools that help team members automate certain steps are an integral part of this process. These tools save time and their output is naturally in line with the defined rules.<br></p><p>In practice, it is so common that Code Style or Project Architecture is enforced by automated rules, but at the same time, there are code templates and formatting tools that do most of the work for the developers without them being aware of it.<br></p><p>Most issue tracking tools provide a programmatic interface so that it is easy to automate the creation of a new development branch in VCS so that the new code is linked to a specific issue. Similarly, it is possible to create a VCS hook that checks that a corresponding issue exists for a given branch or commit for cases when the developer has created the new development branch manually.<br></p><p>Release management is a completely separate chapter. When releasing a new version of a product, there are generally routine and clearly defined steps that need to be performed. Here, automation not only gives us the assurance that the release of a new version will be done in an orderly and error-free manner but it also speeds up the process and allows for easy knowledge sharing between team members. A bonus is an easy automation of generating release notes, even if only for internal testers.<br></p><p>Testers will also appreciate the ability to configure the product for internal testing. They can toggle a feature flag, configure the environment the application runs against, or have the ability to simulate scenarios that are difficult to do manually. Besides the undeniable benefit of these test tools for testers, it has benefits for the developers themselves. They don't have to maintain more versions of the product than strictly necessary, which saves them time by fundamentally simplifying the build logic.<br></p><p>This is just a small sample of the rules we commonly encounter on projects. However, it is far from exhaustive of the options, whether they are related to quantity, depth, or sophistication.<br></p><h3>How far to go?</h3><p>Some rules may seem strict enough to restrict your freedom to work. Others may seem so vague that they will not have the desired effect. That's all right. Every team and every member has different needs and different perceptions of risk. All of this has a bearing on the form of the rules.<br></p><p>In our projects, we try to define the rules strictly by default. Over time, when we find that they limit us too much, it's easy to make the rule more generalized or turn it into a recommendation or warning. The opposite approach is considerably more complicated, because the team and its operation have already become accustomed to the more general rule, so it may not be possible to make a change overnight.<br></p><h3>Project sustainability</h3><p>When developing a product, in addition to the short-term goals of making the necessary features, we always consider the idea of long-term sustainability and viability of the project. Especially in mobile development, it is not an exception to the opinion that a project should be discarded once every 2-3 years and developed completely from scratch. This is a real disaster in terms of productivity.<br></p><p>In our portfolio, we have apps that are more than 7 years old and have gone through several major changes during their lifetime. On a business level, there has been a change in targeting a different sector of users and aligned with changes in branding and design. On a technical level I would mention the switch from Java programming language to Kotlin, or the transition of asynchronous work from a custom imperative solution to a reactive approach via RxJava and later Kotlin Coroutines. Even so, the development team is still only two people (while they are altering throughout) and at the same pace, it delivers new functionalities according to the business needs.<br></p><p>Clearly defined development rules and the consistency enforced by them have a major impact on the quality of the final product in every way.​<br></p><div><p>Next time we will take a closer look at how some rules can be implemented and what tools we have for this.<br></p></div>
SwiftUI and Architecture: Statehttps://cleverlance.de/en/blog/Pages/swift-ui-and-architecture-state.aspxSwiftUI and Architecture: State<p>​​​​​A new era has come to the mobile world. At least in the context of UI frameworks. What does this mean for your project? Will your architecture stand strong and allow for incremental adoption? Or will you have to resort to complete rewrite?<br></p><h2>​​Welcome to the new old world</h2><p>The cornerstone of user interface development for iOS since its inception has been UIKit (or AppKit for macOS). It provides a mechanism to define window and view hierarchy, navigate between scenes, render content on the screen, and has tools for handling user interaction. UIKit was designed over a decade ago in the Objective-C world and leverages principles that were common back then, like delegates and inheritance. Functional elements of modern languages like Swift naturally lead to a declarative programming paradigm which is where SwiftUI steps in.</p><p>The SwiftUI framework was announced at WWDC 2019 and introduces the aforementioned declarative approach to writing UI code, favors composition, uses value types extensively and provides under the hood optimization. It completely changes how we reason about the UI and how we write the UI code. Its principles and design are inspired by React from the Javascript world, which dates back to 2013, so our thanks and a round of applause are in order for the JS community for working out its kinks!</p><p>Code written in SwiftUI is multiplatform and can be deployed to tvOS, macOS, and watchOS platforms. Interoperability with UIKit and AppKit helps with the transition even further.</p><p>Interestingly, a very similar approach also came to the Android world, known as Jetpack Compose. If you are more interested in this, it is well described in posts "Jetpack Compose: What you need to know", <a href="https://www.mobileit.cz/Blog/Pages/compose-1.aspx">part 1​</a> and <a href="https://www.mobileit.cz/Blog/Pages/compose-2.aspx">part 2</a>, although since then some things inevitably changed. </p><p>Both of these technologies are ready for production use. Let's focus on what the arrival of SwiftUI means from the architectural point of view, especially regarding state.</p><h2>SwiftUI and state</h2><p>In SwiftUI, a view is a function of a state, not of a sequence of events changing some internal, encapsulated state. What does that mean in practice?</p><p>SwiftUI observes UI state and triggers re-rendering of the view on every change (with some smart optimizations happening under the hood). This is done by property wrappers that annotate UI state objects and/or Combine publishers. It's only up to you to model, hold, transform, compose and distribute the state.</p><p>The state can be perceived from many different angles, for example:</p><ul><li>what is rendered on the screen,</li><li>data that are persisted in the storage,</li><li>state that's spread across multiple screens or features.</li></ul><p>It is crucial to properly separate these kinds of states from each other, as some have a limited role in a merely encapsulated context, while others may span across multiple contexts and may serve the purpose of the source of truth.</p><p>Such a source of truth must be unambiguously defined and shared. Let's take a look at how the currently most discussed architectures approach this.</p><h3> MVx architectures</h3><p>MVC was most commonly used in iOS applications back in the day. It got sidetracked with the advent of functional reactive programming and was replaced with MVVM and its derivative MVVM-C which specifies an additional layer for navigation. The place for View and Presentation logic is clear in those cases, but the Model layer has too many responsibilities, which might lead to big components that have too many concerns. In another case, the Model layer may contain only domain objects whereas the Presentation layer deals with networking, storage, business logic, and transformation of domain objects into renderable objects for the view on one side together with handling actions from the view on the other side. Huge ViewControllers with many responsibilities led to the joke saying MVC is short for Massive-View-Controller.</p><p>MVx architectures are not sufficient by their definition to design the whole system. They are merely a pattern for the presentation part of the system. Clean and robust applications may be written with MVVM as the only architecture tool in your toolbox but it requires strict discipline and proper decomposition. The architecture used often branches out into something more sophisticated than 3-layer architecture but with no clear boundaries that are defined somewhere between the lines.</p><h3> Redux</h3><p>As the SwiftUI is inspired by React from the Javascript world, where React and Redux often go hand in hand, it's natural to think about how this is mirrored in mobile application development.</p><p>Redux is a mechanism to update and distribute state around. It cannot be considered as "architecture" as it does not answer the important questions</p><ul><li>how to protect the app from the outside world?</li><li>how to enable easy change of technologies and third-party dependencies?</li><li>how to define strict boundaries to isolate features?</li><li>where are the business rules defined?</li><li>which parts deal with navigation, presentation, networking, storage, user input, and so on?</li></ul><p>These discussed architectures do not address modeling and state sharing in complete detail, they are often either used in a poor way that is not very readable and sustainable, or in a way that inherently leads to a more complex architecture with a looser definition of responsibilities.</p><p>Although SwiftUI is a new player on the mobile playground, managing state is definitely not. Let's see if the old and traditional principles still have anything to offer in this new world.</p><h2>Lessons learned from history</h2><p>There are many patterns and principles that are timeless, namely two that enable to store and distribute state in a transparent way.</p><h3> Repository pattern</h3><p>A repository is a design pattern that abstracts data access logic from business access logic by exposing the collection-like interface to access business entities. The actual implementation of the interface might communicate with the database, REST API, and what your project requires as long as it doesn't leak its details to the business domain interface.</p><p>Such a repository could easily be the source of the truth for each feature. Repositories obviously hold the state, but let's see how to distribute the same state to multiple parts of the application.</p><h3> Dependency Injection</h3><p>Sharing state across features is as simple as sharing the same repository instance. Dependency injection frameworks help organize the dependency graph. Some use Service Locator patterns that abstracts instance resolution behind an abstraction layer. It reduces boilerplate code you would otherwise need with manual dependency injection. The resolution might cause runtime crashes if some requested instances are not registered. That's a downside that can you can handle with unit tests though.</p><p>You can also implement a shared repository using pure language without any dependency frameworks. The principle remains the same in both cases.</p><h2>Architecture and state</h2><p>It's important to design your system</p><ul><li>to be soft and malleable, so you're able to swiftly deliver changes that are desired,</li><li>but robust enough, so that you can be sure those changes are not going to cause unexpected behavior, </li><li>and clear enough so it's easy to navigate and doesn't grow over your head.</li></ul><p>Decoupling is critical to achieving that. To decouple views, view models, scenes, and what have you, you need to figure out how to share the source of truth across the app. If you mishandle it or don't think much about the state, you're going to have a hard time even with UIKit applications as it leads to coupling that results in code that's hard to test, read and reason about, for instance:</p><p>​<img src="/de/blog/PublishingImages/Articles/MobileIt/swift-ui-and-state-02.png" data-themekey="#" alt="" />ViewModels in this case do way too much. They pass state among each other which makes them difficult to test and harder to read. The source of truth for these data is also lost, it's unclear where the state originated and who owns it.<br></p><p>State management is not something new that came with SwiftUI, it's been here for decades, and there are no specific new architecture requirements. If you make features independent, inject your dependencies, test, and define the source of truth with a repository pattern, you can design your system to be easier to maintain and grow, regardless of which UI framework you pick.</p> <p><img src="/de/blog/PublishingImages/Articles/MobileIt/swift-ui-and-state-01.png" data-themekey="#" alt="" style="margin:5px;" />There's a strict boundary between features in this example. ViewModels only transform data and actions between Views and UseCases. There is one clear source of truth for each feature. Isolation leads to reusability and testability.</p><p>State management was always important in app development, unfortunately often it was neglected or done poorly. Declarative UI concepts do not bring anything new to the table as they just explicitly accent what's important to handle well because the view is a function of a state.</p><h2>Old and new, together</h2><p>Breakthrough technologies such as SwiftUI don't come out that often, but that doesn't mean that your app and architecture should succumb to being completely dependent on the technology and/or derive itself from it. On the contrary, if you adhere to the separation of concerns and decouple your code, you achieve strictly defined boundaries and can start adopting those technologies without having to rewrite most of your app and even do so incrementally.</p><p>SwiftUI is a brand new technology, but that doesn't mean we can't benefit from timeless and classic principles that helped deal with many challenges over many decades. Old and new can go hand in hand together and complement each other to enable us to create brilliant apps.<span style="color:#696158;font-size:14px;">​</span><span style="color:#696158;font-size:14px;">​</span></p><br>