<?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 Hamed Rezaee on Medium]]></title>
        <description><![CDATA[Stories by Hamed Rezaee on Medium]]></description>
        <link>https://medium.com/@hamed-rezaee?source=rss-d8e3a8cd7224------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jXtJFek-uUtTp1-yrghQww.jpeg</url>
            <title>Stories by Hamed Rezaee on Medium</title>
            <link>https://medium.com/@hamed-rezaee?source=rss-d8e3a8cd7224------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:43:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamed-rezaee/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[The Observer Pattern: Facilitating Bloc Dependency Management in Dart]]></title>
            <link>https://hamed-rezaee.medium.com/the-observer-pattern-facilitating-bloc-dependency-management-in-dart-db69c19ae541?source=rss-d8e3a8cd7224------2</link>
            <guid isPermaLink="false">https://medium.com/p/db69c19ae541</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[cubit]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Hamed Rezaee]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 04:20:14 GMT</pubDate>
            <atom:updated>2023-07-22T08:32:40.935Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern software development, managing dependencies and communication between different components is essential for building robust and maintainable applications. The <em>Observer Pattern</em> is a powerful design pattern that promotes loose coupling between objects, making it an ideal choice for addressing bloc dependency issues in Dart applications. In this article, we will delve into the <em>Observer Pattern</em> and explore how it can be used to streamline the management of bloc dependencies in the Dart programming language.</p><h3>Understanding the Observer Pattern</h3><p>The <em>Observer Pattern</em> is a behavioral design pattern where an object (known as the <em>subject</em> or <em>observable</em>) maintains a list of its dependents (<em>observers</em>) and notifies them of any state changes. The observers, in turn, are notified automatically when the subject’s state changes, thus ensuring they stay in sync without direct coupling.</p><h4>The Building Blocks of the Observer Pattern</h4><p>Before we dive into how the <em>Observer Pattern</em> can be utilized for bloc dependency management, let’s understand the key components involved:</p><p><strong>Subject (Observable): </strong>The Subject is the component that holds the data or state of interest. It maintains a list of registered observers and provides methods to register, unregister, and notify observers of any changes.</p><p><strong>Observer: </strong>The Observer represents the dependent component that expresses interest in being notified when the state of the subject changes. Observers implement an update method, which the subject calls to notify them of changes.</p><h3>Applying the Observer Pattern to Bloc Dependency Management</h3><p><strong>Bloc (Business Logic Component)</strong> is an architectural pattern that manages the state of an application by dividing it into separate logical units. The <em>Observer Pattern</em> can be effectively used to manage dependencies between different blocs, ensuring they remain decoupled and can communicate without tight coupling.</p><p>Let’s walk through the steps of applying the <em>Observer Pattern</em> to bloc dependency management in Dart:</p><h4>State Listeners: Listening for State Updates</h4><p><em>State Listeners</em> are an essential part of <em>state management</em> They serve as <strong><em>observers </em></strong>that are interested in receiving updates whenever the application state changes. The provided code snippet presents an abstract class called BaseStateListener, which forms the foundation for all state listeners.</p><pre>abstract class BaseStateListener {}</pre><p>As an <em>abstract </em>class, BaseStateListener cannot be directly instantiated. Instead, each state listener in the application should extend this class and define its own methods to handle state updates.</p><p><strong>To create a state listener, follow these steps:</strong></p><ol><li>Create a new class that extends BaseStateListener.</li><li>Implement specific methods within the new class to receive and handle state updates based on the application’s requirements.</li></ol><h4>Dependency Managers: Coordinating State Changes</h4><p>Dependency Managers play a crucial role in managing state changes and ensuring that relevant listeners are informed of these changes.</p><p>The provided code snippet presents an abstract class called BaseDependencyManager which serves as the foundation for all dependency managers.</p><pre>abstract class BaseDependencyManager {<br>  final List&lt;BaseStateListener&gt; _listeners = &lt;BaseStateListener&gt;[];<br><br>  List&lt;BaseStateListener&gt; get listeners =&gt; _listeners;<br><br>  void register(BaseStateListener listener) =&gt; _listeners.add(listener);<br><br>  void unregister(BaseStateListener listener) =&gt; _listeners.remove(listener);<br><br>  void notify(Object? state);<br><br>  void dispose() =&gt; _listeners.clear();<br>}</pre><p>Similar to BaseStateListener, BaseDependencyManager is an abstract class, and developers should extend it to create specific dependency managers tailored to their application&#39;s needs.</p><p>Let’s break down the key components and methods of the BaseDependencyManager class:</p><ol><li><strong>Listeners List:</strong> This private list holds all the registered state listeners that are interested in receiving updates from the dependency manager. It is of type List&lt;BaseStateListener&gt; meaning it can store any class that extends BaseStateListener.</li><li><strong>Registering Listeners:</strong> The register method allows developers to add a state listener to the dependency manager&#39;s list of listeners. When a listener is registered, it becomes part of the <em>observer pattern</em>, and it will receive state updates from the dependency manager.</li><li><strong>Unregistering Listeners:</strong> The unregister method allows developers to remove a state listener from the dependency manager&#39;s list of listeners. When a listener is unregistered, it will no longer receive state updates from the dependency manager.</li><li><strong>Notifying Listeners:</strong> The notify method is abstract, meaning it does not have an implementation in the BaseDependencyManager class. Instead, each specific dependency manager must override this method to define how it will notify its listeners of state changes. The method takes an optional state parameter, which represents the new state that will be sent to the listeners.</li><li><strong>Disposing the Dependency Manager:</strong> The dispose method allows developers to clear the list of listeners when the dependency manager is no longer needed. This helps prevent potential memory leaks and ensures that listeners are not unnecessarily retained.</li></ol><h3>Putting it All Together</h3><p>In a Dart application, developers would create <em>concrete </em>classes that extend both BaseStateListener and BaseDependencyManager. Each <em>concrete </em>state listener would define its own methods to process <em>state </em>updates, while each <em>concrete </em>dependency manager would implement the notify method, sending <strong>state updates</strong> to its <strong>registered listeners</strong>.</p><p>When <em>state </em>changes occur in the application, the corresponding <em>dependency manager</em> is responsible for invoking its notify method, passing the <strong>updated state</strong> as an argument. This, in turn, triggers all registered listeners to receive the updated state and handle it accordingly.</p><p>The combination of <em>State Listeners</em> and <em>Dependency Managers</em> provides a powerful mechanism for maintaining a well-structured and efficient state management system in Dart applications.</p><p>By abstracting these components, developers can easily extend and customize them to fit the specific needs of their projects, promoting code reusability and maintainability.</p><h3>Example</h3><p>In this example, we have three Blocs (BlocA, BlocB, and BlocC) that manage different types of application states. Additionally, we have two Dependency Managers (BlocADependencyManager and BlocBDependencyManager) responsible for notifying the relevant State Listeners when state updates occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDPtlP-SUaQedHImsPkPig.png" /><figcaption><strong>UML Diagram</strong></figcaption></figure><p><strong>“Bloc A” Structure:</strong></p><pre>class BlocA extends Cubit&lt;int&gt; {<br>  BlocA(this.dependencyManager) : super(0);<br><br>  final BaseDependencyManager dependencyManager;<br><br>  void update() {<br>    emit(Random().nextInt(100));<br><br>    print(&#39;$runtimeType update is called: $state&#39;);<br><br>    dependencyManager.notify(state);<br>  }<br>}</pre><pre>abstract class BlocAStateListener implements BaseStateListener {<br>  void updateBlocAListeners({int? state});<br>}</pre><pre>class BlocADependencyManager extends BaseDependencyManager {<br>  @override<br>  void notify(Object? state) =&gt; listeners<br>      .whereType&lt;BlocAStateListener&gt;()<br>      .forEach((BlocAStateListener listener) =&gt;<br>          listener.updateBlocAListeners(state: state as int?));<br>}</pre><p><strong>“Bloc B” Structure:</strong></p><pre>class BlocB extends Cubit&lt;int&gt; implements BlocAStateListener {<br>  BlocB(this.dependencyManager) : super(0);<br><br>  final BaseDependencyManager dependencyManager;<br><br>  void update() {<br>    emit(state + 1);<br><br>    print(&#39;$runtimeType update is called: $state&#39;);<br><br>    dependencyManager.notify(&#39;$state&#39;);<br>  }<br><br>  @override<br>  void updateBlocAListeners({int? state}) {<br>    emit(state!);<br><br>    print(&#39;$runtimeType update is received from BlocAStateListener: $state&#39;);<br>  }<br>}</pre><pre>abstract class BlocBStateListener implements BaseStateListener {<br>  void updateBlocBListeners({String? state});<br>}</pre><pre>class BlocBDependencyManager extends BaseDependencyManager {<br>  @override<br>  void notify(Object? state) =&gt; listeners<br>      .whereType&lt;BlocBStateListener&gt;()<br>      .forEach((BlocBStateListener listener) =&gt;<br>          listener.updateBlocBListeners(state: state as String?));<br>}</pre><p><strong>“Bloc C” Structure:</strong></p><pre>class BlocC extends Cubit&lt;String&gt;<br>    implements BlocAStateListener, BlocBStateListener {<br>  BlocC() : super(&#39;&#39;);<br><br>  @override<br>  void updateBlocAListeners({int? state}) {<br>    emit(&#39;$state&#39;);<br><br>    print(&#39;$runtimeType update is received from BlocAStateListener: $state&#39;);<br>  }<br><br>  @override<br>  void updateBlocBListeners({String? state}) {<br>    emit(state!);<br><br>    print(&#39;$runtimeType update is received from BlocBStateListener: $state&#39;);<br>  }<br>}</pre><p><strong>Main Method:</strong></p><pre>void main() {<br>  final BaseDependencyManager dependencyManagerA = BlocADependencyManager();<br>  final BaseDependencyManager dependencyManagerB = BlocBDependencyManager();<br><br>  final BlocA blocA = BlocA(dependencyManagerA);<br>  final BlocB blocB = BlocB(dependencyManagerB);<br>  final BlocC blocC = BlocC();<br><br>  dependencyManagerA<br>    ..register(blocB)<br>    ..register(blocC);<br><br>  dependencyManagerB.register(blocC);<br><br>  blocA.update();<br>  blocB.update();<br><br>  dependencyManagerA.dispose();<br>  dependencyManagerB.dispose();<br>}</pre><p>The <em>Observer Pattern</em>, like any other design pattern, comes with its set of limitations and benefits.</p><h4><strong>Limitations of the Observer Pattern</strong></h4><ol><li><strong>Overhead:</strong> Implementing the <em>Observer Pattern</em> can add some overhead, especially if there are a large number of observers and frequent state changes. Notifying multiple observers can impact performance, leading to potential bottlenecks.</li><li><strong>Ordering of Notifications:</strong> The order in which observers are notified may not be guaranteed, which could be a concern in certain scenarios where the order matters.</li><li><strong>Debugging Complexity:</strong> As the number of observers and the complexity of interactions increase, debugging and tracing event flows can become challenging.</li><li><strong>No Contextual Information:</strong> The basic <em>Observer Pattern</em> provides limited information to observers when notifying them. Observers may have to retrieve additional context information from the subject if required.</li></ol><h4><strong>Benefits of the Observer Pattern</strong></h4><ol><li><strong>Loose Coupling:</strong> The primary advantage of the <em>Observer Pattern</em> is its ability to promote loose coupling between components. Subjects and observers are decoupled, allowing them to evolve independently without affecting each other.</li><li><strong>Modularity and Scalability:</strong> The pattern enables better code organization by separating concerns into distinct components, making the codebase more modular and easier to scale.</li><li><strong>Extensibility:</strong> New observers can be added without modifying the subject’s code, promoting <em>open-closed principles</em> and enhancing code maintainability.</li><li><strong>Reactivity:</strong> The <em>Observer Pattern</em> facilitates a <strong><em>reactive programming</em></strong><em> </em>style, where changes in one component automatically trigger actions in other dependent components, leading to real-time updates and responsiveness.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db69c19ae541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Dependency Graph for Dart and Flutter Projects]]></title>
            <link>https://hamed-rezaee.medium.com/generating-dependency-graph-for-dart-and-flutter-projects-ae733ec847d1?source=rss-d8e3a8cd7224------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae733ec847d1</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dependency-graph]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Hamed Rezaee]]></dc:creator>
            <pubDate>Thu, 04 May 2023 08:03:52 GMT</pubDate>
            <atom:updated>2023-05-04T08:03:52.721Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Dart </em></strong>is a well-known programming language that is widely used for creating web, mobile, and desktop applications. However, managing class dependencies and maintaining organized and manageable code can be complex, especially in large projects. To overcome this challenge, this article presents a straightforward class that can extract class dependencies in Dart and creates a dependency graph.</p><p>A dependency graph is a visual representation of the relationships between different components of a software system, including classes, modules, and packages. It shows how each component depends on others and how changes in one component can impact others.</p><p>Having a dependency graph can be immensely helpful for developers, particularly in large-scale projects, for several reasons:</p><ol><li><strong><em>Better code organization:</em></strong> By visualizing class dependencies, developers can organize their code in a more structured and logical way.</li><li><strong><em>Easier maintenance:</em></strong> Understanding how different components of the system depend on each other can make it easier to maintain and update the codebase.</li><li><strong><em>Smoother collaboration:</em></strong> A dependency graph can help developers working on different parts of a project understand how their code fits into the overall system.</li><li><strong><em>Efficient troubleshooting:</em></strong> When something goes wrong in the system, a dependency graph can help identify the root cause of the issue by tracing the dependencies.</li></ol><p>Here is how we can implement a simple class to extract the dependency graph:</p><h3>0. Data Structures</h3><p><strong><em>ClassStructureModel</em> </strong>represents a class structure in a Dart source code file, The class has properties that store the class type (concrete or abstract), name, superclass (if any), interfaces (if any), and mixins (if any).</p><pre>class ClassStructureModel {<br>  ClassStructureModel({<br>    required this.type,<br>    required this.name,<br>    this.superClasse,<br>    this.interfaces,<br>    this.mixins,<br>  });<br><br>  final ClassType type;<br>  final String name;<br>  final String? superClasse;<br>  final List&lt;String&gt;? interfaces;<br>  final List&lt;String&gt;? mixins;<br>}</pre><p><strong><em>ClassType </em></strong>is an enumeration that defines two possible class types, concreteClass and abstractClass.</p><pre>enum ClassType {<br>  concreteClass,<br>  abstractClass,<br>}</pre><h3><strong><em>1. Get files in a specific path</em></strong></h3><p><strong><em>getAllFiles </em></strong>method accepts a directory path and returns a list of all the files and subdirectories in the specified directory. The method uses the Directory class from the dart:io library to get a list of all entities in the directory and its subdirectories and returns the list.</p><pre>List&lt;FileSystemEntity&gt; _getAllFiles(String path) =&gt;<br>    Directory(path).listSync(recursive: true);</pre><h3><strong>2. Parse Dart classes</strong></h3><p><strong><em>parseDartFile </em></strong>method accepts a path to a Dart source code file and extracts the class structures from the file using a regular expression. The method reads the file&#39;s content, creates a regular expression object to match the class structures, and iterates over all the matches to extract the relevant information (e.g., class name, superclasses, interfaces, etc.). The method returns a list of ClassStructureModel instances that represent the class structures in the file.</p><pre>List&lt;ClassStructureModel&gt; _parseDartFile(String path) {<br>  final List&lt;ClassStructureModel&gt; result = &lt;ClassStructureModel&gt;[];<br><br>  final String fileContent = File(path).readAsStringSync();<br><br>  final RegExp regex = RegExp(<br>    r&#39;(abstract\s+)?(class|extension)\s+(\w+)\s*(extends\s+([\w&lt;&gt;]+))?(?:\s*with\s+([\w,\s]+))?(?:\s*implements\s+([\w,\s]+))?&#39;,<br>    multiLine: true,<br>  );<br><br>  final Iterable&lt;RegExpMatch&gt; matches = regex.allMatches(fileContent);<br><br>  for (final RegExpMatch match in matches) {<br>    final bool isAbstract = match.group(1) != null;<br>    final String? className = match.group(3);<br>    final String? superClass = match.group(5);<br>    final String? mixins = match.group(6);<br>    final String? interfaces = match.group(7);<br><br>    result.add(<br>      ClassStructureModel(<br>        type: isAbstract ? ClassType.abstractClass : ClassType.concreteClass,<br>        name: className!,<br>        superClasse: superClass,<br>        interfaces:<br>            interfaces?.split(&#39;,&#39;).map((String item) =&gt; item.trim()).toList(),<br>        mixins: mixins?.split(&#39;,&#39;).map((String item) =&gt; item.trim()).toList(),<br>      ),<br>    );<br>  }<br><br>  return result;<br>}</pre><h3>3. Print graph</h3><p><strong><em>printGraph </em></strong>method accepts a list of ClassStructureModel instances and generates a <strong><em>DOT </em></strong>language string representing the class dependencies graph. The method uses a StringBuffer to build the DOT language string by iterating over all the ClassStructureModel instances, adding a node for each class, and connecting nodes that have dependencies (e.g., a subclass and its superclass or interfaces). The method returns the <strong><em>DOT </em></strong>language string.</p><pre>String _printGraph(List&lt;ClassStructureModel&gt; classStructures) {<br>  final StringBuffer buffer = StringBuffer();<br><br>  buffer.writeln(&#39;digraph G {&#39;);<br>  buffer.writeln(&#39;  rankdir=LR;&#39;);<br><br>  for (final ClassStructureModel classStructure in classStructures) {<br>    buffer.writeln(<br>      &#39;  ${classStructure.name} [shape=${classStructure.type == ClassType.abstractClass ? &#39;doubleoctagon&#39; : &#39;rectangle&#39;}];&#39;,<br>    );<br><br>    if (classStructure.superClasse != null) {<br>      buffer.writeln(<br>        &#39;  ${classStructure.name} -&gt; ${classStructure.superClasse};&#39;,<br>      );<br>    }<br><br>    if (classStructure.interfaces != null) {<br>      for (final String interface in classStructure.interfaces!) {<br>        buffer.writeln(<br>          &#39;  ${classStructure.name} -&gt; $interface [style=dashed, arrowhead=empty];&#39;,<br>        );<br>      }<br>    }<br><br>    if (classStructure.mixins != null) {<br>      for (final String mixin in classStructure.mixins!) {<br>        buffer.writeln(<br>          &#39;  ${classStructure.name} -&gt; $mixin [style=dashed, arrowhead=empty];&#39;,<br>        );<br>      }<br>    }<br>  }<br><br>  buffer.writeln(&#39;}&#39;);<br><br>  return &#39;$buffer&#39;;<br>}</pre><h3>4. Generate output</h3><p><strong><em>generateOutput</em></strong> accepts a list of ClassStructureModel instances and generates a DOT file and an image file that represent the class dependencies graph. The method calls the _printGraph method to get the DOT language string writes the string to a DOT file and uses the dot command-line tool to generate a PNG image file from the DOT file.</p><pre>Future&lt;void&gt; _generateOutput(List&lt;ClassStructureModel&gt; projectStructure) async {<br>  File(&#39;dependency_graph.dot&#39;).writeAsStringSync(_printGraph(projectStructure));<br><br>  await Process.run(<br>    &#39;dot&#39;,<br>    &lt;String&gt;[<br>      &#39;-Tpng&#39;,<br>      &#39;dependency_graph.dot&#39;,<br>      &#39;-o&#39;,<br>      &#39;dependency_graph.png&#39;,<br>    ],<br>  );<br>}</pre><p><strong><em>Note:</em></strong> You need to install <a href="https://www.graphviz.org/download/">Graphviz</a> in order to generate output.</p><h3>Full Code Snippet</h3><pre>import &#39;dart:io&#39;;<br><br>void main(List&lt;String&gt; arguments) async {<br>  final List&lt;ClassStructureModel&gt; projectStructure = &lt;ClassStructureModel&gt;[];<br><br>  final String path = arguments.first;<br>  final List&lt;FileSystemEntity&gt; entities = _getAllFiles(path);<br><br>  for (final FileSystemEntity entity in entities) {<br>    if (entity is File &amp;&amp; entity.path.endsWith(&#39;.dart&#39;)) {<br>      projectStructure.addAll(_parseDartFile(entity.path));<br>    }<br>  }<br><br>  await _generateOutput(projectStructure);<br>}<br><br>List&lt;FileSystemEntity&gt; _getAllFiles(String path) =&gt;<br>    Directory(path).listSync(recursive: true);<br><br>List&lt;ClassStructureModel&gt; _parseDartFile(String path) {<br>  final List&lt;ClassStructureModel&gt; result = &lt;ClassStructureModel&gt;[];<br><br>  final String fileContent = File(path).readAsStringSync();<br><br>  final RegExp regex = RegExp(<br>    r&#39;(abstract\s+)?(class|extension)\s+(\w+)\s*(extends\s+([\w&lt;&gt;]+))?(?:\s*with\s+([\w,\s]+))?(?:\s*implements\s+([\w,\s]+))?&#39;,<br>    multiLine: true,<br>  );<br><br>  final Iterable&lt;RegExpMatch&gt; matches = regex.allMatches(fileContent);<br><br>  for (final RegExpMatch match in matches) {<br>    final bool isAbstract = match.group(1) != null;<br>    final String? className = match.group(3);<br>    final String? superClass = match.group(5);<br>    final String? mixins = match.group(6);<br>    final String? interfaces = match.group(7);<br><br>    result.add(<br>      ClassStructureModel(<br>        type: isAbstract ? ClassType.abstractClass : ClassType.concreteClass,<br>        name: className!,<br>        superClasse: superClass,<br>        interfaces:<br>            interfaces?.split(&#39;,&#39;).map((String item) =&gt; item.trim()).toList(),<br>        mixins: mixins?.split(&#39;,&#39;).map((String item) =&gt; item.trim()).toList(),<br>      ),<br>    );<br>  }<br><br>  return result;<br>}<br><br>String _printGraph(List&lt;ClassStructureModel&gt; classStructures) {<br>  final StringBuffer buffer = StringBuffer();<br><br>  buffer.writeln(&#39;digraph G {&#39;);<br>  buffer.writeln(&#39;  rankdir=LR;&#39;);<br><br>  for (final ClassStructureModel classStructure in classStructures) {<br>    buffer.writeln(<br>      &#39;  ${classStructure.name} [shape=${classStructure.type == ClassType.abstractClass ? &#39;doubleoctagon&#39; : &#39;rectangle&#39;}];&#39;,<br>    );<br><br>    if (classStructure.superClasse != null) {<br>      buffer.writeln(<br>        &#39;  ${classStructure.name} -&gt; ${classStructure.superClasse};&#39;,<br>      );<br>    }<br><br>    if (classStructure.interfaces != null) {<br>      for (final String interface in classStructure.interfaces!) {<br>        buffer.writeln(<br>          &#39;  ${classStructure.name} -&gt; $interface [style=dashed, arrowhead=empty];&#39;,<br>        );<br>      }<br>    }<br><br>    if (classStructure.mixins != null) {<br>      for (final String mixin in classStructure.mixins!) {<br>        buffer.writeln(<br>          &#39;  ${classStructure.name} -&gt; $mixin [style=dashed, arrowhead=empty];&#39;,<br>        );<br>      }<br>    }<br>  }<br><br>  buffer.writeln(&#39;}&#39;);<br><br>  return &#39;$buffer&#39;;<br>}<br><br>Future&lt;void&gt; _generateOutput(List&lt;ClassStructureModel&gt; projectStructure) async {<br>  File(&#39;dependency_graph.dot&#39;).writeAsStringSync(_printGraph(projectStructure));<br><br>  await Process.run(<br>    &#39;dot&#39;,<br>    &lt;String&gt;[<br>      &#39;-Tpng&#39;,<br>      &#39;dependency_graph.dot&#39;,<br>      &#39;-o&#39;,<br>      &#39;dependency_graph.png&#39;,<br>    ],<br>  );<br>}<br><br>class ClassStructureModel {<br>  ClassStructureModel({<br>    required this.type,<br>    required this.name,<br>    this.superClasse,<br>    this.interfaces,<br>    this.mixins,<br>  });<br><br>  final ClassType type;<br>  final String name;<br>  final String? superClasse;<br>  final List&lt;String&gt;? interfaces;<br>  final List&lt;String&gt;? mixins;<br><br>  @override<br>  String toString() =&gt;<br>      &#39;name: $name, type: ${type.name}, ${superClasse != null ? &#39;superClass =&gt; $superClasse, &#39; : &#39;&#39;}${interfaces != null ? &#39;interfaces =&gt; $interfaces, &#39; : &#39;&#39;}${mixins != null ? &#39;mixins =&gt; $mixins&#39; : &#39;&#39;}&#39;;<br>}<br><br>enum ClassType {<br>  concreteClass,<br>  abstractClass,<br>}</pre><h3>Sample Output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPyulEWjS1lWxrtLIsST0A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae733ec847d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Binary Search with Interpolation Search in Dart]]></title>
            <link>https://hamed-rezaee.medium.com/improving-binary-search-with-interpolation-search-in-dart-6bbe83e950d9?source=rss-d8e3a8cd7224------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bbe83e950d9</guid>
            <category><![CDATA[interpolation-search]]></category>
            <category><![CDATA[search-algorithm]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Hamed Rezaee]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 10:56:26 GMT</pubDate>
            <atom:updated>2023-07-22T07:11:42.571Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Interpolation Search</em></strong> is a <strong><em>searching algorithm</em></strong> that works on a <strong><em>sorted array</em></strong> of elements. It is an improvement over <strong><em>Binary Search</em></strong>, as it uses the value of the element being searched for to estimate its position in the array, rather than always starting from the middle. This makes it faster for arrays with <strong><em>uniformly distributed</em></strong> values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Mqe459w_VmvcVaxi9COltQ.png" /></figure><p><strong><em>Iterative Approach</em></strong></p><p>The Iterative <strong><em>Interpolation Search</em></strong> algorithm works by calculating the position of the element being searched for using the formula:</p><pre>position = low + ((value - array[low]) * (high - low) ~/ (array[high] - array[low]))</pre><p>Here, low and high are the indices of the first and last elements in the array, respectively, value is the element being searched for, and the array is the sorted array.</p><p>Once the position is calculated, the algorithm checks if the element at that position is equal to the value being searched for. If it is, the algorithm returns the position. If not, it updates low or high based on whether the element at position is greater or less than the value being searched for and repeats the process until the element is found or the array is exhausted.</p><p>Here’s the <strong><em>Dart</em></strong> code for the Iterative <strong><em>Interpolation Search</em></strong> algorithm:</p><pre>int interpolationSearch(List&lt;int&gt; array, int value) {<br>  int low = 0;<br>  int high = array.length - 1;<br>  <br>  while (low &lt;= high &amp;&amp; value &gt;= array[low] &amp;&amp; value &lt;= array[high]) {<br>    int position = low + ((value - array[low]) * (high - low) ~/ (array[high] - array[low]));<br>    <br>    if (array[position] == value) {<br>      return position;<br>    }<br>    <br>    if (array[position] &lt; value) {<br>      low = position + 1;<br>    } else {<br>      high = position - 1;<br>    }<br>  }<br>  <br>  return -1;<br>}</pre><p><strong><em>Recursive Approach</em></strong></p><p>The recursive <strong><em>Interpolation Search</em></strong> algorithm is similar to the Iterative algorithm but uses <strong><em>recursion</em></strong> instead of <strong><em>iteration</em></strong>. It also has an additional base case to handle the situation where the element being searched for is not present in the array.</p><p>Here’s the Dart code for the recursive <strong><em>Interpolation Search</em></strong> algorithm:</p><pre>int recursiveInterpolationSearch(List&lt;int&gt; array, int value, int low, int high) {<br>  if (low &gt; high || value &lt; array[low] || value &gt; array[high]) {<br>    return -1;<br>  }<br>  <br>  int position = low + ((value - array[low]) * (high - low) ~/ (array[high] - array[low]));<br>  <br>  if (array[position] == value) {<br>    return position;<br>  }<br>  <br>  if (array[position] &lt; value) {<br>    return recursiveInterpolationSearch(array, value, position + 1, high);<br>  } else {<br>    return recursiveInterpolationSearch(array, value, low, position - 1);<br>  }<br>}</pre><p><strong><em>Conclusion</em></strong></p><p><strong><em>Interpolation Search</em></strong> is a fast searching algorithm that can be used on sorted arrays with <strong><em>uniformly distributed</em></strong> values.</p><p>The <strong><em>iterative</em></strong> and <strong><em>recursive</em></strong> approaches both have their advantages and can be used depending on the specific requirements of the application.</p><p>By using <strong><em>Interpolation Search</em></strong>, you can improve the performance of your search algorithms and provide a better user experience for your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bbe83e950d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your Dart and Flutter Application’s Performance with Caching and the Strategy Pattern]]></title>
            <link>https://hamed-rezaee.medium.com/boost-your-dart-and-flutter-applications-performance-with-caching-and-the-strategy-pattern-f21ff0b0172?source=rss-d8e3a8cd7224------2</link>
            <guid isPermaLink="false">https://medium.com/p/f21ff0b0172</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Hamed Rezaee]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 14:46:54 GMT</pubDate>
            <atom:updated>2023-07-22T07:14:21.667Z</atom:updated>
            <content:encoded><![CDATA[<p>Caching is a performance optimization technique that involves storing frequently used data in a cache for quick access. The strategy pattern is a design pattern that <em>enables the use of interchangeable algorithms or strategies within an application</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGvjFecTIBp9r5o2RuQHEA.png" /></figure><p>In Dart, we can implement caching using the strategy pattern as follows:</p><ul><li>Define a CacheStrategy interface that includes methods for getting, setting, and clearing cache data.</li></ul><pre>abstract class CacheStrategy&lt;T&gt; {<br>  T? get(String key);<br>  void set(String key, T value);<br>  void clear();<br>}</pre><ul><li>Implement the CacheStrategy interface with concrete caching strategies, such as an in-memory cache or a key-value store cache.</li></ul><pre>class InMemoryCacheStrategy&lt;T&gt; implements CacheStrategy&lt;T&gt; {<br>  final Map&lt;String, T&gt; _cache = {};<br><br>  @override<br>  T? get(String key) =&gt; _cache[key];<br><br>  @override<br>  void set(String key, T value) =&gt; _cache[key] = value;<br><br>  @override<br>  void clear() =&gt; _cache.clear();<br>}<br><br>class KeyValueStoreCacheStrategy&lt;T&gt; implements CacheStrategy&lt;T&gt; {<br>  final KeyValueStore _store;<br><br>  KeyValueStoreCacheStrategy(this._store);<br><br>  @override<br>  T? get(String key) =&gt; _store.get&lt;T&gt;(key);<br><br>  @override<br>  void set(String key, T value) =&gt; _store.set&lt;T&gt;(key, value);<br><br>  @override<br>  void clear() =&gt; _store.clear();<br>}</pre><ul><li>Create a caching service that accepts a CacheStrategy instance and uses it to retrieve or store data.</li></ul><pre>class CacheService&lt;T&gt; {<br>  final CacheStrategy&lt;T&gt; _strategy;<br><br>  CacheService(this._strategy);<br><br>  T? get(String key) =&gt; _strategy.get(key);<br><br>  void set(String key, T value) =&gt; _strategy.set(key, value);<br><br>  void clear() =&gt; _strategy.clear();<br>}</pre><ul><li>Use the caching service in your application, passing in the desired CacheStrategy implementation.</li></ul><pre>final cache = CacheService&lt;int&gt;(InMemoryCacheStrategy());<br>final value = cache.get(&#39;KEY&#39;) ?? expensiveComputation();<br><br>cache.set(&#39;KEY&#39;, value);</pre><p>By using this approach, you can easily swap out caching strategies without modifying the rest of your code. For example, if you decide to switch from an in-memory cache to a key-value store cache, you can simply pass in the appropriate CacheStrategy implementation to the caching service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f21ff0b0172" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing A* Pathfinding in Flutter]]></title>
            <link>https://hamed-rezaee.medium.com/implement-a-algorithm-in-flutter-32220e810c19?source=rss-d8e3a8cd7224------2</link>
            <guid isPermaLink="false">https://medium.com/p/32220e810c19</guid>
            <category><![CDATA[search-algorithm]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[a-star-algorithm]]></category>
            <category><![CDATA[pathfinder]]></category>
            <dc:creator><![CDATA[Hamed Rezaee]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 10:59:11 GMT</pubDate>
            <atom:updated>2020-12-14T19:02:12.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*DYwvRoOOtx3nQEPjEG_-8Q.png" /></figure><p><a href="https://en.wikipedia.org/wiki/A*_search_algorithm">A* (pronounced “A-star”)</a> is a graph traversal and path search algorithm, which is often used in many fields of computer science due to its completeness, optimality, and optimal efficiency.</p><p>I want to explain how to implement this algorithm with flutter.<br>Actually, A* is an improved <a href="https://en.wikipedia.org/wiki/Breadth-first_search">BFS (Breadth-first search)</a> algorithm. you can use a <a href="http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html">heuristic method</a> to help BFS find the solution faster.</p><p>A heuristic method is any approach to problem solving or self-discovery that employs a practical method that is not guaranteed to be optimal, perfect, or rational, but is nevertheless sufficient for reaching an immediate, short-term goal or approximation.</p><p>The heuristic method gives A* an estimate of the minimum cost from any vertex to the goal. In this case, <a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean Distance</a> is used as the heuristic method to help BFS reach the answer faster.</p><p>Pseudocode for the A* algorithm:</p><pre>List&lt;PathElements&gt; <em>queue </em>= [<em>start</em>]<br>PathElements <em>current </em>= <em>queue</em>.remove()</pre><pre><strong>while </strong><em>current</em> <strong>is</strong> <strong>not equal </strong><em>goal</em><br><strong>    for each </strong><em>adjacen </em><strong>of </strong><em>current</em><br>        <strong>if </strong><em>adjacen </em><strong>is not </strong>visited<br>            <em>queue</em>.add(adjacen)</pre><pre><em>            adjacen</em>.visited = true<br>            <em>adjacen</em>.parents.add(<em>current</em>)<br>            <em>adjacen</em>.g = min(g, <em>current</em>.g + <em>adjacen</em>.cost)<br>            <em>adjacen</em>.h = calculateHeuristic(<em>adjacen, goal</em>)</pre><pre><em>current </em>= <em>queue</em>.remove()  // remove item with lowest g + h from queue</pre><p>Pseudocode for calculating Heuristic value using Euclidean Distance:</p><pre>calculateHeuristic(<em>adjacen</em>, <em>goal</em>)<br>    sqrt((<em>adjacen</em>.row - <em>goal</em>.row)^2 + (<em>adjacen</em>.column - <em>goal</em>.column)^2)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5S8F6LfZX1jGxKe3rv%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2F5S8F6LfZX1jGxKe3rv&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2F5S8F6LfZX1jGxKe3rv%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="550" frameborder="0" scrolling="no"><a href="https://medium.com/media/6be1f891aaf55945889ca25416375f73/href">https://medium.com/media/6be1f891aaf55945889ca25416375f73/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fk2RxqECvelD3PLOnAW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fk2RxqECvelD3PLOnAW&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fk2RxqECvelD3PLOnAW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="550" frameborder="0" scrolling="no"><a href="https://medium.com/media/f70eb397b6a720e688e1bdba3688b384/href">https://medium.com/media/f70eb397b6a720e688e1bdba3688b384/href</a></iframe><p>First of all, we need a class to hold coordinate for each element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6840414285f59a5867599cbfc80574f8/href">https://medium.com/media/6840414285f59a5867599cbfc80574f8/href</a></iframe><p>Then we need a class to represent information for each element in the grid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a45848669d5726d151724b1e55cd5fa/href">https://medium.com/media/4a45848669d5726d151724b1e55cd5fa/href</a></iframe><p>In this class g is responsible to keep all cost from the start point to the current point, andh keeps value that will be calculated by the heuristic method.</p><p>cost is the cost of reach to the current element. For example, the cost of a straight move is 1.0, and const of a diagonal move is 1.3.</p><p>The value of passable shows if you can cross from this element or not, flag visited indicates if you have seen this element before in search or not.</p><p>We will use inPath when we want to show the optimal path from start to thegoal.</p><p>Finally the parents property keeps parents of the current element. We need to store them for backtracking.</p><p>After adding the base model classes, we need a grid to visualize our process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39390acf573d88474ec3c94e5f877b01/href">https://medium.com/media/39390acf573d88474ec3c94e5f877b01/href</a></iframe><p>Also, we need some button to set start, set goal, reset grid, and run pathfinder algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c7fe164e4f1d67c9b212ae1ee881b13/href">https://medium.com/media/2c7fe164e4f1d67c9b212ae1ee881b13/href</a></iframe><p>Here is the main method for pathfinder, you can pass false as the argument to perform regular BFS algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a990158ed654bff3333fd1885372eb2/href">https://medium.com/media/7a990158ed654bff3333fd1885372eb2/href</a></iframe><p>And finally, the GitHub repository for the project…</p><p><a href="https://github.com/hamed-rezaee/flutter_path_finder">hamed-rezaee/flutter_path_finder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32220e810c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>