<?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 Öznur Demir on Medium]]></title>
        <description><![CDATA[Stories by Öznur Demir on Medium]]></description>
        <link>https://medium.com/@dmroznurr?source=rss-b2498bce227b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pwOEM5RHSFuwjEqG</url>
            <title>Stories by Öznur Demir on Medium</title>
            <link>https://medium.com/@dmroznurr?source=rss-b2498bce227b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:00:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dmroznurr/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[State Management in Flutter: The Power of the BLoC Pattern ]]></title>
            <link>https://medium.com/@dmroznurr/state-management-in-flutter-the-power-of-the-bloc-pattern-89e5574b77c6?source=rss-b2498bce227b------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e5574b77c6</guid>
            <category><![CDATA[flutterdev]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[bloc]]></category>
            <dc:creator><![CDATA[Öznur Demir]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 11:57:25 GMT</pubDate>
            <atom:updated>2025-02-18T11:57:25.168Z</atom:updated>
            <content:encoded><![CDATA[<p>As the complexity of modern mobile applications increases, state management becomes critically important. The Business Logic Component (BLoC) pattern comes to the rescue of Flutter developers precisely at this point ✨.</p><h4>What is State Management and Why is it Important?</h4><p>The state of an application represents all the data it holds at any given moment. User preferences, API responses, form data, and even the visual state of the UI — all these are parts of the state 📱. Managing this data is one of the most challenging aspects of modern application development. Poor state management can lead to performance issues, incorrect UI updates, and codebases that are difficult to maintain.</p><h4>The Main Purpose of the BLoC Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUsorHMw1bBJJo9CRcUB0g.png" /></figure><p>BLoC allows you to write clean and maintainable code by separating business logic from the UI ⚡. It applies reactive programming principles using streams. This approach makes data flow unidirectional and predictable.</p><h4>Why Choose BLoC?</h4><ol><li><strong>Separation of Concerns:</strong> Clearly separating the UI and business logic enhances code organization and testability 🎯</li><li><strong>Reactive Programming:</strong> Its stream-based structure makes managing real-time data flow easier</li><li><strong>Testability:</strong> Isolating business logic simplifies unit testing ✅</li><li><strong>Scalability:</strong> It ensures sustainable state management even in large projects.</li><li><strong>Code Reusability: </strong>BLoCs can be easily shared between different widgets.</li></ol><p>This pattern, supported by Google, is especially preferred in enterprise-level applications. It aligns perfectly with Flutter’s reactive structure and offers a powerful solution for managing complex state scenarios 💪.</p><p>Like every pattern, BLoC also has a learning curve, but the advantages it provides more than make up for this investment. In the following sections, we will examine BLoC in more detail with practical examples.</p><h4>The Fundamental Principles of the BLoC Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrJo9ukJwGXc6MKtf1w51w.png" /></figure><p><strong>The Concepts of Event and State </strong>🔄</p><p>The foundation of the BLoC pattern is based on the concepts of Event and State. Events are actions triggered by user interactions or system occurrences. State, on the other hand, represents the application’s condition at a specific moment.</p><pre>// Event Example<br>abstract class CounterEvent {}<br>class IncrementEvent extends CounterEvent {}<br>class DecrementEvent extends CounterEvent {}<br><br>// State Example<br>class CounterState {<br>  final int count;<br>  CounterState(this.count);<br>}</pre><p><strong>Stream Usage</strong></p><p>BLoC manages data flow using Dart’s Stream API 🌊. StreamController receives Events and broadcasts States.</p><pre>class CounterBloc extends Bloc&lt;CounterEvent, CounterState&gt; {<br>  CounterBloc() : super(CounterState(0)) {<br>    on&lt;IncrementEvent&gt;((event, emit) {<br>      emit(CounterState(state.count + 1));<br>    });<br>    <br>    on&lt;DecrementEvent&gt;((event, emit) {<br>      emit(CounterState(state.count - 1));<br>    });<br>  }<br>}</pre><h4>Simple Example with BLoC: Favorite List Application</h4><p>Let’s create a practical example to demonstrate BLoC in action ⭐. We’ll build a favorite list feature where users can add or remove items from their favorites list.</p><p><strong>Favorite List Application</strong></p><p>Our goal is for the user to be able to add or remove an item from their favorites 📝. This example will help you better understand the basic operation of BLoC and event-state management.</p><ol><li><strong>Event and State Definitions</strong></li></ol><p>First, we define the Event and State classes that represent adding and removing items from the favorites.</p><pre>// Event Classes:<br>abstract class FavoriteEvent {}<br><br>class AddToFavorite extends FavoriteEvent {<br>  final String item;<br>  AddToFavorite(this.item);<br>}<br><br>class RemoveFromFavorite extends FavoriteEvent {<br>  final String item;<br>  RemoveFromFavorite(this.item);<br>}</pre><p>These event classes are used for adding (AddToFavorite) and removing (RemoveFromFavorite) items from the favorites.</p><pre>// State Class:<br>class FavoriteState {<br>  final List&lt;String&gt; favorites;<br>  FavoriteState(this.favorites);<br>}</pre><p>The State class holds the list of favorites. The favorites are stored as a List&lt;String&gt;.</p><p>2. <strong>BLoC Class</strong></p><p>Now, let’s write the BLoC class to add and remove items from the favorites. Whenever an event is triggered, the corresponding item is added or removed from the list.</p><pre>class FavoriteBloc extends Bloc&lt;FavoriteEvent, FavoriteState&gt; {<br>  FavoriteBloc() : super(FavoriteState([])) {<br>    on&lt;AddToFavorite&gt;((event, emit) {<br>      final updatedFavorites = List&lt;String&gt;.from(state.favorites)..add(event.item);<br>      emit(FavoriteState(updatedFavorites));<br>    });<br><br>    on&lt;RemoveFromFavorite&gt;((event, emit) {<br>      final updatedFavorites = List&lt;String&gt;.from(state.favorites)..remove(event.item);<br>      emit(FavoriteState(updatedFavorites));<br>    });<br>  }<br>}</pre><p>This class manages two events for adding and removing items from favorites. Each time an event is triggered, the current favorites list is updated, and a new state is emitted.</p><p>3.<strong> UI Integration with BLoC </strong>🎨</p><p>Finally, let’s create the favorite list UI. The user should be able to add and remove items from their favorites.</p><pre>class FavoritePage extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (_) =&gt; FavoriteBloc(),<br>      child: Scaffold(<br>        appBar: AppBar(title: Text(&quot;Favorite List&quot;)),<br>        body: BlocBuilder&lt;FavoriteBloc, FavoriteState&gt;(<br>          builder: (context, state) {<br>            return Column(<br>              children: [<br>                ListView.builder(<br>                  shrinkWrap: true,<br>                  itemCount: 10, // Example number of items<br>                  itemBuilder: (context, index) {<br>                    final item = &#39;Item ${index + 1}&#39;;<br>                    final isFavorite = state.favorites.contains(item);<br><br>                    return ListTile(<br>                      title: Text(item),<br>                      trailing: IconButton(<br>                        icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),<br>                        onPressed: () {<br>                          if (isFavorite) {<br>                            context.read&lt;FavoriteBloc&gt;().add(RemoveFromFavorite(item));<br>                          } else {<br>                            context.read&lt;FavoriteBloc&gt;().add(AddToFavorite(item));<br>                          }<br>                        },<br>                      ),<br>                    );<br>                  },<br>                ),<br>                SizedBox(height: 20),<br>                Text(&#39;Favorite Items: ${state.favorites.join(&#39;, &#39;)}&#39;, style: TextStyle(fontSize: 18)),<br>              ],<br>            );<br>          },<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>This UI allows the user to add and remove items from their favorites. Each ListTile contains a button, and when clicked, it either adds or removes the item from the favorites. Changes in the favorites are immediately reflected on the screen.</p><h4>Advantages of BLoC</h4><ol><li><strong>Separation of Concerns </strong>🎯</li></ol><p>BLoC ensures a clear separation between the UI and business logic. The UI is responsible only for visualizing data, while the business logic is managed by BLoC. This way, both layers can work independently from each other, and the code becomes cleaner and more maintainable 🧩.</p><p><strong>Example:</strong> The UI listens to the CounterState, while the business logic resides within the CounterBloc and is solely concerned with data processing.</p><pre>class CounterBloc extends Bloc&lt;CounterEvent, CounterState&gt; {<br>  CounterBloc() : super(CounterState(0));<br><br>  @override<br>  Stream&lt;CounterState&gt; mapEventToState(CounterEvent event) async* {<br>    if (event is IncrementEvent) {<br>      yield CounterState(state.count + 1);<br>    }<br>  }<br>}</pre><p>2. <strong>Testability</strong></p><p>Since BLoC separates the business logic from the UI, it allows the business logic to be tested independently. Each BLoC function can be tested with different scenarios.</p><p><strong>Example:</strong> To test BLoC, we can trigger a specific event and check the expected state.</p><pre>test(&#39;should emit [CounterState] with incremented count&#39;, () {<br>  final bloc = CounterBloc();<br>  <br>  bloc.add(IncrementEvent());<br>  <br>  expectLater(bloc.stream, emits(CounterState(1)));<br>});</pre><h4>BLoC and Other State Management Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIZ-iyEPuagep1_pYD_mXg.png" /></figure><p><strong>BLoC vs. Provider vs. Riverpod </strong>🔄</p><p>Each state management method offers advantages for different needs:</p><ul><li><strong>Provider</strong>: A simple and lightweight solution that easily manages UI updates. It is suitable for small to medium-sized projects. However, it may fall short in applications with complex business logic 🌱.</li><li><strong>Riverpod</strong>: A more powerful version of Provider. It is more flexible and testable, especially beneficial for asynchronous operations. However, its learning curve may be slightly steeper than Provider.</li><li><strong>BLoC</strong>: Preferred for large, complex projects. It completely separates the UI from the business logic, offering modularity and testability. However, its structure may require writing more code, and it might take time to learn 🏢.</li></ul><p><strong>When is BLoC More Suitable?</strong></p><p>BLoC is the best choice in the following situations:</p><ul><li><strong>Large and complex projects</strong>: When independent, robust business logic is required, BLoC makes the project more modular 🏗️.</li><li><strong>When testability is important</strong>: By separating business logic from the UI, each component can be tested independently.</li><li><strong>When asynchronous data flow is required</strong>: Its stream-based structure is ideal for situations where data is constantly changing.</li></ul><p><strong>Example:</strong> In an e-commerce application, tasks like adding products to the cart or handling payment processes can become complex workflows. BLoC helps make these tasks more organized and manageable.</p><h4>Conclusion</h4><p>BLoC provides powerful state management in Flutter projects, ensuring clean, testable, and maintainable code. Especially in large and complex applications, it completely separates business logic from the UI, offering a modular structure.</p><p>In this article, we explored the core principles of BLoC, its advantages, and a comparison with other state management methods. If you want to develop scalable and robust applications with Flutter, continuing to learn BLoC will be a valuable investment.</p><p><strong>Resources for Further Learning </strong>📚</p><ul><li><strong>Official BLoC Documentation</strong>: <a href="https://bloclibrary.dev/">https://bloclibrary.dev</a></li><li><strong>Felix Angelov’s Medium Articles on BLoC</strong></li><li><strong>Official Flutter YouTube Channel</strong>: Contains detailed guides on BLoC</li><li><strong>Open Source BLoC Projects on GitHub</strong>: Learn by examining real-world applications</li></ul><p>Remember to start small and gradually build up to more complex implementations 🌱. With practice, you’ll master the power of BLoC and create more maintainable Flutter applications.</p><p>Happy coding! 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e5574b77c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizable Calendar Widget with Flutter: flutter_custom_calendar]]></title>
            <link>https://medium.com/@dmroznurr/customizable-calendar-widget-with-flutter-flutter-custom-calendar-b8e7bedb159d?source=rss-b2498bce227b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8e7bedb159d</guid>
            <category><![CDATA[custom-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Öznur Demir]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 07:00:14 GMT</pubDate>
            <atom:updated>2024-10-10T11:27:01.513Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s mobile application development processes, user experience plays a significant role. In this context, a calendar widget that allows users to easily select dates and navigate between months can greatly enhance the value of your applications. This is where the <strong>flutter_custom_calendar</strong> package comes in. Designed to facilitate date selection for users and to customize the appearance of your app, this widget stands out with its features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y6D6JK8Mt45iiL9jf-IuQ.jpeg" /><figcaption>calender widget (tr)</figcaption></figure><h4><strong>Features</strong></h4><ol><li>Customizable Appearance</li></ol><p>You can customize visual elements like the background color of the calendar, the color of the selected day, and the text color as you wish. For example:</p><pre>FlutterCustomCalendar(<br>  selectedDate: DateTime.now(),<br>  calenderBackgroundColor: Colors.white,<br>  selectedDayColor: Colors.orange,<br>  unselectedDayColor: Colors.transparent,<br>  selectedDayTextColor: Colors.white,<br>  unselectedDayTextColor: Colors.black,<br>  onDateSelected: (DateTime date) {<br>    print(&#39;Selected date: $date&#39;);<br>  },<br>)</pre><p>2. Date Selection</p><p>Users can easily select any day in the calendar by clicking on it. This feature provides a more interactive experience for users with your application. For instance, in the code above, the onDateSelected function is used to print the selected date to the console.</p><p>3. Month Navigation</p><p>Users can navigate between months using the back and forward buttons on the calendar. This process makes the navigation of your application smoother. For example, you can display the month and year information in the header section of the calendar widget:</p><pre>Widget _buildHeader(String locale) {<br>  List&lt;String&gt; months = AppLocalizations.getMonths(locale);<br>  String monthName = months[widget.selectedDate.month - 1];<br><br>  return Row(<br>    mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>    children: [<br>      IconButton(<br>        icon: Icon(widget.previousMonthIcon),<br>        onPressed: _previousMonth,<br>      ),<br>      Text(&#39;$monthName ${widget.selectedDate.year}&#39;),<br>      IconButton(<br>        icon: Icon(widget.nextMonthIcon),<br>        onPressed: _nextMonth,<br>      ),<br>    ],<br>  );<br>}</pre><p>4. Responsive Design</p><p>The calendar widget is designed to adapt to different screen sizes. This way, users can enjoy a consistent experience, regardless of the device they are using.</p><p>5. Multi-Language Support</p><p>The <strong>flutter_custom_calendar</strong> package supports multiple languages, specifically English, Turkish, Urdu, and Chinese. This localization feature allows you to display month names and day names in these languages, enhancing accessibility for users from different linguistic backgrounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*kTgA4pyg6LCQBLtS4NJq-Q.jpeg" /><figcaption>calender widget (tr)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*Qb-GhmVhVqOpyMVw84cfDA.jpeg" /><figcaption>calendar widget (zh)</figcaption></figure><p>To implement localization, use the flutter_localizations package. Here’s how to set it up:</p><pre>import &#39;package:flutter_localizations/flutter_localizations.dart&#39;;<br><br>MaterialApp(<br>  localizationsDelegates: [<br>    GlobalMaterialLocalizations.delegate,<br>    GlobalWidgetsLocalizations.delegate,<br>    GlobalCupertinoLocalizations.delegate,<br>  ],<br>  supportedLocales: [<br>    const Locale(&#39;en&#39;, &#39;&#39;), // English<br>    const Locale(&#39;tr&#39;, &#39;&#39;), // Turkish<br>    const Locale(&#39;ur&#39;, &#39;&#39;), // Urdu<br>    const Locale(&#39;zh&#39;, &#39;&#39;), // Chinese<br>  ],<br>  // Other properties...<br>)</pre><h4>Getting Started</h4><p>Getting started with the <strong>flutter_custom_calendar</strong> package is quite easy. Here are the necessary steps:</p><ol><li>Add the flutter_custom_calendar dependency to your <strong>pubspec.yaml</strong> file:</li></ol><pre>dependencies:<br>  flutter_custom_calendar: ^0.0.1</pre><p>2. Load the package:</p><pre>flutter pub get</pre><p>3. Import the package into your Dart file:</p><pre>import &#39;package:flutter_custom_calendar/flutter_custom_calendar.dart&#39;;</pre><h4>Example Usage</h4><p>Below is a simple example of how to use the CustomCalendar widget in your application:</p><pre>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(<br>          title: Text(&#39;Customizable Calendar Example&#39;),<br>        ),<br>        body: Center(<br>          child: FlutterCustomCalendar(<br>            selectedDate: DateTime.now(),<br>            calenderBackgroundColor: Colors.white,<br>            selectedDayColor: Colors.orange,<br>            unselectedDayColor: Colors.transparent,<br>            selectedDayTextColor: Colors.white,<br>            unselectedDayTextColor: Colors.black,<br>            onDateSelected: (DateTime date) {<br>              print(&#39;Selected date: $date&#39;);<br>            },<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>void main() {<br>  runApp(MyApp());<br>}</pre><h4>Conclusion</h4><p>The flutter_custom_calendar package offers a great solution to enhance the user experience in your Flutter applications. With its customizable features, user-friendly interface, and easy integration, it aims to provide your users with a seamless and enjoyable date selection experience. Now, add this package to your applications and elevate the way your users interact with dates!</p><p>You can find and use the package on Pub.dev: <a href="https://pub.dev/packages/flexible_calendar_widget">Pub.dev — Flexible Calendar</a> Widget<br>If you’re interested in contributing or reviewing the code, feel free to check out the project on my GitHub page: <a href="https://github.com/oznurdemir/flexible_calendar_widget">GitHub Repository</a><br>I’d love to hear your feedback and see your contributions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8e7bedb159d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles in Kotlin: A Quick Guide]]></title>
            <link>https://medium.com/@dmroznurr/solid-principles-in-kotlin-a-quick-guide-a5ed03fda0cf?source=rss-b2498bce227b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5ed03fda0cf</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Öznur Demir]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 07:29:49 GMT</pubDate>
            <atom:updated>2024-08-06T07:29:49.595Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In software development processes, code quality, sustainability, and flexibility are crucial factors. The SOLID principles guide developers to achieve these goals. SOLID is an acronym consisting of five fundamental principles that aim to produce high-quality code in software design. In this article, we will explore the SOLID principles in depth and explain how each principle can be applied with examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*p3coHZrM8IcORif2pp_aDA.png" /><figcaption>SOLID Principles</figcaption></figure><h3><strong>What is SOLID?</strong></h3><p>SOLID is an acronym that stands for five core principles:</p><ul><li><strong>S: Single Responsibility Principle (SRP)</strong> — A class should have only one responsibility and that responsibility should be entirely encapsulated by the class. In other words, a class should only have one job, and changes to that job should only affect that class.</li><li><strong>O: Open/Closed Principle (OCP)</strong> — Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means that you should be able to add new functionality without changing existing code.</li><li><strong>L: Liskov Substitution Principle (LSP)</strong> — Derived classes should be able to substitute their base classes without affecting the correctness of the program. In other words, derived classes should honor the expectations set by the base class.</li><li><strong>I: Interface Segregation Principle (ISP)</strong> — A class should not be forced to implement interfaces it does not use. Interfaces should be specific and tailored to the needs of the client.</li><li><strong>D: Dependency Inversion Principle (DIP)</strong> — High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.</li></ul><p>These principles help make software more modular, flexible, and maintainable. Let’s examine each principle in detail.</p><h4><strong>S: Single Responsibility Principle (SRP)</strong></h4><p>A class should have only one reason to change, meaning it should have only one responsibility. This principle ensures that a class does one thing and does it well, and any changes to that responsibility affect only that class.</p><p><strong>Example:</strong></p><pre>//Code Violating SRP:<br>class UserManager {<br>    fun addUser(user: String) {<br>        // Code to add a user<br>    }<br><br>    fun generateUserReport() {<br>        // Code to generate user report<br>    }<br>}</pre><p>This class handles both user management and report generation, demonstrating multiple responsibilities.</p><pre>//SRP Compliant Version:<br>class UserManager {<br>    fun addUser(user: String) {<br>        // Code to add a user<br>    }<br>}<br><br>class UserReport {<br>    fun generateReport() {<br>        // Code to generate user report<br>    }<br>}</pre><p>Here, the UserManager class is responsible only for user management, while the UserReport class handles report generation, ensuring single responsibility for each class.</p><h4><strong>O: Open/Closed Principle (OCP)</strong></h4><p>Software entities should be open for extension but closed for modification. This means that you should be able to extend the behavior of a class without altering its existing code.</p><p><strong>Example:</strong></p><pre>//Code Violating OCP:<br>class ReportGenerator {<br>    fun generateReport(reportType: String) {<br>        when (reportType) {<br>            &quot;pdf&quot; -&gt; {<br>                // Code to generate PDF report<br>            }<br>            &quot;xls&quot; -&gt; {<br>                // Code to generate XLS report<br>            }<br>        }<br>    }</pre><p>This class requires modification whenever a new report type is added.</p><pre>//OCP Compliant Version:<br>interface ReportGenerator {<br>    fun generateReport()<br>}<br><br>class PDFReportGenerator : ReportGenerator {<br>    override fun generateReport() {<br>        // Code to generate PDF report<br>    }<br>}<br><br>class XLSReportGenerator : ReportGenerator {<br>    override fun generateReport() {<br>        // Code to generate XLS report<br>    }<br>}</pre><p>In this version, ReportGenerator is an interface that defines a contract for generating reports. Specific report types implement this contract, allowing for new types to be added without changing existing code.</p><h4><strong>L: Liskov Substitution Principle (LSP)</strong></h4><p>Derived classes should be able to replace their base classes without affecting the correctness of the program. In essence, derived classes should not alter the behavior expected by the base class.</p><p><strong>Example:</strong></p><pre>//Code Violating LSP:<br>open class Bird {<br>    open fun fly() {<br>        // Code to fly<br>    }<br>}<br><br>class Penguin : Bird() {<br>    override fun fly() {<br>        throw UnsupportedOperationException(&quot;Penguins cannot fly&quot;)<br>    }<br>}</pre><p>Here, the Penguin class breaks the Bird class’s contract by not implementing the fly method.</p><pre>//LSP Compliant Version:<br>abstract class Bird {<br>    abstract fun move()<br>}<br><br>class Sparrow : Bird() {<br>    override fun move() {<br>        // Code to fly<br>    }<br>}<br><br>class Penguin : Bird() {<br>    override fun move() {<br>        // Code to walk<br>    }<br>}</pre><p>In this version, Bird defines a move method that is implemented differently by Sparrow and Penguin. Both subclasses honor the base class’s expectations.</p><h4><strong>I: Interface Segregation Principle (ISP)</strong></h4><p>A class should not be forced to implement interfaces it does not use. Interfaces should be specific and only include the methods needed by the class.</p><p><strong>Example:</strong></p><pre>//Code Violating ISP:<br>class Worker {<br>    fun work() {<br>        // Code to work<br>    }<br><br>    fun eat() {<br>        // Code to eat<br>    }<br>}</pre><p>This class implements both work and eat methods, which represent different responsibilities.</p><pre>//ISP Compliant Version:<br>interface Workable {<br>    fun work()<br>}<br><br>interface Eatable {<br>    fun eat()<br>}<br><br>class Worker : Workable, Eatable {<br>    override fun work() {<br>        // Code to work<br>    }<br><br>    override fun eat() {<br>        // Code to eat<br>    }<br>}</pre><p>Here, Workable and Eatable interfaces are separated, and the Worker class implements only the interfaces it needs.</p><h4><strong>D: Dependency Inversion Principle (DIP)</strong></h4><p>High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.</p><p><strong>Example:</strong></p><pre>//Code Violating DIP:<br><br>class LightBulb {<br>    fun turnOn() {<br>        // Code to turn on<br>    }<br><br>    fun turnOff() {<br>        // Code to turn off<br>    }<br>}<br><br>class Switch(private val bulb: LightBulb) {<br>    fun operate() {<br>        // Code to operate the switch<br>    }<br>}</pre><p>Here, the Switch class directly depends on the LightBulb class, violating the dependency inversion principle.</p><pre>//DIP Compliant Version:<br>interface Switchable {<br>    fun turnOn()<br>    fun turnOff()<br>}<br><br>class LightBulb : Switchable {<br>    override fun turnOn() {<br>        // Code to turn on<br>    }<br><br>    override fun turnOff() {<br>        // Code to turn off<br>    }<br>}<br><br>class Switch(private val device: Switchable) {<br>    fun operate() {<br>        // Code to operate the switch<br>    }<br>}</pre><p>In this version, the Switch class depends on the Switchable abstraction rather than a concrete implementation. The LightBulb class implements this abstraction, allowing for more flexibility.</p><h3><strong>Benefits of Applying SOLID Principles</strong></h3><p>Applying SOLID principles results in more modular, testable, and maintainable code. These principles make software projects easier to manage, extend, and reduce the likelihood of errors. Adhering to SOLID principles enhances overall code quality and improves the development process.</p><h3><strong>Conclusion</strong></h3><p>The SOLID principles are crucial guidelines for software design. Applying these principles enhances code quality and makes the software development process more efficient. In this article, we have explored each SOLID principle and how to apply them. By incorporating these principles into your development practice, you can write better and more sustainable code.</p><h3><strong>Additional Resources and Reading Recommendations</strong></h3><ul><li><strong>“Clean Code: A Handbook of Agile Software Craftsmanship”</strong> by Robert C. Martin</li><li><strong>“Design Patterns: Elements of Reusable Object-Oriented Software”</strong> by Gamma, Helm, Johnson, Vlissides</li><li><strong>“Agile Software Development, Principles, Patterns, and Practices”</strong> by Robert C. Martin</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5ed03fda0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>