├── LICENSE ├── README.md ├── README_en.md └── imgs ├── img1.png ├── img2.png └── img3.png /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Clean Dart 2 | Proposta de Arquitetura Limpa para o Dart/Flutter 3 | 4 | 5 | # Início 6 | 7 | Podemos dizer que uma arquitetura limpa pode definir o futuro do seu projeto, sabendo disso, devemos tê-la como objeto de estudo constante para que assim saibamos onde, quando e como aplicá-la. 8 | 9 | Para essa proposta nos baseamos nas camadas da Arquitetura Limpa proposta por Robert C. Martin no livro **“Arquitetura Limpa: O Guia do Artesão para Estrutura e Design de Software”**. 10 | 11 | 12 | # Camadas de uma Arquitetura Limpa 13 | 14 | **Robert C. Martin** conclui que uma arquitetura deve conter pelo menos 4 camadas principais e independentes para ser considerada “limpa”, são elas: 15 | 1. Regras de Negócio Corporativas 16 | 2. Regras de Negócio da Aplicação 17 | 3. Adaptadores de Interface 18 | 4. Frameworks & Drivers (Externos) 19 | 20 | ![Image 3](imgs/img3.png) 21 | 22 | 23 | ## Regras de Negócio Corporativas 24 | 25 | São as regras de negócio cruciais para a sua aplicação, são representadas por modelos de dados denominado **"Entidades"**, essa camada tem as regras mais sensíveis de um sistema, por isso ela está no topo das camadas. Uma "Entidade" deve ser pura, ou seja, não deve conhecer nenhuma outra camada, porém é conhecida pelas outras camadas. 26 | 27 | 28 | ## Regras de Negócio da Aplicação 29 | 30 | São as regras que só o computador pode executar, aqui temos uma representação de comandos chamados de **"Casos de Uso"**, e basicamente representam as ações que um usuário pode fazer na aplicação. 31 | 32 | Um **"Caso de Uso"** conhece apenas as Entidades, porém não sabe nada sobre as implementações das camadas de mais baixo nível. 33 | 34 | Se um **"Caso de Uso"** precisar acessar uma camada superior, deverá fazê-lo por meio de contratos definidos por uma interface, seguindo o **“Princípio de Inversão de Dependências”** do [SOLID](https://www.youtube.com/watch?v=mkx0CdWiPRA). 35 | 36 | 37 | ## Adaptadores de Interface 38 | 39 | Essa camada é responsável por “dar suporte” para as camadas mais altas (Regras de Negócios) convertendo os dados externos em um formato que cumpra os contratos de interface definidos pelas Regras de Negócios. 40 | 41 | 42 | ## Frameworks & Drivers 43 | 44 | Todas as abstrações feitas pelas camadas mais altas foram para aumentar a facilidade do plug & play dos artefatos externos como um banco de dados ou uma interface gráfica. 45 | 46 | Essa camada normalmente sofre muitas modificações, porém com uma arquitetura limpa aplicada isso pode ser completamente indolor e segura para a sua regra de negócio. 47 | 48 | Podemos então trocar uma API REST por outra em GraphQL sem afetar suas regras de negócio. Poderemos também trocar a interface gráfica completamente ou até mesmo trocar o Flutter pelo AngularDart e mesmo assim as Regras de Negócio ficarão funcionais! 49 | 50 | Dado as descrições iremos apresentar a proposta de Arquitetura Limpa da Flutterando, a **“Clean Dart”**. 51 | 52 | 53 | # Clean Dart 54 | 55 | ![Image 1](imgs/img1.png) 56 | 57 | Usando o Flutter como exemplo teremos então quatro camadas mantendo a “Arquitetura de Plugin”, com foco principal no Domínio da Aplicação, camada esta que hospeda as 2 Regras de Negócio principais, estamos falando das **Entidades** e dos **Casos de Uso**. 58 | 59 | ![Image 1](imgs/img2.png) 60 | 61 | A proposta de Arquitetura se propõe a desacoplar as camadas mais externas e preservar a Regra de Negócio. 62 | 63 | 64 | ## Presenter 65 | 66 | A Camada **Presenter** fica responsável por declarar as entradas, saídas e interações da aplicação. 67 | 68 | Usando o Flutter como exemplo, hospedaremos os Widgets, Pages e também Alguma Gerência de Estado, já no backend como exemplo, seria nesta camada onde colocaríamos os Handlers ou Commands da nossa API. 69 | 70 | 71 | ## Domain 72 | 73 | A camada de **Domain** hospedará as Regras de Negócio Corporativa(Entity) e da Aplicação(Usecase). 74 | 75 | Nossas Entidades devem ser objetos simples podendo conter regras de validação dos seus dados por meio de funções ou ValueObjects. **A Entidade não deve usar nenhum objeto das outras camadas.** 76 | 77 | Os **Casos de Uso** devem executar a lógica necessária para resolver o problema. Se o **Caso de Uso** precisar de algum acesso externo então esse acesso deve ser feito por meio de contratos de interface que serão implementados em uma camada de mais baixo nível. 78 | 79 | A camada **Domain** deve ser responsável apenas pela execução da lógica de negócio, não deve haver implementações de outros objetos como Repositories ou Services dentro do **Domain**. 80 | 81 | Tomando um Repository como exemplo, teremos que ter apenas o contrato de interfaces(Abstrações) e a responsabilidade de implementação desse objeto deverá ser repassado a outra camada mais baixa. 82 | 83 | 84 | ## Infrastructure (Infra) 85 | 86 | Esta camada dá suporte a camada **Domain** implementando suas interfaces. Para isso, adapta os dados externos para que possa cumprir os contratos do domínio. 87 | 88 | Muito provavelmente nessa camada iremos implementar alguma interface de um Repository ou Services que pode ou não depender de dados externos como uma API ou acesso a algum Hardware como por exemplo Bluetooth. 89 | 90 | Para que o Repository possa processar e adaptar os dados externos devemos criar contratos para esses serviços visando passar a responsabilidade de implementação para a camada mais baixa da nossa arquitetura. 91 | 92 | Como sugestão, iremos criar objetos de **DataSource** quando quisermos acessar um dado externo, uma BaaS como Firebase ou um Cache Local usando SQLite por exemplo. 93 | Outra sugestão seria criar objetos denominados **Drivers** para interfacear a comunicação com algum Hardware do dispositivo. 94 | 95 | Os acessos externos como Datasources e Drivers devem ser implementados por outra camada, ficando apenas os Contratos de Interface nesta camada de Infra. 96 | 97 | 98 | ## External 99 | 100 | Aqui começaremos a implementar os acessos externos e que dependem de um hardware, package ou acesso muito específico. 101 | 102 | Basicamente a camada External deve conter tudo aquilo que terá grandes chances de ser alterado sem que o programador possa intervir diretamente no projeto. 103 | 104 | No Flutter por exemplo, para cache local usamos o SharedPreferences, mas talvez em alguma estágio do projeto a implementação do SharedPreferences não seja mais suficiente para a aplicação e deve ser substituída por outro package como Hive, nesse ponto a única coisa que precisamos fazer é criar uma nova classe, implementando o Contrato esperado pela camada mais alta (que seria a **Infra**) e implementarmos a lógica usando o Hive. 105 | 106 | Um outro exemplo prático seria pensar em um login com Firebase Auth, porém outro produto deseja utilizar um outro provider de autenticação. Bastaria apenas implementar um datasource baseado no outro provider e “Inverter a Dependência” substituindo a implementação do Firebase pela nova quando for necessário. 107 | 108 | Os Datasources devem se preocupar apenas em “descobrir” os dados externos e enviar para a camada de Infra para serem tratados. 109 | 110 | Da mesma forma os objetos **Drivers** devem apenas retornar as informações solicitadas sobre o Hardware do Device e não devem fazer tratamento fora ao que lhe foi solicitado no contrato. 111 | 112 | # Dicas 113 | 114 | ## Pense por camada 115 | 116 | Quando for desenvolver comece a pensar por camada, não devemos nos preocupar com o que tem na camada de **Presenter** ou **External** por exemplo. Se pensarmos nas camadas mais externas podemos acabar nos orientando (erroneamente) por essas camadas. Assim, devemos nos acostumar a desenvolver camada por camada, de dentro para fora e não ao contrário. 117 | 118 | Talvez no começo da sua jornada "Limpa" algumas camadas possam parecer "sem utilidade", isso acontece quando nossa mente ainda não está **Pensando em Camadas** (ou porque sua Regra de Negócio é simples demais para isso) 119 | 120 | ## Teste de Unidade será sua nova UI 121 | 122 | É muito comum os desenvolvedores criarem primeiro as suas Views para que então possam "testar" as Regras de Negócio. Mas nós já temos uma ferramenta própria para isso e um lugar dedicado para armazenar esses testes. 123 | 124 | Desenvolver de forma "limpa" está em total sinergia com o **TDD**(Test Driven Development) pois a camada de **Presenter** será uma das últimas coisas que iremos pensar no desenvolvimento da nossa feature. 125 | 126 | ## Gaste mais tempo tratando erros 127 | 128 | **"É melhor deixar uma Exception acontecer do que tratar um erro de forma genérica"...** 129 | Uma boa dica é usar alguma classe que nos obrigue a tratar os erros como o **Either** do pacote **dartz**. 130 | 131 | Either é uma classe que pode receber dois tipos de dados, um Left (para quando enviar o erro) e o Right(para enviar o dado esperado). Isso também diminui muito a necessidade de realizar um tratamento manual de erro com **try catch** em camadas mais superiores como **Presenter**. 132 | 133 | ## Não caia na tentação de furar uma camada 134 | 135 | Algumas vezes você poderá ter um **UseCase** muito simples, que apenas repassa para o **Repository**, como por exemplo em um CRUD onde você apenas precisa validar se a informação está chegando da maneira correta e repassar para o **Repository** fazer seu trabalho. 136 | 137 | Parece estranho você ter uma classe com um método que faz somente a validação dos dados e repassa para outra classe, porém você verá a grande utilidade disso no momento de uma manutenção. Pois muitas vezes o **UseCase** pode nascer pequeno mas em um futuro próximo ele pode ganhar corpo. 138 | 139 | Um exemplo disso é a utilização do Firebase, o package do Firebase te retornar uma Stream que você pode muito bem colocar ele direto na sua **View**, porém se um dia você quiser remover o firebase do seu projeto, você terá que reconstruir toda sua tela ou pior todo seu projeto. 140 | 141 | Sendo assim não caia na tentação de chamar o **Repository** direto do **Controller** ou mesmo plugar o Firebase direto na sua **View**, além de infringir as regras da arquitetura, você irá se arrepender em um futuro próximo. 142 | 143 | # Assine! 144 | 145 | Apreciamos o seu feedback! 146 | Se concorda com a proposta de Arquitetura Limpa "Clean Dart", deixe uma **Star** neste repositório. Uma **Star** é o mesmo que assinar um "manifesto limpo" concordando com essa proposta. 147 | 148 | Estamos abertos a sugestões e melhorias na documentação! 149 | Faça isso por meio das [issues](https://github.com/Flutterando/Clean-Dart/issues), nossa equipe ficará muito contente com seu interesse em melhorar essa ferramenta para a comunidade. 150 | 151 | Sinta-se a vontade para abrir um **PR** com correções na documentação dessa proposta. 152 | 153 | # Exemplos 154 | 155 | - [Clean Dart Login with Firebase, MobX and Modular](https://github.com/jacobaraujo7/login-firebase-clean-dart) 156 | - [Clean Dart Github Search with BLoC and Modular](https://github.com/Flutterando/clean-dart-search-bloc) 157 | - [Clean Dart Github Search with MobX and Modular](https://github.com/jacobaraujo7/clean-dart-search-mobx) 158 | - [Clean Dart Github Search with Flutter Command](https://github.com/aquilarafa/clean_dart_flutter_command) 159 | - [Clean Dart Github - Path dependency with State Managers approaches](https://github.com/whosramoss/clean-dart-github) 160 | - [Chat WebSocket with Get_It and Cubit](https://github.com/rodrigorahman/flutter_curso_chat_websocket) 161 | - [Movie App With MicroApps, Modular and Flutter_Triple](https://github.com/Bwolfs2/coffsy_movie_app) 162 | - [Clean Dart Pokedex with BLoC and Modular](https://github.com/umpedetiago/pokedex_with_cleandart.git) 163 | 164 | # Links úteis 165 | 166 | - [Resumo do livro "Arquitetura Limpa"](https://medium.com/@deividchari/desvendando-a-arquitetura-limpa-de-uncle-bob-3e60d9aa9cce) 167 | - [Sua Arquitetura está limpa?](https://medium.com/flutterando/sua-arquitetura-est%C3%A1-limpa-clean-architecture-no-flutter-458c68fad120) 168 | - [Os tijolos do Clean Architecture](https://www.youtube.com/watch?v=C8mpy3pwqQc) 169 | - [The Clean Code Blog](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) 170 | - [Guilherme's Proposal](https://github.com/guilherme-v/flutter-clean-arch) 171 | - [Flutter TDD Clean Architecture Course](https://www.youtube.com/watch?v=KjE2IDphA_U&list=PLB6lc7nQ1n4iYGE_khpXRdJkJEp9WOech) 172 | -------------------------------------------------------------------------------- /README_en.md: -------------------------------------------------------------------------------- 1 | # Clean Dart 2 | Clean architecture proposal for Dart/Flutter. 3 | 4 | # Introduction 5 | 6 | We can say that a clean architecture might define the future of your project. Knowing that, it's our role to study constantly in order to know where, when and how to apply it. 7 | 8 | This proposal is based on Robert C. Martin's **“Clean Architecture: A Craftsman's Guide to Software Structure and Design”** principles and it's layers structure approach. 9 | 10 | # Clean Architecture layers 11 | 12 | **Robert C. Martin** states that, to be considered "clean", an architecture must have at least 4 main and independent layers. They are: 13 | 14 | 1. Enterprise Business Rules 15 | 2. Application Business Rules 16 | 3. Interface Adapters 17 | 4. Frameworks & Drivers (External) 18 | 19 | ![Image 3](imgs/img3.png) 20 | 21 | 22 | ## Enterprise Business Rules 23 | 24 | They are the most sensitive rules of a system and, thus, the highest-level layer. They are represented by data models called **entities**. 25 | 26 | An **entity** must be pure. This means that it cannot have any knowledge about the layers below it. On the other hand, all other layers know about the **entities**. 27 | 28 | ## Application Business Rules 29 | 30 | They are the rules that are exclusive and specific to your application and can only be executed by the target device. They are expressed in commands called **use cases**, which, roughly speaking, represents any action the user can perform within your application. 31 | 32 | An **use case** only knows the **entities** layer, and know nothing about the lower layers. 33 | 34 | If an **use case** needs to access a higher layer, it should be done with the [**Dependency Inversion Principle**](https://en.wikipedia.org/wiki/Dependency_inversion_principle) in mind. 35 | 36 | ## Interface Adapters 37 | 38 | This layer is responsible for acting as a bridge between the higher layers and the external data. It helps the external data to communicate with the higher layers in a way that respects the interface contracts defined in the business rules. 39 | 40 | 41 | ## Frameworks & Drivers 42 | 43 | All the higher-level layers abstractions were designed specially top improve the decoupling between them and the external artifacts. This makes easier to switch them whenever you want, in a plug & play fashion. 44 | 45 | The frameworks & drivers layer is highly volatile, and is constantly changing. Within a clean architecture, however, these changes may be completely painless and safe, leaving your business rules untouched. 46 | 47 | We can, then, switch from our Rest API to a GraphQL one, from our UI to another one, or even from Flutter itself to AngularDart. The business rules will keep working as before, as you won't need to change them not even a little. 48 | 49 | That said, let's present our proposal for a Flutterando Clean Architecture, namely, **Clean Dart**. 50 | 51 | 52 | # Clean Dart 53 | 54 | ![Image 1](imgs/img1.png) 55 | 56 | By using Flutter as an example, we have four layers, keeping the "plugin architecture", with the main focus on the Application Domain. In this layer inhabits the two main business rules, the **entities** and the **usecases**. 57 | 58 | ![Image 1](imgs/img2.png) 59 | 60 | This architecture proposes to dissociate the external layers and preserve the business rules. 61 | 62 | ## Presenter 63 | 64 | The **Presenter** layer is responsible to declare the I/O and the interactions of the application. 65 | 66 | If we take Flutter as an example, this layer would contain the Widgets, Pages and the State Management. On the other hand, if we were dealing with the backend, this layer would be where we would have the Handlers or Commands of our API. 67 | 68 | ## Domain 69 | 70 | The **Domain** layer will contain our **core business rules** (entity) and **application-specific business rules** (usecases). 71 | 72 | Our **entities** must be simple objects, that may or not have validation rules for its data through functions or ValueObjects. **The entity must not depend on any object of the other layers.** 73 | 74 | The **usecases** must run the necessary logic to solve a specific problem. If the **usecase** needs the any external access, this access may be done through interface contacts that will be implemented by the lower-level layers. 75 | 76 | The **Domain** must be responsible only for the execution of the business rules. It must not have any other object implementations, like repositories or services. 77 | 78 | Taking a repository as example, we will have only the interface contract to this repository. The implementation of this contract must be done by a lower-level layer. 79 | 80 | ## Infrastructure (Infra) 81 | 82 | This layer supports the **Domain** layer by implementing its interfaces. To do this, it have to adapt the external data so that it fullfill the domain contracts. 83 | 84 | This layer will, probably, have the implementation for some repository or service interface that can't depend on external data, like an API, or the access to some hardware, like a Bluetooth device. 85 | 86 | For the repository to be able to process and adapt the external data we must create contracts for these services, aiming to defer the implementation responsibility to a lower-level layer in our architecture. 87 | 88 | Our suggestion is to create **DataSource** object when we want to access external data, that is, for example, a BaaS like Firebase or a SQLite-based local cache. Another suggestion is to create **Driver** objects to interface the communication between your application and some device hardware. 89 | 90 | The external accesses like data sources and drivers must be implemented by another layer, leaving only the interface contracts in this layer. 91 | 92 | ## External 93 | 94 | Here we implement the external accesses that depends on a hardware, package or highly-specific access. 95 | 96 | Basically, the **External** layer must contain everything that is expected to be highly volatile and constantly changed. 97 | 98 | In Flutter, for instance, we use `shared_preferences` for local cache. However, it may be that, in a later stage of the project, `shared_preferences` won't be able to meet the requirements of our application and we will want to replace it with another package, like `hive`. When this happens, all we need to do is to implement, using the logic inherent to `hive`, a new instance of the contract that the infrastructure layer expects. 99 | 100 | Another pragmatic example would be to think in a login system based on Firebase Auth. Another product, however, want to use other authentication provider. To make this substitution it would be as simple as implementing a data source based on this new provider and "invert the dependency", using this implementation instead of the Firebase one's when need. 101 | 102 | The **data sources** must only worry about discovering the external data and sending it to the infra layer, where they will be dealt. 103 | 104 | Likewise, the **drivers** objects must only provide the device hardware info that is required by the contract, and not deal with anything else. 105 | 106 | # Tips 107 | 108 | ## Think on layers 109 | 110 | When you are about to start developing, start thinking about layers. We shouldn't worry with what the **Presenter** or **External** layers have, for example. If we start thinking by the external layers we may be eventually misguided by them. Thus, we should get used to develop each layer, from the most internal to the most external. 111 | 112 | It may be that, in the beginning of your "clean" journey, some of these layers may seem useless. This happens when our thinking is not yet based **on layers** (or, maybe, because your business rule is too much simple for this). 113 | 114 | ## Unit Testing is your new UI 115 | 116 | It's very common to developers to create your apps views before anything, so they help them to test their business rules. However, we already have a more proper tool for this, and a place specially designed for this kind of test. 117 | 118 | Developing in a "clean" way is completely related with **TDD** (Test-Driven Development), as the **Presenter** layer is going to be one of the latest that we are going to think and develop. 119 | 120 | ## Spent your time dealing with possible errors 121 | 122 | **It's better to let a Exception be thrown than to handle it in a generic way...** 123 | A good tip is to use some handling-enforcing approach, like the `Either` class from `dartz` library. 124 | 125 | The `Either` class may receive two distinct data, a `Left` one, representing an error, and a `Right` one, representing the actual expected result. This reduces a lot the need to manually handle the exceptions with **try-catch**, which is error-prone, in higher layers. 126 | 127 | ## Don't fall in the temptation of bypassing a layer 128 | 129 | Sometimes you may have a very simple **usecase**, that will simply pass the data to the **repository**, like, for example, a CRUD where all you need to do is to validate if the data is being correctly received and yield it to the **repository** to do its work. 130 | 131 | It may seem weird to have a class that have a single method which only function is to validate the data and send it to another class, but you are going to see that this will become quite useful when you are maintaining your project. It's not uncommon that your **usecase** borns small like this, but in the near future it grows bigger and more complex. 132 | 133 | An example of this case is when you are using Firebase. The Firebase package only returns a Stream, and you could, as well, simply put it directly in your **view**. However, if someday you need to remove Firebase from your project and replace it with an alternative, you will have to remake your entire view, or even your entire project. 134 | 135 | That said, don't fall in the temptation of calling the **repository** directly from your **controller**, or to use Firebase directly in your **view**. You will be breaking your architecture laws and will eventually regret of your decision. 136 | 137 | # Sign up! 138 | 139 | We would like to have your feedback! 140 | 141 | If you like your "Clean Dart" architecture proposal, leave a **star** in this repository. This is the same as signing a "clean manifest" agreeing with our proposal! 142 | 143 | We are open to suggestions and improvements on this documentation! 144 | If you want to contribute, open an [issue](https://github.com/Flutterando/Clean-Dart/issues). Our team will be very happy with your interest in improving this tool for the community. Also, feel free to open a **pull request** with fixes to this proposal documentation. 145 | 146 | # Examples 147 | 148 | - [Clean Dart Login with Firebase, MobX and Modular](https://github.com/jacobaraujo7/login-firebase-clean-dart) 149 | - [Clean Dart Github Search with BLoC and Modular](https://github.com/Flutterando/clean-dart-search-bloc) 150 | - [Clean Dart Github Search with MobX and Modular](https://github.com/jacobaraujo7/clean-dart-search-mobx) 151 | - [Clean Dart Github Search with Flutter Command](https://github.com/aquilarafa/clean_dart_flutter_command) 152 | - [Chat WebSocket with Get_It and Cubit](https://github.com/rodrigorahman/flutter_curso_chat_websocket) 153 | - [Clean Dart Pokedex with BLoC and Modular](https://github.com/umpedetiago/pokedex_with_cleandart.git) 154 | 155 | # Useful links 156 | 157 | - [Resumo do livro "Arquitetura Limpa"](https://medium.com/@deividchari/desvendando-a-arquitetura-limpa-de-uncle-bob-3e60d9aa9cce) 158 | - [Sua Arquitetura está limpa?](https://medium.com/flutterando/sua-arquitetura-est%C3%A1-limpa-clean-architecture-no-flutter-458c68fad120) 159 | - [Os tijolos do Clean Architecture](https://www.youtube.com/watch?v=C8mpy3pwqQc) 160 | - [The Clean Code Blog](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) 161 | - [Guilherme's Proposal](https://github.com/guilherme-v/flutter-clean-arch) 162 | -------------------------------------------------------------------------------- /imgs/img1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterando/Clean-Dart/f727395bc76bcaba30d6cba6df0de00fe533e280/imgs/img1.png -------------------------------------------------------------------------------- /imgs/img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterando/Clean-Dart/f727395bc76bcaba30d6cba6df0de00fe533e280/imgs/img2.png -------------------------------------------------------------------------------- /imgs/img3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flutterando/Clean-Dart/f727395bc76bcaba30d6cba6df0de00fe533e280/imgs/img3.png --------------------------------------------------------------------------------