<?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 Dhia Chemingui on Medium]]></title>
        <description><![CDATA[Stories by Dhia Chemingui on Medium]]></description>
        <link>https://medium.com/@dhia.cheminguid?source=rss-b2d32d098bb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WQBKmZP4WWSPLhkv</url>
            <title>Stories by Dhia Chemingui on Medium</title>
            <link>https://medium.com/@dhia.cheminguid?source=rss-b2d32d098bb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:50:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhia.cheminguid/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[Open Closed Principle and Clean architecture]]></title>
            <link>https://medium.com/@dhia.cheminguid/open-closed-principle-and-clean-architecture-1d72de9859a6?source=rss-b2d32d098bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d72de9859a6</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[open-closed]]></category>
            <dc:creator><![CDATA[Dhia Chemingui]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 19:27:24 GMT</pubDate>
            <atom:updated>2023-06-14T19:27:24.333Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Designing code to be extendable without modifying the artifact is the most fundamental reason we study software architecture.</strong></blockquote><p><em>Closed for modification</em>, in simple terms, means that when we add new functionality, we should not touch the existing files in the codebase. Of course, not touching them at all is impossible, but we should minimize the changes in the current codebase</p><p>To embrace extensibility, it is crucial to design classes that inherit from established interfaces for incorporating fresh functionalities. By developing new concrete implementations, we can introduce the desired behaviors without altering existing classes. This approach effectively mitigates the potential risks associated with altering past behaviors.</p><p>lets assume that we have to repositories and when we are offline will use the local data base else will use the server . but we need to inject the same one its impossible hhh … not with open close .</p><p>for example</p><pre>interface BookRepositorty {<br><br>   fun create(book: Book)<br>   fun update()<br>   fun delete(Int id)<br>   fun getBookDetailsByID(Int id): BookDetails<br>}</pre><p>we can implement tow extensions now one for local and other for server</p><p>Server :</p><pre>class ServerBookRepositoryImpl(private val client: ServerClient): BookRepositorty{<br>    <br>    @overide<br>    fun create(book: Book) {<br>      client.create(book)<br>    }<br>    @overide<br>    fun update() .....<br>    <br>    @overide<br>    fun delete(Int id) = client.delete(id)<br><br>    @overide<br>    fun fun getBookDetailsByID(Int id): BookDetails {<br>          return client.getBookDetails(id).toBookDetails<br>    }<br>}</pre><p>Local</p><pre>class LocalBookRepositoryImpl(private val localClient: DatabaseCleint): BookRepositorty{<br>    <br>    @overide<br>    fun create(book: Book) {<br>      localClient.create(book)<br>    }<br>    @overide<br>    fun update() .....<br>    <br>    @overide<br>    fun delete(Int id) = localClient.delete(id)<br><br>    @overide<br>    fun fun getBookDetailsByID(Int id): BookDetails {<br>          return localClient.getBookDetails(id).toBookDetails<br>    }<br>}</pre><p>we have tow <strong>different behaviour</strong> but we use the same Repo in our view model we can do this with dependency injection but i will cover that using in other chapter .</p><p>example</p><pre>class BookScreenViewModel(): ViewModel {<br>      lazy bookRepository: BookRepositorty<br>      init {<br>          if(isOnline){<br>              bookRepository = ServerBookRepositoryImpl(<br>                                      localClient = ServerClient())<br>          }else {<br>                bookRepository = LocalBookRepositoryImpl(<br>                                      localClient = DataBaseClient())<br>          }<br>         <br>      }<br>      ......<br>    //State Management<br><br>}</pre><p>other Example useCase with Strategy Pattern</p><p>many apps have different membership to authenticate (<strong>different behaviour in the same action</strong>)</p><pre>// Strategy interface for authentication<br>interface AuthenticationStrategy {<br>    fun authenticate(username: String, password: String): Boolean<br>}<br><br>// Concrete authentication strategy implementations<br>class DefaultAuthenticationStrategy : AuthenticationStrategy {<br>    override fun authenticate(username: String, password: String): Boolean {<br>        // Default authentication logic<br>        return username == &quot;admin&quot; &amp;&amp; password == &quot;password&quot;<br>    }<br>}<br><br>class MultiFactorAuthenticationStrategy : AuthenticationStrategy {<br>    override fun authenticate(username: String, password: String): Boolean {<br>        // Multi-factor authentication logic<br>        val isUsernameValid = username == &quot;admin&quot;<br>        val isPasswordValid = password == &quot;password&quot;<br>        val isOTPValid = validateOTP()<br><br>        return isUsernameValid &amp;&amp; isPasswordValid &amp;&amp; isOTPValid<br>    }<br><br>    private fun validateOTP(): Boolean {<br>        // Perform OTP validation logic<br>        return true<br>    }<br>}<br><br>// User class<br>data class User(val username: String, val password: String, val authenticationStrategy: AuthenticationStrategy)<br><br>// Usage example<br>fun main() {<br>    val user1 = User(&quot;admin&quot;, &quot;password&quot;, DefaultAuthenticationStrategy())<br>    val user2 = User(&quot;admin&quot;, &quot;password&quot;, MultiFactorAuthenticationStrategy())<br><br>    val users = listOf(user1, user2)<br><br>    for (user in users) {<br>        val isAuthenticated = user.authenticationStrategy.authenticate(user.username, user.password)<br>        val authenticationMethod = if (user.authenticationStrategy is DefaultAuthenticationStrategy) {<br>            &quot;Default Authentication&quot;<br>        } else {<br>            &quot;Multi-Factor Authentication&quot;<br>        }<br>        println(&quot;${user.username} - Authentication Method: $authenticationMethod, Authenticated: $isAuthenticated&quot;)<br>    }<br>}</pre><p>the Strategy pattern is a valuable technique for achieving compliance with the Open-Closed Principle. It provides a way to encapsulate behaviors in separate classes and allows for easy extension without modifying existing code. By utilizing the Strategy pattern, we can design systems that are more maintainable, flexible, and extensible.</p><p>Clean Architecture provides a blueprint for structuring the codebase in a way that supports the Open-Closed Principle. By clearly defining boundaries between layers and modules, and by using well-defined interfaces and abstractions, we can introduce new features or change implementation details without impacting the core components of the system (like the first example). This makes it easier to maintain and extend the software over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d72de9859a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relation between Single Responsibility Pattern (SRP) and Clean Architecture]]></title>
            <link>https://medium.com/@dhia.cheminguid/relation-between-single-responsibility-pattern-srp-and-clean-architecture-ea2297f75b10?source=rss-b2d32d098bb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea2297f75b10</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[rp]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dhia Chemingui]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 19:25:06 GMT</pubDate>
            <atom:updated>2023-06-12T19:25:06.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*opkjo09tI7k5WhSEUZapgw.png" /></figure><h3>1) Pros and Cons</h3><p>By following the Single Responsibility Principle, developers can create software that is more modular, flexible, and maintainable, which can make it easier to develop and evolve over time. This can be especially important in large, complex systems, where it is important to keep the code as simple and focused as possible.</p><p><strong>One potential disadvantage !!!!</strong></p><p>SRP is that it can result in a large number of small classes or modules, which may make the codebase more difficult to navigate and understand. This can be especially true in large, complex systems where there may be many different components with narrowly-defined responsibilities.</p><p><strong>Here are a few examples from the Clean Code Book:</strong></p><ul><li><strong>“The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change.” (p. 23)</strong></li><li><strong>“The Single Responsibility Principle is about the reasons for change. A class or module should have one reason to change. It should have only one job.” (p. 24)</strong></li><li><strong>“A class or module should have only one reason to change, but that doesn’t mean it should have only one method or only one line of code.” (p. 24)</strong></li><li><strong>“The Single Responsibility Principle is about change. It is about the fact that change is inevitable. And it is about the fact that as change occurs, it is much easier to deal with when it affects only one class or module.” (p. 25)</strong></li></ul><p>One of the core principles of clean architecture is the Single Responsibility Principle. By organizing the code into distinct layers, with each layer having a specific responsibility, clean architecture helps to apply the Single Responsibility Principle by ensuring that each layer has a single, well-defined responsibility and that the dependencies between the layers are minimized. This can help to make the code easier to understand and maintain, and it can also make it easier to extend and modify the app as the requirements change.</p><h3>Layers</h3><p><strong><em>Domain Layer :</em></strong><em> </em>This is the innermost layer of the system and it contains the business logic of the app. It is responsible for defining the core concepts and rules of the app, and it should be independent of any specific implementation details.</p><p><strong><em>Data Layer :</em> </strong>This layer is responsible for managing data and interacting with external data sources such as databases or APIs. It should provide a consistent interface for the domain layer to access data, and it should be independent of the specific implementation of the data source.</p><p><strong><em>Presentation Layer :</em></strong><em> </em>Presentation layer: This layer is responsible for the user interface of the app and handling user input. It should be independent of the business logic and data management, and it should only be concerned with displaying the app’s user interface and handling user input.</p><p>Example in the architecture (Using Kotlin):</p><p>For example, in a typical clean architecture-based Android app, the presentation layer (such as the UI) is responsible for displaying the app’s user interface and handling user input, the domain layer is responsible for the business logic of the app, and the data layer is responsible for managing data and interacting with external data sources.</p><pre>class MainActivity. : AppCompatActivity() {<br>  private val viewModel = QuestionsViewModel()<br><br>override fun onCreate(savedInstanceState: Bumdle?) {<br>    super.oncreate(savedInstanceState)<br><br>     setContent {<br>        MaterialTheme {<br>           Column {<br>               Text(&quot;Why did the software engineer follow the SRP ? &quot;)<br>               Button(onClick = { viewModel.answerTheQuestion }){<br>                    Text(&quot;Answer The  Question ? &quot;)<br>               }<br>              }<br>            }<br>           }<br>        }<br>}</pre><pre>class QuestionsViewModel {<br>    private val useCase = AnswerTheQuestionUseCase()<br>    val answer: String get() useCase.answerTheQuestion()<br>    fun answerTheQuestion() {<br>        useCase.answerTheQuestion()<br>    }<br>}</pre><p>To further apply the Single Responsibility Principle, it is often helpful to use design patterns such as the Model-View-ViewModel (MVVM) pattern within each layer. For example, in the presentation layer, the MVVM pattern can be used to separate the responsibility of the UI from the business logic like in the previous example the. use Case is separated of the ui and we can implement it with different extensions like we will see in next chapters .</p><h4>RepositoryPattern and SRP</h4><p>By using the Repository pattern, you can apply the Single Responsibility Principle (SRP) in the data layer of a software system by separating the responsibility of data management from the business logic. This can help to make the code easier to understand and maintain, and it can also make it easier to modify the data layer without affecting the business logic .</p><pre>class AnswerQuestionUseCase {<br>  private val repository = QuestionRepository();<br>  <br>  fun answer(): String {<br>    val theAnswer = repository.answerQuestion()<br>     return theAnswer<br>  }<br>}<br><br>class AnswerRepository {<br>    fun answerQuestion(){/*Logic*/}<br>    fun saveQuestion(){/*Logic*/}<br><br>}</pre><p>in this example AnswerQuestionUseCase class is responsible for the business logic of the getting the answer of the question the QuestionRepository is responsible for managing data and interacting with the database. by using the repository pattern, the AnswerQuestionUseCase provided by QuestionRepository class we avoid complexity burden viewModels .</p><p>Thanks to a single UseCase class, we can do these operations wherever we want.</p><h3>Conclusion</h3><p>In summary, the SRP is an important principle in software design that helps to create maintainable and scalable code by ensuring that each class or module has a single well-defined responsibility. Clean architecture is a pattern that helps to apply the SRP by orgonazing the code into distinct layers, each with a specific responsibility, and minimizing the dependencies between the layers . See you in the next Chapter to understand SOLID and Clean Architecture .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea2297f75b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>