<?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 Suraj Yadav on Medium]]></title>
        <description><![CDATA[Stories by Suraj Yadav on Medium]]></description>
        <link>https://medium.com/@surajofficeemail?source=rss-828366bb0e1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UT53KuQc_agmFzDj</url>
            <title>Stories by Suraj Yadav on Medium</title>
            <link>https://medium.com/@surajofficeemail?source=rss-828366bb0e1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 15:30:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surajofficeemail/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[Understanding the Factory Design Pattern: A Beginner’s Guide]]></title>
            <link>https://medium.com/@surajofficeemail/understanding-the-factory-design-pattern-a-beginners-guide-599051debfb2?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/599051debfb2</guid>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Sat, 03 May 2025 09:23:50 GMT</pubDate>
            <atom:updated>2025-05-03T09:23:50.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dqJHmr0QRDlVgraV5u7Rw.png" /></figure><p>The Factory Design Pattern is one of the most widely used creational design patterns in software engineering. It provides a clean and flexible way to create objects without tightly coupling the client code to the specific classes being instantiated. In this blog post, we’ll explore the Factory Pattern, its variations — Simple Factory, Factory Method, and Abstract Factory — and provide clear examples to make it easy to understand, even for beginners. By the end, you’ll have a solid grasp of how to use this pattern in your projects.</p><h3>What is the Factory Design Pattern?</h3><p>The Factory Pattern is a creational design pattern that deals with object creation. Instead of directly instantiating objects using the new keyword, the Factory Pattern delegates the responsibility of object creation to a separate entity—a factory. This approach reduces coupling between the client code and the concrete classes, making the code more maintainable and scalable.</p><p>The pattern is particularly useful when:</p><ul><li>The exact type of object to be created is determined at runtime.</li><li>You want to encapsulate object creation logic to improve code flexibility.</li><li>You need to create objects that belong to a family of related classes.</li></ul><p>There are three main variations of the Factory Pattern: <strong>Simple Factory</strong>, <strong>Factory Method</strong>, and <strong>Abstract Factory</strong>. Let’s dive into each one with examples.</p><h3>1. Simple Factory: The Starting Point</h3><h3>What is it?</h3><p>A Simple Factory is not technically a design pattern but a programming idiom. It uses a static method to create and return instances of classes based on input parameters. This method acts as a centralized point for object creation, making it easy to manage but less extensible.</p><h3>Example</h3><p>Imagine a system where you need to create different types of users — students, teachers, or admins. Instead of directly instantiating these objects, you can use a Simple Factory.</p><pre>enum UserRole {<br>    STUDENT, TEACHER, ADMIN<br>}</pre><pre>class UserFactory {<br>    public static User createUser(UserRole role) {<br>        switch (role) {<br>            case STUDENT:<br>                return new Student(&quot;John&quot;, &quot;Doe&quot;);<br>            case TEACHER:<br>                return new Teacher(&quot;John&quot;, &quot;Doe&quot;);<br>            case ADMIN:<br>                return new Admin(&quot;John&quot;, &quot;Doe&quot;);<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown role&quot;);<br>        }<br>    }<br>}</pre><pre>class Student extends User {<br>    public Student(String firstName, String lastName) {<br>        super(firstName, lastName);<br>    }<br>}</pre><pre>class Teacher extends User {<br>    public Teacher(String firstName, String lastName) {<br>        super(firstName, lastName);<br>    }<br>}</pre><pre>class Admin extends User {<br>    public Admin(String firstName, String lastName) {<br>        super(firstName, lastName);<br>    }<br>}</pre><pre>abstract class User {<br>    String firstName, lastName;<br>    public User(String firstName, String lastName) {<br>        this.firstName = firstName;<br>        this.lastName = lastName;<br>    }<br>}</pre><p><strong>How it works:</strong></p><ul><li>The client code calls UserFactory.createUser(UserRole.STUDENT) to get a Student object without knowing the Student class.</li><li>The factory uses a switch statement to decide which class to instantiate.</li></ul><p><strong>Pros:</strong></p><ul><li>Simple to implement.</li><li>Centralizes object creation logic.</li></ul><p><strong>Cons:</strong></p><ul><li>Violates the <strong>Open-Closed Principle</strong> (you must modify the factory to add new types).</li><li>Not reusable for creating other types of objects.</li></ul><h3>2. Factory Method: Extensible and Reusable</h3><h3>What is it?</h3><p>The Factory Method Pattern moves the responsibility of object creation to subclasses. Instead of a static method, it defines an abstract method in a base class (or interface) that concrete subclasses implement to create specific objects. This makes the pattern extensible and reusable.</p><h3>Example</h3><p>Let’s extend the user creation example. Instead of a single factory, we create a base factory class with an abstract method for creating users.</p><pre>abstract class UserFactory {<br>    public abstract User createUser(String firstName, String lastName);<br>}</pre><pre>class StudentFactory extends UserFactory {<br>    @Override<br>    public User createUser(String firstName, String lastName) {<br>        return new Student(firstName, lastName);<br>    }<br>}</pre><pre>class TeacherFactory extends UserFactory {<br>    @Override<br>    public User createUser(String firstName, String lastName) {<br>        return new Teacher(firstName, lastName);<br>    }<br>}</pre><pre>// Usage<br>UserFactory factory = new StudentFactory();<br>User user = factory.createUser(&quot;John&quot;, &quot;Doe&quot;);</pre><p><strong>How it works:</strong></p><ul><li>The UserFactory abstract class declares the createUser method.</li><li>Concrete factories (StudentFactory, TeacherFactory) override this method to create specific user types.</li><li>The client code interacts with the abstract UserFactory type, not the concrete classes.</li></ul><p><strong>Pros:</strong></p><ul><li>Follows the <strong>Open-Closed Principle</strong> (add new factories without modifying existing code).</li><li>Reusable across different types of objects.</li><li>Reduces coupling between client code and concrete classes.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires creating new factory classes for each product type, which can increase complexity.</li></ul><h3>3. Abstract Factory: Families of Related Objects</h3><h3>What is it?</h3><p>The Abstract Factory Pattern is a “factory of factories.” It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This is useful when you need to ensure that objects created are compatible with each other.</p><h3>Example</h3><p>Consider a classroom system where students and teachers must belong to the same subject (e.g., Biology or Physics). An Abstract Factory ensures that a BiologyStudent is paired with a BiologyTeacher.</p><pre>abstract class ClassroomFactory {<br>    public abstract Student createStudent(String firstName, String lastName);<br>    public abstract Teacher createTeacher(String firstName, String lastName);<br>}</pre><pre>class BiologyClassroomFactory extends ClassroomFactory {<br>    @Override<br>    public Student createStudent(String firstName, String lastName) {<br>        return new BiologyStudent(firstName, lastName);<br>    }</pre><pre>    @Override<br>    public Teacher createTeacher(String firstName, String lastName) {<br>        return new BiologyTeacher(firstName, lastName);<br>    }<br>}</pre><pre>class PhysicsClassroomFactory extends ClassroomFactory {<br>    @Override<br>    public Student createStudent(String firstName, String lastName) {<br>        return new PhysicsStudent(firstName, lastName);<br>    }</pre><pre>    @Override<br>    public Teacher createTeacher(String firstName, String lastName) {<br>        return new PhysicsTeacher(firstName, lastName);<br>    }<br>}</pre><pre>class BiologyStudent extends Student {<br>    public BiologyStudent(String firstName, String lastName) {<br>        super(firstName, lastName);<br>    }<br>}</pre><pre>class BiologyTeacher extends Teacher {<br>    public BiologyTeacher(String firstName, String lastName) {<br>        super(firstName, lastName);<br>    }<br>}</pre><pre>// Usage<br>ClassroomFactory factory = new BiologyClassroomFactory();<br>Student student = factory.createStudent(&quot;John&quot;, &quot;Doe&quot;);<br>Teacher teacher = factory.createTeacher(&quot;Jane&quot;, &quot;Smith&quot;);</pre><p><strong>How it works:</strong></p><ul><li>The ClassroomFactory abstract class defines methods for creating related objects (Student and Teacher).</li><li>Concrete factories (BiologyClassroomFactory, PhysicsClassroomFactory) create objects that belong to the same family.</li><li>The client code uses the factory to create compatible objects without knowing their concrete classes.</li></ul><p><strong>Pros:</strong></p><ul><li>Ensures consistency among related objects.</li><li>Makes it easy to swap entire families of objects (e.g., switch from Biology to Physics).</li><li>Isolates concrete classes from client code.</li></ul><p><strong>Cons:</strong></p><ul><li>Can be complex to implement due to multiple factory and product classes.</li><li>Adding new products requires updating the abstract factory interface and all concrete factories.</li></ul><h3>Why Use the Factory Pattern?</h3><p>The Factory Pattern offers several benefits:</p><ol><li><strong>Decoupling</strong>: Client code doesn’t need to know the concrete classes, reducing tight coupling.</li><li><strong>Flexibility</strong>: Easily swap or extend object types without changing client code.</li><li><strong>Maintainability</strong>: Centralizes object creation logic, making it easier to manage.</li><li><strong>Scalability</strong>: Supports complex object creation scenarios, especially with Abstract Factory.</li></ol><p>However, it’s not without trade-offs:</p><ul><li>Simple Factory can violate design principles like Open-Closed.</li><li>Factory Method and Abstract Factory can introduce additional complexity due to multiple classes.</li></ul><h3>Real-World Applications</h3><p>The Factory Pattern is widely used in software development. Some examples include:</p><ul><li><strong>UI Frameworks</strong>: Creating platform-specific UI components (e.g., buttons, windows) using Abstract Factory.</li><li><strong>Dependency Injection</strong>: Frameworks like Spring use factories to create beans.</li><li><strong>Game Development</strong>: Creating different types of game characters or items dynamically.</li><li><strong>Database Drivers</strong>: Creating database connections (e.g., MySQL, PostgreSQL) using Factory Method.</li></ul><h3>Recap: Choosing the Right Factory</h3><ul><li><strong>Simple Factory</strong>: Use when you need a quick, centralized way to create objects but don’t need extensibility.</li><li><strong>Factory Method</strong>: Use when you want extensibility and reusability, and object creation logic should be delegated to subclasses.</li><li><strong>Abstract Factory</strong>: Use when you need to create families of related objects and ensure compatibility between them.</li></ul><p>Each variation serves a specific purpose, so choose based on your project’s requirements for flexibility, scalability, and complexity.</p><h3>Conclusion</h3><p>The Factory Design Pattern is a powerful tool for managing object creation in a flexible and decoupled way. By understanding its variations — Simple Factory, Factory Method, and Abstract Factory — you can apply the right approach to your projects. Whether you’re building a small application or a complex system, the Factory Pattern can help you write cleaner, more maintainable code.</p><p>Try implementing the examples above in your preferred programming language (Dart, C#, Java, Python, JavaScript, etc.) to get hands-on experience. If you have questions or want to explore other design patterns, let me know in the comments!</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599051debfb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Prototype Design Pattern in Dart]]></title>
            <link>https://medium.com/@surajofficeemail/understanding-the-prototype-design-pattern-in-dart-e386bd4622bf?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e386bd4622bf</guid>
            <category><![CDATA[prototype-design-pattern]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 13:22:28 GMT</pubDate>
            <atom:updated>2025-04-29T13:22:28.089Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tE6kiqJ28AQMnh8js9J_3w.png" /></figure><p>The Prototype Design Pattern is a powerful tool in a developer’s toolkit, especially when you need to create objects that are similar to each other without the overhead of building*.* It’s a creational pattern that focuses on cloning existing objects (called prototypes) to create new ones, saving time and resources. In this blog, we’ll explore the Prototype pattern, why it’s useful, and how to implement it in Dart in a clean, beginner-friendly way. Let’s dive in!</p><h3>What is the Prototype Design Pattern?</h3><p>Imagine you’re baking cookies. You’ve got a perfect cookie cutter for star-shaped cookies. Instead of shaping each cookie from scratch, you use the cutter to quickly make more stars. The Prototype pattern works similarly in programming. Instead of creating a new object from the ground up (which can be slow or complex), you “clone” an existing object and tweak it as needed.</p><p>This pattern is great when:</p><ul><li>Creating a new object is expensive (e.g., fetching data from an API or database).</li><li>You want to avoid repetitive setup code.</li><li>You need objects that are slightly different but share a common structure.</li></ul><p>For example, suppose you’re building a user management system and need to create multiple user objects with similar properties (like name, email, and role). Instead of calling an API or database for each user, you can clone a pre-configured user object and modify specific fields, like the ID or role.</p><h3>Why Use the Prototype Pattern?</h3><ol><li><strong>Efficiency</strong>: Cloning is often faster than creating objects from scratch, especially for complex objects.</li><li><strong>Simplicity</strong>: It hides the complexity of object creation from the client code.</li><li><strong>Flexibility</strong>: You can create variations of an object by tweaking the cloned copy without affecting the original.</li></ol><h3>Implementing the Prototype Pattern in Dart</h3><p>Let’s implement the Prototype pattern in Dart using a real-world example: a user management system. We’ll create a User class, a UserRegistry to store prototypes, and demonstrate cloning. The code will be clean, well-structured, and easy to understand.</p><h3>Step 1: Define the Clonable Interface</h3><p>In Dart, we can use an abstract class to define a clone method that all clonable objects must implement.</p><pre>abstract class Prototype {<br>  Prototype clone();<br>}</pre><p>This ensures any class implementing Prototype has a clone method.</p><h3>Step 2: Create the User Class</h3><p>Let’s create a User class that implements the Prototype interface. It’ll have fields like id, firstName, lastName, email, and role. The clone method will create a copy of the user.</p><pre>enum UserRole { student, teacher, admin }</pre><pre>class User implements Prototype {<br>  int id;<br>  String firstName;<br>  String lastName;<br>  String email;<br>  UserRole role;</pre><pre>  User({<br>    required this.id,<br>    required this.firstName,<br>    required this.lastName,<br>    required this.email,<br>    required this.role,<br>  });</pre><pre>  @override<br>  User clone() {<br>    return User(<br>      id: id,<br>      firstName: firstName,<br>      lastName: lastName,<br>      email: email,<br>      role: role,<br>    );<br>  }</pre><pre>  void setId(int newId) {<br>    id = newId;<br>  }</pre><pre>  @override<br>  String toString() {<br>    return &#39;User(id: $id, name: $firstName $lastName, email: $email, role: $role)&#39;;<br>  }<br>}</pre><p>Here, the clone method creates a new User with the same properties. The setId method lets us modify the cloned user’s ID.</p><h3>Step 3: Create a Prototype Registry</h3><p>A registry stores pre-defined prototypes for different user roles (e.g., Student, Teacher, Admin). This makes it easy to fetch and clone prototypes based on the role.</p><pre>class UserRegistry {<br>  final Map&lt;UserRole, User&gt; _prototypes = {};<br><br>void addPrototype(UserRole role, User user) {<br>    _prototypes[role] = user;<br>  }<br>  User? getPrototype(UserRole role) {<br>    final prototype = _prototypes[role];<br>    return prototype?.clone();<br>  }<br>}</pre><p>The registry uses a Map to store prototypes and provides methods to add and retrieve them. The getPrototype method returns a cloned copy to prevent modifying the original prototype.</p><h3>Step 4: Putting It All Together</h3><p>Let’s write a main function to demonstrate how the Prototype pattern works. We’ll create prototypes for different roles, store them in the registry, and clone them to create new users.</p><pre>void main() {<br>  // Create a registry<br>  final registry = UserRegistry();<br><br>// Create prototype users<br>  final studentPrototype = User(<br>    id: 0,<br>    firstName: &#39;John&#39;,<br>    lastName: &#39;Doe&#39;,<br>    email: &#39;john@doe.in&#39;,<br>    role: UserRole.student,<br>  );<br>  final teacherPrototype = User(<br>    id: 0,<br>    firstName: &#39;Jane&#39;,<br>    lastName: &#39;Smith&#39;,<br>    email: &#39;jane@smith.in&#39;,<br>    role: UserRole.teacher,<br>  );<br>  // Add prototypes to the registry<br>  registry.addPrototype(UserRole.student, studentPrototype);<br>  registry.addPrototype(UserRole.teacher, teacherPrototype);<br>  // Clone a student and modify it<br>  final student1 = registry.getPrototype(UserRole.student);<br>  student1?.setId(1);<br>  print(student1); // User(id: 1, name: John Doe, email: john@doe.in, role: student)<br>  // Clone another student<br>  final student2 = registry.getPrototype(UserRole.student);<br>  student2?.setId(2);<br>  print(student2); // User(id: 2, name: John Doe, email: john@doe.in, role: student)<br>  // Clone a teacher<br>  final teacher1 = registry.getPrototype(UserRole.teacher);<br>  teacher1?.setId(1);<br>  print(teacher1); // User(id: 1, name: Jane Smith, email: jane@smith.in, role: teacher)<br>}</pre><h3>How It Works</h3><ol><li>We create prototype users for student and teacher roles with default values.</li><li>These prototypes are stored in the UserRegistry.</li><li>To create a new user, we fetch a prototype from the registry and clone it.</li><li>We modify the cloned user’s ID (or other fields) as needed.</li><li>The original prototypes remain unchanged, and we avoid repetitive setup code.</li></ol><h3>When to Use the Prototype Pattern</h3><p>Use the Prototype pattern when:</p><ul><li>Object creation is resource-intensive (e.g., involves API calls or database queries).</li><li>You need multiple objects with similar properties but slight variations.</li><li>You want to decouple client code from the complexity of object creation.</li></ul><p>For example, in a game, you might use prototypes to create enemies with similar stats but different IDs or positions. In a web app, you could clone user profiles or form templates.</p><h3>Deep Cloning vs. Shallow Cloning</h3><p>Our example uses <strong>shallow cloning</strong>, where the clone method copies the object’s fields. If your object contains nested objects (e.g., a List or another class), you may need <strong>deep cloning</strong> to copy those nested objects as well. In Dart, you’d manually copy each nested object in the clone method.</p><p>For example, if User had a List&lt;String&gt; skills, you’d update the clone method:</p><pre>class User implements Prototype {<br>  // ... other fields ...<br>  List&lt;String&gt; skills;<br>User({required this.skills, /* other params */});<br>  @override<br>  User clone() {<br>    return User(<br>      id: id,<br>      firstName: firstName,<br>      lastName: lastName,<br>      email: email,<br>      role: role,<br>      skills: List.from(skills), // Deep copy the list<br>    );<br>  }<br>}</pre><p>This ensures the cloned user has its own copy of skills, so modifying it doesn’t affect the prototype.</p><h3>Advantages and Disadvantages</h3><h3>Advantages</h3><ul><li><strong>Performance</strong>: Faster than creating objects from scratch.</li><li><strong>Clean Code</strong>: Simplifies object creation for clients.</li><li><strong>Scalability</strong>: Works well with registries for managing multiple prototypes.</li></ul><h3>Disadvantages</h3><ul><li><strong>Complexity</strong>: Implementing cloning (especially deep cloning) can be tricky for complex objects.</li><li><strong>Memory</strong>: Cloning many objects can consume memory if not managed properly.</li></ul><h3>Real-World Example</h3><p>Imagine a mobile app where users can have different account types (e.g., Free, Premium, Admin). Each account type has default settings (e.g., storage limits, features). Instead of hardcoding each account’s settings, you can:</p><ol><li>Create prototype accounts for each type.</li><li>Store them in a registry.</li><li>Clone the appropriate prototype when a new user signs up and tweak their ID or email.</li></ol><p>This approach saves time, reduces errors, and makes the code easier to maintain.</p><h3>Conclusion</h3><p>The Prototype Design Pattern is a fantastic way to create objects efficiently by cloning existing ones. In Dart, it’s straightforward to implement using an abstract Prototype interface, concrete classes, and a registry for managing prototypes. Whether you’re building a user management system, a game, or a web app, this pattern can save time and simplify your code.</p><p>Try experimenting with the example above in DartPad or your IDE. Add more fields to the User class, create new roles, or implement deep cloning for nested objects. The Prototype pattern is versatile and fun to work with!</p><p>Happy coding, and let me know in the comments if you have questions or cool use cases for the Prototype pattern!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e386bd4622bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Principles vs. Design Patterns: Guiding the Art of Software Design]]></title>
            <link>https://medium.com/@surajofficeemail/design-principles-vs-design-patterns-guiding-the-art-of-software-design-eb5202f79802?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5202f79802</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 12:33:09 GMT</pubDate>
            <atom:updated>2025-04-29T12:33:09.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VpTNnvhhez9qQiSDwDeG5g.png" /></figure><p>In the world of software engineering, creating clean, maintainable, and scalable code is both an art and a science. Two foundational concepts — <strong>design principles</strong> and <strong>design patterns</strong> — play distinct but complementary roles in this process. As the saying goes: <em>design principles are the way to design, while design patterns are the way to solve</em>. Let’s explore what this means, especially in the context of low-level design (LLD).</p><h3>Design Principles: The Way to Design</h3><p>Design principles are high-level guidelines that shape <em>how</em> you approach software design. They act like a compass, ensuring your code is modular, readable, and adaptable. In LLD, where you define detailed class structures and interactions, principles provide the philosophical foundation for robust systems.</p><p>A prime example is the <strong>SOLID principles</strong>:</p><ul><li><strong>Single Responsibility Principle (SRP)</strong>: Each class should have one purpose.</li><li><strong>Open/Closed Principle (OCP)</strong>: Classes should be extensible without modifying their core.</li><li><strong>Liskov Substitution Principle (LSP)</strong>: Subtypes must seamlessly replace their base types.</li><li><strong>Interface Segregation Principle (ISP)</strong>: Keep interfaces specific to client needs.</li><li><strong>Dependency Inversion Principle (DIP)</strong>: Depend on abstractions, not concrete implementations.</li></ul><p>These principles address common issues like unreadable code or untestable modules by promoting modularity and loose coupling. For instance, applying SRP in LLD ensures a class handling payment validation doesn’t also generate receipts, making the code easier to maintain and test.</p><h3>Design Patterns: The Way to Solve</h3><p>While design principles guide your mindset, <strong>design patterns</strong> offer concrete solutions to recurring problems. They are reusable templates that you adapt to specific contexts, providing a proven way to tackle challenges in LLD.</p><p>Design patterns are grouped into three categories:</p><ul><li><strong>Creational</strong>: E.g., <strong>Singleton</strong> ensures a single instance of a class, or <strong>Factory Method</strong> abstracts object creation.</li><li><strong>Structural</strong>: E.g., <strong>Adapter</strong> bridges incompatible interfaces, or <strong>Decorator</strong> adds functionality dynamically.</li><li><strong>Behavioral</strong>: E.g., <strong>Observer</strong> manages event-driven updates, or <strong>Strategy</strong> swaps algorithms at runtime.</li></ul><p>For example, if you’re designing a notification system in LLD, the Observer pattern provides a ready-made solution for broadcasting updates to multiple subscribers, while adhering to principles like OCP by allowing new subscribers without modifying the core system.</p><h3>Principles and Patterns in Harmony</h3><p>The key difference is clear: <strong>principles guide the design process</strong>, ensuring your code is clean and flexible, while <strong>patterns provide specific solutions</strong> to well-known problems. In practice, they work together. For instance, applying DIP (a principle) might lead you to use dependency injection, which pairs well with the Factory pattern (a solution) to create objects dynamically.</p><p>In LLD, this synergy is critical. Principles like SOLID help you avoid pitfalls like tightly coupled or untestable code, while patterns offer battle-tested solutions to implement those principles effectively. Overusing patterns without principles can lead to bloated designs, while principles without patterns might leave you reinventing the wheel.</p><h3>Getting Started</h3><p>To leverage both in your projects:</p><ol><li><strong>Master SOLID</strong>: Start with principles like SRP and OCP to build a strong design foundation.</li><li><strong>Learn Key Patterns</strong>: Familiarize yourself with patterns like Factory, Observer, and Decorator for common LLD scenarios.</li><li><strong>Apply Thoughtfully</strong>: Use principles to guide your architecture and patterns to solve specific problems, ensuring balance.</li><li><strong>Refactor Regularly</strong>: Review your code to align with principles and optimize with patterns where needed.</li></ol><h3>Conclusion</h3><p>Design principles and patterns are two sides of the same coin in software design. Principles provide the <em>way to design</em> — a mindset for creating clean, maintainable systems — while patterns offer the <em>way to solve</em> — practical solutions for recurring challenges. By combining SOLID principles with patterns in low-level design, you can craft software that is both elegant and robust, ready to evolve with changing needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5202f79802" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles in Flutter: A Beginner-Friendly Guide with a Simple Example]]></title>
            <link>https://medium.com/@surajofficeemail/solid-principles-in-flutter-a-beginner-friendly-guide-with-a-simple-example-e377262085ec?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e377262085ec</guid>
            <category><![CDATA[solid-principles-in-dart]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[design-principles]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 13:40:14 GMT</pubDate>
            <atom:updated>2025-04-29T13:24:17.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eq2atJDujyeXV6KeJAn5GQ.png" /></figure><p>The SOLID principles are a set of five design guidelines that help you write clean, maintainable, and scalable Flutter apps. They might sound complex, but they’re really about keeping your code organized and easy to change. In this article, we’ll break down <strong>what</strong> each SOLID principle is, <strong>why</strong> it’s useful, and <strong>how</strong> to apply it in Flutter with a simple example of a settings manager for a Flutter app. Instead of using the Singleton pattern, we’ll use dependency injection (DI) to keep things flexible and testable.</p><h3>What are the SOLID Principles?</h3><p>SOLID stands for five principles that make your code better:</p><ol><li><strong>S — Single Responsibility Principle (SRP)</strong>: Each class should do one thing only.</li><li><strong>O — Open/Closed Principle (OCP)</strong>: You should be able to add new features without changing existing code.</li><li><strong>L — Liskov Substitution Principle (LSP)</strong>: Subclasses should work seamlessly in place of their parent class.</li><li><strong>I — Interface Segregation Principle (ISP)</strong>: Don’t force classes to use methods they don’t need.</li><li><strong>D — Dependency Inversion Principle (DIP)</strong>: Depend on abstractions (like interfaces), not specific implementations.</li></ol><p>These principles help you avoid messy code and make your Flutter apps easier to update and test.</p><h3>Why Use SOLID Principles in Flutter?</h3><p>Flutter apps can grow complex with widgets, state management, and data handling. SOLID principles help by:</p><ul><li><strong>Keeping Code Simple</strong>: Each class has a clear job, making it easier to understand.</li><li><strong>Making Changes Easy</strong>: Add features without breaking existing code.</li><li><strong>Improving Testing</strong>: Smaller, focused classes are easier to test.</li><li><strong>Reducing Bugs</strong>: Organized code means fewer surprises.</li></ul><p>For example, in a Flutter app that manages user settings (like theme or language), SOLID ensures that updating the theme doesn’t accidentally mess up the database or UI.</p><h3>How to Apply SOLID Principles in Flutter</h3><p>Let’s build a simple Flutter app that manages user settings (theme and language) and applies each SOLID principle. We’ll use dependency injection to pass dependencies around instead of a Singleton, making the code more flexible and testable. We’ll keep it minimal to focus on clarity.</p><h3>Step 1: Single Responsibility Principle (SRP)</h3><p><strong>What</strong>: A class should have one job or reason to change. For example, a class shouldn’t handle both settings logic and saving data.</p><p><strong>Why</strong>: If a class does too much, changing one part (like how data is saved) could break another (like how settings are displayed).</p><p><strong>How</strong>: Create a SettingsManager class that only manages settings (theme and language), not saving them or updating the UI.</p><pre>class SettingsManager {<br>  String theme = &#39;light&#39;;<br>  String language = &#39;en&#39;;<br>void setTheme(String newTheme) {<br>    theme = newTheme;<br>  }<br>  void setLanguage(String newLanguage) {<br>    language = newLanguage;<br>  }<br>}</pre><p><strong>Example</strong>: SettingsManager only handles settings logic. Saving settings to a database or updating the UI will be handled by separate classes, keeping SettingsManager focused.</p><h3>Step 2: Open/Closed Principle (OCP)</h3><p><strong>What</strong>: You should be able to add new features (like a new setting type) without changing existing code.</p><p><strong>Why</strong>: Changing existing code risks breaking things. Extending code (e.g., adding new classes) is safer.</p><p><strong>How</strong>: Use an abstract Setting class so new settings (e.g., font size) can be added without modifying SettingsManager.</p><pre>abstract class Setting {<br>  String getValue();<br>  void setValue(String value);<br>}</pre><pre>class ThemeSetting implements Setting {<br>  String _value = &#39;light&#39;;</pre><pre>  @override<br>  String getValue() =&gt; _value;</pre><pre>  @override<br>  void setValue(String value) =&gt; _value = value;<br>}</pre><pre>class LanguageSetting implements Setting {<br>  String _value = &#39;en&#39;;</pre><pre>  @override<br>  String getValue() =&gt; _value;</pre><pre>  @override<br>  void setValue(String value) =&gt; _value = value;<br>}</pre><pre>class SettingsManager {<br>  final Map&lt;String, Setting&gt; _settings = {<br>    &#39;theme&#39;: ThemeSetting(),<br>    &#39;language&#39;: LanguageSetting(),<br>  };</pre><pre>  Setting getSetting(String key) =&gt; _settings[key]!;<br>  void addSetting(String key, Setting setting) =&gt; _settings[key] = setting;<br>}</pre><p><strong>Example</strong>: To add a FontSizeSetting, create a new class implementing Setting and add it to SettingsManager without changing its code:</p><pre>class FontSizeSetting implements Setting {<br>  String _value = &#39;medium&#39;;<br>@override<br>  String getValue() =&gt; _value;<br>  @override<br>  void setValue(String value) =&gt; _value = value;<br>}</pre><h3>Step 3: Liskov Substitution Principle (LSP)</h3><p><strong>What</strong>: Any subclass should work correctly when used in place of its parent class.</p><p><strong>Why</strong>: If a subclass behaves differently, it could cause errors when code expects the parent’s behavior.</p><p><strong>How</strong>: Ensure all Setting implementations follow the same rules for getValue and setValue.</p><pre>class FontSizeSetting implements Setting {<br>  String _value = &#39;medium&#39;;<br>@override<br>  String getValue() =&gt; _value;<br>  @override<br>  void setValue(String value) {<br>    if ([&#39;small&#39;, &#39;medium&#39;, &#39;large&#39;].contains(value)) {<br>      _value = value;<br>    } else {<br>      throw ArgumentError(&#39;Invalid font size&#39;);<br>    }<br>  }<br>}</pre><p><strong>Example</strong>: FontSizeSetting can replace ThemeSetting in SettingsManager because it follows the Setting interface’s contract. A Flutter widget can use any Setting without issues.</p><h3>Step 4: Interface Segregation Principle (ISP)</h3><p><strong>What</strong>: Classes shouldn’t be forced to implement methods they don’t need.</p><p><strong>Why</strong>: Extra methods make code harder to maintain and can lead to errors.</p><p><strong>How</strong>: If some settings are read-only (e.g., an API key), create a smaller ReadOnlySetting interface.</p><pre>abstract class ReadOnlySetting {<br>  String getValue();<br>}</pre><pre>abstract class WritableSetting implements ReadOnlySetting {<br>  void setValue(String value);<br>}</pre><pre>class ThemeSetting implements WritableSetting {<br>  String _value = &#39;light&#39;;</pre><pre>  @override<br>  String getValue() =&gt; _value;</pre><pre>  @override<br>  void setValue(String value) =&gt; _value = value;<br>}</pre><pre>class ReadOnlyApiKeySetting implements ReadOnlySetting {<br>  @override<br>  String getValue() =&gt; &#39;abc123&#39;;<br>}</pre><pre>class SettingsManager {<br>  final Map&lt;String, ReadOnlySetting&gt; _settings = {<br>    &#39;theme&#39;: ThemeSetting(),<br>    &#39;apiKey&#39;: ReadOnlyApiKeySetting(),<br>  };</pre><pre>  ReadOnlySetting getSetting(String key) =&gt; _settings[key]!;<br>}</pre><p><strong>Example</strong>: A widget that only reads settings can use ReadOnlySetting, avoiding unnecessary methods like setValue.</p><h3>Step 5: Dependency Inversion Principle (DIP)</h3><p><strong>What</strong>: Depend on abstractions (like interfaces), not specific classes. For example, don’t tie SettingsManager to a specific database.</p><p><strong>Why</strong>: This makes it easy to swap implementations (e.g., from a mock database to a real one) without changing code.</p><p><strong>How</strong>: Create a SettingsRepository interface for saving settings and inject it into SettingsManager.</p><pre>abstract class SettingsRepository {<br>  Future&lt;void&gt; saveSetting(String key, String value);<br>  Future&lt;String&gt; loadSetting(String key);<br>}</pre><pre>class MockSettingsRepository implements SettingsRepository {<br>  final Map&lt;String, String&gt; _storage = {};</pre><pre>  @override<br>  Future&lt;void&gt; saveSetting(String key, String value) async {<br>    _storage[key] = value;<br>  }</pre><pre>  @override<br>  Future&lt;String&gt; loadSetting(String key) async {<br>    return _storage[key] ?? &#39;&#39;;<br>  }<br>}</pre><pre>class SettingsManager {<br>  final SettingsRepository repository;<br>  final Map&lt;String, WritableSetting&gt; _settings = {<br>    &#39;theme&#39;: ThemeSetting(),<br>  };</pre><pre>  SettingsManager(this.repository);</pre><pre>  WritableSetting getSetting(String key) =&gt; _settings[key]!;</pre><pre>  Future&lt;void&gt; save(String key) async {<br>    final setting = _settings[key]!;<br>    await repository.saveSetting(key, setting.getValue());<br>  }<br>}</pre><p><strong>Example</strong>: SettingsManager uses SettingsRepository, not a specific database. You can swap MockSettingsRepository with a FirebaseSettingsRepository without changing SettingsManager.</p><h3>Step 6: Building the Flutter App</h3><p>Here’s a simple Flutter app that uses SettingsManager with dependency injection. We’ll pass SettingsManager to widgets using the provider package for DI (add provider: ^6.0.0 to pubspec.yaml).</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br>void main() {<br>  final settingsManager = SettingsManager(MockSettingsRepository());<br>  runApp(<br>    ChangeNotifierProvider(<br>      create: (_) =&gt; SettingsProvider(settingsManager),<br>      child: MyApp(),<br>    ),<br>  );<br>}<br>class SettingsProvider extends ChangeNotifier {<br>  final SettingsManager manager;<br>  SettingsProvider(this.manager);<br>  String getTheme() =&gt; manager.getSetting(&#39;theme&#39;).getValue();<br>  void setTheme(String theme) {<br>    manager.getSetting(&#39;theme&#39;).setValue(theme);<br>    notifyListeners();<br>  }<br>  Future&lt;void&gt; saveTheme() =&gt; manager.save(&#39;theme&#39;);<br>}<br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      theme: Provider.of&lt;SettingsProvider&gt;(context).getTheme() == &#39;dark&#39;<br>          ? ThemeData.dark()<br>          : ThemeData.light(),<br>      home: Scaffold(<br>        appBar: AppBar(title: Text(&#39;SOLID Settings App&#39;)),<br>        body: Center(<br>          child: Column(<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: [<br>              ElevatedButton(<br>                onPressed: () {<br>                  Provider.of&lt;SettingsProvider&gt;(context, listen: false)<br>                      .setTheme(&#39;dark&#39;);<br>                },<br>                child: Text(&#39;Set Dark Theme&#39;),<br>              ),<br>              ElevatedButton(<br>                onPressed: () async {<br>                  await Provider.of&lt;SettingsProvider&gt;(context, listen: false)<br>                      .saveTheme();<br>                  ScaffoldMessenger.of(context).showSnackBar(<br>                    SnackBar(content: Text(&#39;Theme saved&#39;)),<br>                  );<br>                },<br>                child: Text(&#39;Save Theme&#39;),<br>              ),<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p><strong>How It Works</strong>:</p><ul><li>SettingsManager is created with a MockSettingsRepository and passed to SettingsProvider.</li><li>SettingsProvider wraps SettingsManager to notify widgets of changes.</li><li>The app uses provider to access settings and update the UI (e.g., switching themes).</li></ul><h3>Why No Singleton?</h3><p>Singletons create a global instance that’s hard to test and change. By using dependency injection (via provider), we:</p><ul><li>Make SettingsManager testable by passing mock dependencies.</li><li>Allow multiple SettingsManager instances if needed (e.g., for different users).</li><li>Keep the code flexible for future changes.</li></ul><h3>Best Practices</h3><ol><li><strong>Keep Classes Small</strong>: Each class should have one clear job (SRP).</li><li><strong>Use Interfaces</strong>: Abstract classes like Setting and SettingsRepository make code extensible (OCP, DIP).</li><li><strong>Validate Subclasses</strong>: Ensure subclasses follow their parent’s rules (LSP).</li><li><strong>Minimize Interfaces</strong>: Use small, focused interfaces like ReadOnlySetting (ISP).</li><li><strong>Use DI</strong>: Packages like provider or get_it make dependency injection easy and testable.</li><li><strong>Test Everything</strong>: Write unit tests for each class to catch errors early.</li></ol><h3>Summary</h3><p>The SOLID principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — help you write clean, flexible Flutter code. By applying them to a simple settings manager, we created an app that’s easy to extend, test, and maintain. Using dependency injection instead of a Singleton keeps the code modular and avoids global state issues.</p><p>Try applying SOLID to your next Flutter project! For more learning:</p><ul><li><a href="https://flutter.dev/docs">Flutter Documentation</a></li><li><a href="https://pub.dev/packages/provider">Provider Package</a></li><li><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">SOLID Principles Explained</a></li></ul><p>Share your thoughts or questions in the comments, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e377262085ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Builder Pattern in Dart/Flutter: A Step-by-Step Practical Guide]]></title>
            <link>https://medium.com/@surajofficeemail/mastering-the-builder-pattern-in-dart-flutter-a-step-by-step-practical-guide-4e25bce8326b?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e25bce8326b</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[builder-design-pattern]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 13:15:19 GMT</pubDate>
            <atom:updated>2025-04-29T13:56:40.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-HrKaY3uJ67xSfcnbUI8w.png" /></figure><p>The Builder pattern is a creational design pattern that allows for the step-by-step construction of complex objects. It’s particularly useful for creating objects with many optional parameters, ensuring immutability, and providing a clear and maintainable way to instantiate objects. In this blog post, we’ll explore the Builder pattern and implement it in <strong>Dart</strong>, a versatile language used for Flutter and other applications. We’ll create a Database class example, similar to the one discussed in the provided documents, to demonstrate the pattern’s benefits.</p><h3>Why Use the Builder Pattern?</h3><p>Before diving into the code, let’s understand why the Builder pattern is valuable:</p><ol><li><strong>Complex Object Creation</strong>: It avoids the telescoping constructor anti-pattern, where constructors with many parameters become unwieldy.</li><li><strong>Validation</strong>: It allows validation of parameters before object creation, preventing invalid states.</li><li><strong>Immutability</strong>: It supports creating immutable objects, which are easier to maintain and less prone to bugs.</li><li><strong>Flexibility</strong>: It enables different representations of an object using the same construction process.</li></ol><p>The Builder pattern is particularly useful in Dart, where immutability and clean code are emphasized, especially in Flutter applications.</p><h3>Step-by-Step Implementation in Dart</h3><p>Let’s implement the Builder pattern in Dart by creating a Database class that represents a database connection with parameters like host, port, username, and password. We’ll use the Builder pattern to construct Database objects in a type-safe, immutable, and flexible way.</p><h3>Step 1: Define the Database Class</h3><p>The Database class will hold the final, immutable state of the object. We’ll make its constructor private to prevent direct instantiation and ensure that objects are created only through the builder.</p><pre>class Database {<br>  final String host;<br>  final int port;<br>  final String username;<br>  final String password;<br>// Private constructor<br>  Database._({<br>    required this.host,<br>    required this.port,<br>    required this.username,<br>    required this.password,<br>  });<br>}</pre><p>Here, we use Dart’s final keyword to ensure immutability, and the _ prefix makes the constructor private.</p><h3>Step 2: Create the DatabaseBuilder Class</h3><p>The DatabaseBuilder class will handle the step-by-step construction of the Database object. It will have methods to set each parameter and a build method to create the final object.</p><pre>class DatabaseBuilder {<br>  String? _host;<br>  int? _port;<br>  String? _username;<br>  String? _password;<br><br>DatabaseBuilder host(String host) {<br>    _host = host;<br>    return this;<br>  }<br>  DatabaseBuilder port(int port) {<br>    _port = port;<br>    return this;<br>  }<br>  DatabaseBuilder username(String username) {<br>    _username = username;<br>    return this;<br>  }<br>  DatabaseBuilder password(String password) {<br>    _password = password;<br>    return this;<br>  }<br>  Database build() {<br>    // Provide default values or validate parameters<br>    if (_host == null || _host!.isEmpty) {<br>      throw Exception(&#39;Host is required and cannot be empty&#39;);<br>    }<br>    if (_port == null || _port! &lt;= 0) {<br>      throw Exception(&#39;Port is required and must be positive&#39;);<br>    }<br>    if (_username == null || _username!.isEmpty) {<br>      throw Exception(&#39;Username is required and cannot be empty&#39;);<br>    }<br>    if (_password == null || _password!.isEmpty) {<br>      throw Exception(&#39;Password is required and cannot be empty&#39;);<br>    }<br>    return Database._(<br>      host: _host!,<br>      port: _port!,<br>      username: _username!,<br>      password: _password!,<br>    );<br>  }<br>}</pre><p>In this implementation:</p><ul><li>Each setter method (host, port, etc.) returns this to enable method chaining.</li><li>The build method validates the parameters and constructs the Database object.</li><li>We use nullable fields (String?, int?) to allow optional parameters, with validation in the build method.</li></ul><h3>Step 3: Integrate the Builder with the Database Class</h3><p>To make the builder more accessible, we can add a static method or property to the Database class that returns a new DatabaseBuilder instance.</p><pre>class Database {<br>  final String host;<br>  final int port;<br>  final String username;<br>  final String password;<br>Database._({<br>    required this.host,<br>    required this.port,<br>    required this.username,<br>    required this.password,<br>  });<br>  // Static method to create a builder<br>  static DatabaseBuilder builder() =&gt; DatabaseBuilder();<br>}</pre><p>Now, users can create a Database object by calling Database.builder().</p><h3>Step 4: Using the Builder</h3><p>Here’s how to use the DatabaseBuilder to create a Database object:</p><pre>void main() {<br>  try {<br>    Database database = Database.builder()<br>        .host(&#39;localhost&#39;)<br>        .port(3306)<br>        .username(&#39;root&#39;)<br>        .password(&#39;password&#39;)<br>        .build();<br>print(&#39;Database created:&#39;);<br>    print(&#39;Host: ${database.host}&#39;);<br>    print(&#39;Port: ${database.port}&#39;);<br>    print(&#39;Username: ${database.username}&#39;);<br>    print(&#39;Password: ${database.password}&#39;);<br>  } catch (e) {<br>    print(&#39;Error: $e&#39;);<br>  }<br>}</pre><p>This code:</p><ul><li>Chains method calls to set parameters.</li><li>Calls build() to create the Database object.</li><li>Handles potential validation errors using a try-catch block.</li></ul><p>Running this code will output:</p><pre>Database created:<br>Host: localhost<br>Port: 3306<br>Username: root<br>Password: password</pre><p>If you omit a required parameter, such as host, the build method will throw an exception:</p><pre>Database database = Database.builder()<br>    .port(3306)<br>    .username(&#39;root&#39;)<br>    .password(&#39;password&#39;)<br>    .build();</pre><p>Output:</p><pre>Error: Exception: Host is required and cannot be empty</pre><h3>Step 5: Adding Flexibility with Optional Parameters</h3><p>The Builder pattern shines when you have optional parameters. Let’s modify the DatabaseBuilder to make username and password optional, with default values.</p><pre>class DatabaseBuilder {<br>  String? _host;<br>  int? _port;<br>  String? _username;<br>  String? _password;<br><br>DatabaseBuilder host(String host) {<br>    _host = host;<br>    return this;<br>  }<br>  DatabaseBuilder port(int port) {<br>    _port = port;<br>    return this;<br>  }<br>  DatabaseBuilder username(String username) {<br>    _username = username;<br>    return this;<br>  }<br>  DatabaseBuilder password(String password) {<br>    _password = password;<br>    return this;<br>  }<br>  Database build() {<br>    if (_host == null || _host!.isEmpty) {<br>      throw Exception(&#39;Host is required and cannot be empty&#39;);<br>    }<br>    if (_port == null || _port! &lt;= 0) {<br>      throw Exception(&#39;Port is required and must be positive&#39;);<br>    }<br>    return Database._(<br>      host: _host!,<br>      port: _port!,<br>      username: _username ?? &#39;guest&#39;, // Default value<br>      password: _password ?? &#39;none&#39;,  // Default value<br>    );<br>  }<br>}</pre><p>Now, you can create a Database object without specifying username or password:</p><pre>void main() {<br>  Database database = Database.builder()<br>      .host(&#39;localhost&#39;)<br>      .port(3306)<br>      .build();<br><br>print(&#39;Database created:&#39;);<br>  print(&#39;Host: ${database.host}&#39;);<br>  print(&#39;Port: ${database.port}&#39;);<br>  print(&#39;Username: ${database.username}&#39;);<br>  print(&#39;Password: ${database.password}&#39;);<br>}</pre><p>Output:</p><pre>Database created:<br>Host: localhost<br>Port: 3306<br>Username: guest<br>Password: none</pre><h3>Benefits of the Builder Pattern in Dart</h3><p>By implementing the Builder pattern in Dart, we achieve:</p><ol><li><strong>Type Safety</strong>: Unlike a hash map approach, the builder uses strongly-typed parameters, reducing runtime errors.</li><li><strong>Immutability</strong>: The Database class is immutable, thanks to final fields and a private constructor.</li><li><strong>Readability</strong>: Method chaining makes the code clear and expressive.</li><li><strong>Validation</strong>: The build method enforces parameter validation, ensuring objects are created in a valid state.</li><li><strong>Flexibility</strong>: Optional parameters and default values make the builder versatile.</li></ol><h3>When to Use the Builder Pattern</h3><p>Use the Builder pattern in Dart when:</p><ul><li>Your class has many parameters, especially optional ones.</li><li>You need to enforce immutability.</li><li>You want to validate parameters before object creation.</li><li>You need to create different representations of an object (e.g., different configurations of a Database).</li></ul><p>Common use cases in Dart/Flutter include:</p><ul><li>Configuring complex widgets or services.</li><li>Creating data models with many optional fields.</li><li>Setting up API clients or database connections.</li></ul><h3>Conclusion</h3><p>The Builder pattern is a powerful tool for creating complex objects in a clean, type-safe, and maintainable way. By implementing it in Dart, we can leverage the language’s features like immutability and method chaining to write robust code. The Database example demonstrates how to apply the pattern to a real-world scenario, ensuring flexibility and reliability.</p><p>Try implementing the Builder pattern in your next Dart or Flutter project to simplify object creation and improve code quality. For further reading, explore the telescoping constructor anti-pattern and the benefits of immutable objects.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e25bce8326b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing the Singleton Pattern in Flutter: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@surajofficeemail/implementing-the-singleton-pattern-in-flutter-a-step-by-step-guide-80cbb60ead15?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/80cbb60ead15</guid>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[flutter-singleton-pattern]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 12:15:26 GMT</pubDate>
            <atom:updated>2025-04-29T14:07:21.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMydeTunyPrLOH_BVJy0WQ.png" /></figure><p>The Singleton pattern is a powerful design pattern used in software development to ensure that a class has only one instance and provides a global point of access to it. In this article, we’ll dive deep into implementing the Singleton pattern in Flutter, exploring <strong>what</strong> it is, <strong>why</strong> it’s useful, and <strong>how</strong> to implement it step by step.</p><h3>What is the Singleton Pattern?</h3><p>The Singleton pattern is a creational design pattern that restricts a class to a single instance. This is particularly useful when you need to coordinate actions across your application using a single object, such as managing a database connection, logging mechanism, or application configuration.</p><h3>Key Characteristics:</h3><ul><li><strong>Single Instance</strong>: Ensures only one instance of the class exists.</li><li><strong>Global Access</strong>: Provides a static method to access the single instance.</li><li><strong>Private Constructor</strong>: Prevents external instantiation of the class.</li></ul><h3>Use Cases in Flutter:</h3><ul><li>Managing a single database connection (e.g., SQLite or Firebase).</li><li>Handling application-wide configuration settings.</li><li>Implementing a logging service to write to a single log file.</li></ul><h3>Why Use the Singleton Pattern in Flutter?</h3><p>Flutter applications often require centralized management of resources. Here’s why the Singleton pattern is beneficial:</p><ol><li><strong>Resource Efficiency</strong>: Prevents multiple instances of resource-heavy objects, like database connections, which could lead to performance issues.</li><li><strong>Consistency</strong>: Ensures all parts of the app access the same configuration or data source, avoiding inconsistencies.</li><li><strong>Simplified Access</strong>: Provides a single, globally accessible point to interact with the resource, reducing complexity in code.</li></ol><p>For example, imagine a Flutter app that needs to manage user settings. Without a Singleton, multiple instances of a settings class could lead to conflicting configurations. A Singleton ensures there’s only one source of truth.</p><h3>How to Implement the Singleton Pattern in Flutter</h3><p>Let’s walk through implementing the Singleton pattern in Flutter using Dart, focusing on a practical example: a DatabaseService class to manage a single database connection.</p><h3>Step 1: Create the Singleton Class</h3><p>Start by creating a DatabaseService class with a private constructor to prevent external instantiation.</p><pre>class DatabaseService {<br>  // Private constructor<br>  DatabaseService._();<br>}</pre><p>The _() syntax makes the constructor private, ensuring no other class can create a new instance.</p><h3>Step 2: Add a Static Instance</h3><p>Create a static variable to hold the single instance of the class. You can initialize it eagerly (at declaration) or lazily (on first access).</p><h4>Eager Initialization</h4><pre>class DatabaseService {<br><br>  // Private constructor<br>  DatabaseService._();<br><br><br>  // Static instance<br>  static final DatabaseService _instance = DatabaseService._();<br><br><br> static DatabaseService get instance {<br>    return _instance ;<br>  }<br>}</pre><p>Here, _instance is created when the class is loaded, ensuring it’s ready when needed.</p><h4>Lazy Initialization</h4><pre>class DatabaseService {<br>  // Static instance, initially null<br>  static DatabaseService? _instance;<br>  <br>  // Private constructor<br>  DatabaseService._();<br>}</pre><p>Lazy initialization defers instance creation until the first access, which can save resources if the instance isn’t always needed.</p><h3>Step 3: Provide a Global Access Point</h3><p>Add a static method or getter to access the instance. For lazy initialization, check if the instance exists and create it if necessary.</p><pre>class DatabaseService {<br>  static DatabaseService? _instance;<br>  <br>  // Private constructor<br>  DatabaseService._();<br>  <br>  // Static method to get instance<br>  static DatabaseService getInstance() {<br>    _instance ??= DatabaseService._();<br>    return _instance!;<br>  }<br>}</pre><p>The ??= operator creates the instance only if _instance is null. Alternatively, you can use a getter for cleaner syntax:</p><pre>class DatabaseService {<br>  static DatabaseService? _instance;<br>  <br>  DatabaseService._();<br>  <br>  static DatabaseService get instance {<br>    _instance ??= DatabaseService._();<br>    return _instance!;<br>  }<br>}</pre><h3>Step 4: Add Functionality</h3><p>Let’s add a simple method to simulate database operations, such as connecting to a database.</p><pre>class DatabaseService {<br>  static DatabaseService? _instance;<br>  <br>  DatabaseService._();<br>  <br>  static DatabaseService get instance {<br>    _instance ??= DatabaseService._();<br>    return _instance!;<br>  }<br>  <br>  void connect() {<br>    print(&#39;Connected to the database&#39;);<br>  }<br>  <br>  void query(String query) {<br>    print(&#39;Executing query: $query&#39;);<br>  }<br>}</pre><h3>Step 5: Use the Singleton in Your Flutter App</h3><p>Now, you can access the DatabaseService instance from anywhere in your app.</p><pre>void main() {<br>  // Access the singleton instance<br>  DatabaseService db = DatabaseService.instance;<br>  db.connect();<br>  db.query(&#39;SELECT * FROM users&#39;);<br>  <br>  // Accessing again returns the same instance<br>  DatabaseService anotherDb = DatabaseService.instance;<br>  print(identical(db, anotherDb)); // true, same instance<br>}</pre><h3>Step 6: Thread Safety in Flutter</h3><p>Dart’s single-threaded nature (running on the main isolate by default) means the basic Singleton implementation is thread-safe for most Flutter apps. However, if you use isolates or async operations, you might need thread safety.</p><p>To make the Singleton thread-safe, you can use a factory constructor with a lock (though this is rarely needed in Flutter):</p><pre>import &#39;dart:async&#39;;<br>class DatabaseService {<br>  static DatabaseService? _instance;<br>  static final _lock = Lock();<br>  <br>  DatabaseService._();<br>  <br>  static Future&lt;DatabaseService&gt; get instance async {<br>    await _lock.synchronized(() {<br>      _instance ??= DatabaseService._();<br>    });<br>    return _instance!;<br>  }<br>  <br>  void connect() {<br>    print(&#39;Connected to the database&#39;);<br>  }<br>}</pre><p><strong>Note</strong>: The Lock class requires the synchronized package (pubspec.yaml: synchronized: ^3.0.0). This ensures only one isolate creates the instance.</p><h3>Step 7: Testing the Singleton</h3><p>Create a simple Flutter app to test the Singleton:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>void main() {<br>  runApp(MyApp());<br>}<br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(title: Text(&#39;Singleton Demo&#39;)),<br>        body: Center(<br>          child: ElevatedButton(<br>            onPressed: () {<br>              DatabaseService db = DatabaseService.instance;<br>              db.connect();<br>              db.query(&#39;SELECT * FROM users&#39;);<br>            },<br>            child: Text(&#39;Connect to Database&#39;),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Clicking the button will use the same DatabaseService instance every time.</p><h3>Best Practices and Considerations</h3><ol><li><strong>Avoid Overusing Singletons</strong>: Singletons can make code harder to test and maintain. Use them only when a single instance is truly necessary.</li><li><strong>Dependency Injection</strong>: Consider using dependency injection (e.g., provider or get_it) for more flexible and testable code.</li><li><strong>Lazy vs. Eager Initialization</strong>:</li></ol><ul><li>Use <strong>eager initialization</strong> for critical resources that are always needed.</li><li>Use <strong>lazy initialization</strong> for resources that may not be used in every session.</li></ul><p>4.<strong> Thread Safety</strong>: Only add thread safety if your app uses isolates or heavy async operations.</p><h3>Summary</h3><p>The Singleton pattern in Flutter ensures a class has only one instance, providing a global access point for shared resources like database connections or configurations. By following these steps — private constructor, static instance, global access point, and optional thread safety — you can implement a robust Singleton in Dart.</p><p>For further reading, explore:</p><ul><li><a href="https://dart.dev/">Dart Documentation</a></li><li><a href="https://flutter.dev/docs/development">Flutter Design Patterns</a></li><li><a href="https://refactoring.guru/design-patterns/singleton">Singleton Pattern Variations</a></li></ul><p>Happy coding, and feel free to share your Singleton implementations in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80cbb60ead15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Local Storage, Shared Preference in Flutter]]></title>
            <link>https://medium.com/@surajofficeemail/a-local-storage-shared-preference-in-flutter-ff5665aec9ca?source=rss-828366bb0e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff5665aec9ca</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Suraj Yadav]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 09:22:34 GMT</pubDate>
            <atom:updated>2023-06-21T05:39:33.612Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Basically What is Shared Preference?</strong> To save the users small size data in App, Like some settings and some Data (Not too much, If much then need to go with some DataBase).</p><p>In flutter, Shared Preferences are stored in XML format. And it supports both iOS and Android.</p><h3>Why use SharedPreferences in Flutter?</h3><p>Suppose you wanna save a small value that you wanna refer later sometime when a user launches the application. Then shared preference comes into action.</p><p>We do not use SQLite for saving small values because then you will need to write lengthy codes and supporting classes.</p><p>To use SharedPreferences in Flutter, a plugin called <a href="https://gist.github.com/philipszdavido/aa5086ce7f0f85e50cddd008895ae4b6">shared_preferences</a> enables us to store data. The plugin wraps NSUserDefaults on iOS and SharedPreferences on Android.</p><h3>Installing shared_preferences.</h3><p>Now that we have the Flutter SDK ready and set, it’s time to install the shared_preferences plugin.</p><p>Open the pubspec.yaml file and add shared_preferences in the dependencies section:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  shared_preferences:</pre><p>This will install the latest version of the dependency.</p><p>To use the shared_preferences plugin, we have to import it into our file:</p><pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;</pre><p>The shared_preferences plugin exports a SharedPreferences class, which has methods that can be used to set data of various primitive types in SharedPreferences. It has a method, getInstance, which is used to create an instance of a SharedPreferences.</p><pre>SharedPreferences prefs = await SharedPreferences.getInstance();</pre><p>The getInstance creates and returns a SharedPreferences instance. The prefs holds the instance of SharedPreferences</p><h3>SharedPreferences methods.</h3><p>In this section, we’ll demonstrate how to add data to and get, edit, and delete data from SharedPreferences.</p><h3>Adding data</h3><p>It’s possible to add data of primitive types to SharedPreferences. We can add the following primitive types:</p><ul><li>int</li><li>string</li><li>bool</li><li>double</li></ul><p>Each primitive type has its corresponding setter method. (Note: The key of the key-value pair is in string.)</p><h4>Add int</h4><pre>prefs.setInt(&#39;count&#39;, 1);</pre><p>This adds an int, 1, to the count table of SharedPreferences.</p><h4>Get int data</h4><pre>int value = prefs.getInt(&#39;count&#39;);</pre><p>The getInt method is used to retrieve an int value from the SharedPreferences.</p><pre>value // 1</pre><h4>Add string</h4><pre>prefs.setString(&#39;isLoggedIn&#39;, &quot;yes&quot;);</pre><p>This adds a string, &quot;yes&quot;, to the isLoggedIn.</p><h4>Get string data</h4><pre>string value = prefs.getString(&#39;isLoggedIn&#39;);</pre><p>The getString method returns a string value from the SharedPreferences.</p><pre>value // &quot;yes&quot;</pre><h4>Add bool</h4><pre>prefs.setBool(&#39;isLoggedIn&#39;, true);</pre><p>This adds a bool, true, to the isLoggedIn.</p><h4>Get bool data</h4><pre>bool value = prefs.getBool(&#39;isLoggedIn&#39;);</pre><p>This method getBool returns a boolean value from the SharedPreferences.</p><pre>value // true</pre><h4>Add double</h4><pre>prefs.setDouble(&#39;doubleValue&#39;, 10.2);</pre><p>This adds a double value, 10.2, to the doubleValue.</p><h4>Get double data</h4><pre>double value = prefs.getDouble(&#39;doubleValue&#39;);</pre><p>The getDouble method returns a double value from the SharedPreferences.</p><pre>value // 10.2</pre><h3>Deleting data</h3><p>To remove data from the SharedPreferences, we’ll use the remove method. The key of the data is passed to the .remove method so the key-value pair data in the SharedPreferences is deleted.</p><pre>removeValues() async {<br>  SharedPreferences prefs = await SharedPreferences.getInstance();<br>  //Remove String<br>  prefs.remove(&quot;isLoggedIn&quot;);<br>  //Remove bool<br>  prefs.remove(&quot;isLoggedIn&quot;);<br>  //Remove int<br>  prefs.remove(&quot;count&quot;);<br>  //Remove double<br>  prefs.remove(&quot;doubleValue&quot;);<br>}</pre><h3>Remove all SharedPreferences saved data.</h3><pre>SharedPreferences prefs = await SharedPreferences.getInstance();<br><br>await prefs.clear();</pre><h3>Check value if present or not?</h3><pre>SharedPreferences prefs = await SharedPreferences.getInstance();<br><br>bool CheckValue = prefs.containsKey(&#39;isLoggedIn&#39;);</pre><p><em>containsKey will return true if persistent storage contains the given key and false if not.</em></p><h3>Conclusion</h3><p>In this tutorial, we covered what SharedPreferences is and how it is used in Android and iOS applications. We also introduced the shared_preferences plugin and learned how to set up Flutter with SharedPreferences.</p><p>Next, we learned how to import the shared_preferences plugin, walked through how to initialize its instance, and reviewed its methods and what all of them do.</p><p>Thanks for reading this article ❤</p><p>Connect with me on <a href="https://www.linkedin.com/in/suraj-yadav-251409174?challengeId=AQEFqTvyni6_YwAAAYjYGdhqzPulziDbP-068nY32_ySeQ9aVmpWzE1A5b6iueZaQNWQQQCKNMFQtKVJAPAR0K7vYQrTBhtunQ&amp;submissionId=3b365f4b-7053-6a17-b69c-1302199d1f33&amp;challengeSource=AgEeA0TtXKdJqwAAAYjYGhfk3IvV8qE-moqKCOU3S98YlUWsWrrOCE_tj-y19vk&amp;challegeType=AgGqfsjPYHB9pgAAAYjYGhfocbqFtAjbOjfOJSayRlhHoDavPzfuDUw&amp;memberId=AgFVDX4Igq3ZOwAAAYjYGhfrJaNQcdhUXQiLM51WqpEexZo&amp;recognizeDevice=AgEXSs5npbYdMgAAAYjYGhfvAZcWLe0XXXdSeeeFWGCsmzhYGfhd">Linkedin</a> and <a href="https://github.com/surajdevopscse">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff5665aec9ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>