<?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 Bharath on Medium]]></title>
        <description><![CDATA[Stories by Bharath on Medium]]></description>
        <link>https://medium.com/@bharath-dev?source=rss-a78bd0833de8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XXphAnwRhWOusAaNYGIwuA.jpeg</url>
            <title>Stories by Bharath on Medium</title>
            <link>https://medium.com/@bharath-dev?source=rss-a78bd0833de8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 22:47:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bharath-dev/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[Flutter Bloc-Don’t prefer single state class.]]></title>
            <link>https://bharath-dev.medium.com/flutter-bloc-dont-follow-its-docs-as-it-is-40bf60be38c8?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/40bf60be38c8</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 04:27:11 GMT</pubDate>
            <atom:updated>2023-09-18T13:21:29.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*jz8usNf4VsuCre99rzhdIg.png" /></figure><p>Everyone in the Flutter community knows <a href="https://pub.dev/packages/flutter_bloc">Bloc</a> is one of the leading state management techniques used in Flutter. I’ve been using Bloc for almost 5 years now. So I’ve gone through a lot of different use cases for using Bloc.</p><p>In the example projects provided with the Bloc package, lots of projects are usingSingle-State class to manage states. In this article, I want to talk about why we need to avoid using Single State Class where multiple states are possible.</p><p>In case you are wondering, this is how a Single-State class looks like</p><pre>class SendEmailState {<br>  final Email? email;<br>  final bool isLoading;<br>  final String? failureMessage;<br>  final dynamic? exception;<br><br>  SendEmailState({<br>    this.email,<br>    this.isLoading = false,<br>    this.failureMessage,<br>    this.exception,<br>  });<br>}</pre><p>First, let’s start with some basic questions,</p><h3>What is a state?</h3><p>A state is a thing that changes over the lifetime of the app or a page or a group of widgets or even a single widget.</p><p>For example, let’s consider sending an email. We have 4 states in sending an email.</p><ol><li>Initial (User not yet pressed the send button)</li><li>Sending (Email is being sent to the server)</li><li>Succeed (Email successfully sent)</li><li>Failed (Failed to send)</li></ol><p><strong>We need to understand that at any point in time, the state of sending an email could only be one of these 4 states. It cannot be at </strong><strong>Sending and </strong><strong>Failed state at the same time.</strong></p><h4>What is state management then?</h4><p>State management is nothing but the logic to update the current state based on some action. The action could be anything like</p><ul><li>A user pressing a button</li><li>Receiving a notification</li><li>System state change (eg: Screen orientation)</li><li>App state change (eg: Login state changes User state)</li><li>Backend stream</li></ul><h4>How does Bloc/Cubit manage the state?</h4><p>Bloc works with streams as its core. Bloc is connected to 2 streams. Event stream and State stream. The event stream is used to carry and deliver events triggered by some action to Bloc. Bloc maps the event to a function that holds some logic which yields a new state into the State stream. State stream is used to broadcast the current state to its listeners. Then the listeners react based on the state change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YpGipv_J6-BhCOfRxIwGA.png" /></figure><p>The difference between Bloc and Cubit is that Cubit doesn’t have an event stream. This means the action instead of generating an event, directly calls bloc methods that hold logic which yields state to State stream. And then the flow is the same as the bloc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBj93X3fV72ek9riubYk4Q.png" /></figure><p>Let’s see the Email sending state management example in code using Cubit as the state manager.</p><p>We can represent the state change in 2 ways.</p><ol><li><strong>Each object type represents a different state. (</strong><strong>Multi-Class states)</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b8dccdef50efc3aff412d582622d98/href">https://medium.com/media/63b8dccdef50efc3aff412d582622d98/href</a></iframe><p>2. <strong>A single object having multiple nullable parameters belongs to one or many states. (</strong><strong>Single-Class states)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5b019cb73270dc05f896038d999bd44/href">https://medium.com/media/f5b019cb73270dc05f896038d999bd44/href</a></iframe><p>And these are their respective cubit codes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ec154f07c292730f47d49b9968ffeb4/href">https://medium.com/media/1ec154f07c292730f47d49b9968ffeb4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4de37f19fddda6af69d7c658bcf5583/href">https://medium.com/media/d4de37f19fddda6af69d7c658bcf5583/href</a></iframe><p>Let’s see the side-by-side comparison of state code to understand a bit more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF645M0dVCZgC9lZSylM1w.png" /></figure><p>We all know <strong>the whole point of state management is that we need to be certain of the current state of the thing that could have multiple states</strong>.</p><ul><li>The first thing we could understand from the right side code is that we could not understand the different states this could have 😂. We can only guess the state with the combination of parameters. For that, we need to check all the existing yielded state combinations to be certain that our new combination will work for sure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3RizBwthyGLdEcCRLC9Bg.png" /></figure><ul><li>But on the left side code, we can easily understand the state types with class type.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGYpRRIhE7Qk2A6cmdbfGg.png" /></figure><ul><li>On the right side code, we can see the object Email is declared nullable final Email? email;. This means that even though the email was sent successfully, we cannot access the email object without a null check. However on the left side code, if the state is SucceedState we can be sure that it holds an Email object final Email email;. The same thing happens with the failure case. Even though it failed, we cannot be certain that this holds the failureMessage and exception params.</li><li>Worse than that, even though the email was sent successfully, the right-side code could hold email as well as failureMessage params and even the compiler won’t complain. Logically how could an email-sending state be both a success and a failure state at the same time? Please don’t talk about Quantum Physics here 😂. Now, from the State-listener’s perspective, how could we be certain of which param should be trusted? Should we show a failure message or a success message to the user?</li><li>Also, note that some states could need multiple parameters. Here we need failureMessage and exception params in case of a failure. The compiler won’t complain even though we left a param on the right side code. But on the left side code, if we left something, the compiler won’t let us run the code. We can be certain that if it failed, we can access both failureMessage and exception with certainty.</li><li>If you are a new developer on the team, <strong>how could you know what are the parameters that need to be updated for a state change</strong> with the right side code? We could accidentally create a new combination like having both email and failureMessage. In this case, there are 4 variables of which 3 are nullable and 1 is boolean. So there should be 2^n combinations. So here we have <strong>16 combinations of params</strong>. Now think of having more parameters. We might not be handled all the combinations on the listeners. This could break the code. And it will be harder to debug based on the number of combinations. However, on the left side code, anyone <strong>can be certain that there are only 4 possible states(combinations)</strong>. And even a newbie can be certain that we just need to hold email if it is a success case or we just need to hold failureMessage and exception in case of failure.</li><li>Let’s say we have email as null with a success state on the right-side code. We only get the runtime error at the time of using the email param which too not at the yielded state source. It shows at the place where we used it. Then we need to backtrack to the code and find out the source to fix. In the case of left-side code, the compiler will not even give a chance to emit the email as null.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_i_4fJhoLRdoo9b8sa1rQ.png" /></figure><p>As we can see from this cubit comparison, we are emitting the state object with different parameter configurations on Single-Class state. But on the Multi-Class state, we are emitting different objects which makes it more clear.</p><p>You could argue why someone will ever write a code that has both email and failureMessage params together? That’s a good question. I believe this question is very similar to the question Why do we need Java if Javascript is that simple? and the simple answer is that we programmers are humans which means we are dumb 😂 and we make many mistakes. <strong>After all the most important point of having a programming language with a strong type system is to reduce human error right?</strong> If you are still not satisfied I’m sure you all know Murphy’s law Anything that can go wrong will go wrong. Don’t you think, the simple possibility of the Email param can be nullable itself is frightening?</p><p>Now let’s compare the flow diagram between Multi-Class states and Single-Class states to make it more obvious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCvUsE4eZLPAgsn7FVUluQ.png" /></figure><p>As we can see from the flow diagram, by using Single-Class state option,</p><ul><li>We are just <strong>deligating the current state-deciding logic to the UI</strong>. Feels like a big RED Flag, isn’t it?</li><li>If UI is the one deciding the current state, then <strong>what is the whole point of having separate logic from UI for state management</strong>?</li><li>The worse part is we need to repeat this state deciding logic wherever we are using this state. So if we need to add one more state in the future, we need to make changes everywhere. Huge RED Flag.</li><li>Yes, we could solve this issue by adding a enum parameter to the state object. But this just solves this single problem. All the other problems I mentioned will still exist.</li></ul><p>If we use Multi-Class states option, the UI just needs to reflect based on the current state.</p><p>Now <strong>what if we need multiple params at the same time</strong>? I’ve seen lots of people doing this same mistake while using <strong>pagination</strong>. If we are implementing pagination, we need to show the loading indicator at the bottom with the existing list at the top.</p><p>Let’s start with the worst implementation for obvious reasons mentioned throughout this article.</p><pre>class NewsFeedState {<br>  final List&lt;News&gt;? news;<br>  final bool isLoading;<br>  final bool isPaginating; // &lt;-- true if paginating.<br>  final String? failureMessage;<br>  final dynamic? exception;<br><br>  NewsFeedState(this.news, this.isLoading, this.isPaginating, this.failureMessage, this.exception);<br>}</pre><p>We could just add isLoading parameter to the SucceedState like</p><pre>sealed class NewsFeedState {}<br><br>final class InitialState implements NewsFeedState {}<br><br>final class SendingState implements NewsFeedState {}<br><br>final class SucceedState implements NewsFeedState {<br>  final List&lt;News&gt; news;<br>  final bool isLoading; // &lt;-- true if paginating.<br><br>  SucceedState(this.news, this.isLoading);<br>}<br><br>final class FailedState implements SendEmailState {<br>  final String failureMessage;<br>  final dynamic exception;<br><br>  FailedState(this.failureMessage, this.exception);<br>}</pre><p>But if we think about it, we are letting the UI decide whether this is Succeed without pagination or Succeed with pagination instead of having this logic in the cubit. And we need to understand, Succeed with pagination is just a subset of the succeed state. So the best approach is to extend the Succeed state like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edbb903ba95f77acace4674f4f61e312/href">https://medium.com/media/edbb903ba95f77acace4674f4f61e312/href</a></iframe><p>I hope I delivered some of the important points to think about before selecting the right approach. Of-course <strong>Single-Class State logic feels easy to implement at first but only at the cost of suffering for it later.</strong> After all, this is the exact reason why we need <strong>Inheritance</strong> right?</p><p>Now if you ask me why Bloc team used this kind of solutions in some of its example projects, I can’t think of any point other than they don’t want to scare newbie developers with this Inheritance given that Bloc already using Stream while other popular state management solutions like <a href="https://pub.dev/packages/provider">Provider</a> is very easy to start with.</p><p>I still believe that programming is one of the easiest and best jobs to exist. We just need to write code not only expecting the result but also by thinking of our future selves, because we are the ones who are going to read and update the code. All we need to do is write code for our future selves as straightforward as possible.</p><p>The only reason I could come up with for using Single-Class state is because of lots of boilerplates in Multi-Class states. For that sole reason, <strong>I&#39;ve published a Wrapper package for Bloc called bloc_ease that could help us write Bloc/Cubit without we need to handle states (most cases). Also, we don’t even need to handle all the states in the UI. This could reduce more than 60% of boilerplates. </strong>Sounds fascinating right? Check out this package <a href="https://pub.dev/packages/bloc_ease">bloc_ease</a>.</p><p><a href="https://pub.dev/packages/bloc_ease">bloc_ease | Flutter Package</a></p><p>Connect with me for doubts and updates.</p><p><a href="https://linktr.ee/bharath.dev">Bharath | Twitter, Instagram | Linktree</a></p><figure><a href="https://www.buymeacoffee.com/bharath213"><img alt="" src="https://cdn-images-1.medium.com/max/261/1*CUbZDnk6jN2lLseiNqU4gQ.png" /></a></figure><p>Thanks for your time. Happy coding! 💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40bf60be38c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Unit Testing — The Beginner’s Guide]]></title>
            <link>https://medium.com/better-programming/flutter-unit-testing-the-beginners-guide-35105164722e?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/35105164722e</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 16:40:40 GMT</pubDate>
            <atom:updated>2023-08-31T12:24:07.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Unit Testing — The Beginner’s Guide</h3><h4>Unit testing is a part of the automated testing process in which small units of code are tested</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTFKOYXlcFWo0wbhzEFsWQ.png" /></figure><p>Hello everyone. In this article, we are gonna learn all about unit testing in Flutter and Dart.</p><h4>Agenda</h4><ul><li><a href="#55ba">What is automated testing?</a></li><li><a href="#22c2">What is unit testing?</a></li><li><a href="#5d26">Why do we need to test?</a></li><li><a href="#bab2">What can we test in a unit?</a></li><li><a href="#e992">How to do unit testing in Dart?</a></li><li><a href="#5879">Good unit testing practices</a></li><li><a href="#e0a5">Mocking</a></li><li><a href="#a1e6">Different ways to mock</a></li><li><a href="#61f7">Mockito</a></li><li><a href="#8c58">MockTail</a></li></ul><h3>What is Automated Testing?</h3><p>Software automated testing is the process of evaluating and verifying if the software product or application does what it is supposed to do. It prevents bugs and reduces the development cost.</p><p>First, we need to understand something. Automated testing is just a way to prevent the software from expected bugs. It doesn’t mean the software does not have any bugs. It just means the software does not have any expected bugs.</p><blockquote>“Testing shows the presence, not the absence of bugs.”<em> —</em> Edsger Dijkstra</blockquote><p>The cycle always goes like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*LQQFptO0cmT-SA7Y_HIgdw.png" /></figure><p>As we can see, after the development phase, we write expected test cases (TDD is an exception). Once it passes all the test cases, we usually ship the software. While the software is in production, if any bug raises, we fix it and write the test cases to prevent the software from the same bug in the future.</p><p>Testing is just the act of verification. Under the development of a new feature or fixing an existing bug, test cases help us verify if all the existing features and units work as expected. It makes sure the current development doesn’t break any existing features.</p><h3>What is Unit Testing?</h3><p>Unit testing is a part of the automated testing process in which small units of code are tested with several use cases for their reliability. A unit may be a function, method, class, state, or just a variable.</p><p>Unit testing is the bottom-most layer in the test suite. In this layer, we test the internal working of every feature.</p><p>A unit test has three phases:</p><ul><li>Arrange</li><li>Act</li><li>Assert</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*fP4Eby_XQcAsYyloEyWG0A.png" /></figure><p>In the Arrange phase, we just need to create the object of the unit that we need to test and prepare the prerequisites for our test, i.e., set up the state variable, set up mocks, etc. The Arrange phase may or may not exist based on the need.</p><p>In the Act phase, we run the unit with some state(passing arguments) and store the result if any.</p><p>In the Assert phase, we verify whether the unit behaves as expected. We may expect a method to be called or the result to be the same as the expected result.</p><p><em>The Arrange and Act phase are not compulsory.</em></p><h4>Why do we need to unit test?</h4><ul><li>Unit testing is very easy to write and run. Thus saves a lot of time.</li><li>Unit testing helps us identify bugs at the early stage. Thus saves a lot of time and money.</li><li>Since we write all the expected cases of the unit, anyone can understand what that unit is all about. Thus acts as better documentation.</li><li>Often we won’t refactor our code by thinking, doing so might break the unit. Having unit tests gives us the confidence to refactor our code.</li><li>Debugging is simple. Since we exactly know the cases that are failing, we can pinpoint the exact unit that causes the bug.</li><li>By looking at the test cases, we can easily understand what the unit is all about. Thus long-term maintenance is easier.</li></ul><h4>What can we test in a unit?</h4><p>In order to have a good unit test suite, we need to understand what we need to test in a unit.</p><p>Usually, unit testing is based on these aspects:</p><ul><li>State variables</li><li>Function/variable calls</li><li>Function arguments</li><li>Function returns</li></ul><p><em>State variables are variables outside the local scope. It may be a global variable or a class property that can be accessed by more than one unit. Usually, it holds a state.</em></p><p>Here are some of the cases we need to look for in a unit:</p><ul><li>Verify the constant or final variable’s value.</li><li>Initial values of state variables.</li><li>Verify if the unit calls certain function 1…n times.</li><li>Verify if the unit never calls certain function.</li><li>Make sure the state variables are updated as expected.</li><li>The result of the unit is same as the expected.</li><li>If there is a string, list, or any other complex DS involved, make sure to check empty cases, especially if we traverse through the DS.</li><li>Check for null cases (Only for nullable types. Dart is null safe now)</li><li>Check the type of the variable or argument (Don’t need to if we utilize Dart’s type system well)</li></ul><p><em>Dart’s null safety and type system save a lot of test cases in all scenario.</em></p><h3>How To Do Unit Testing in Dart?</h3><ul><li>First, we need to include the dependency in the pubspec.yaml file.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9453e02ad4e683e5510b16b4468864/href">https://medium.com/media/ea9453e02ad4e683e5510b16b4468864/href</a></iframe><ul><li>Create a dart test file with the _test suffix. It helps the dart analyzer to treat the file as a test file.</li></ul><p>We are gonna test the area of the circle.</p><pre>sample_project/<br>  lib/<br>    area.dart<br>    main.dart<br>  test/<br>    area_test.dart</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/543d48365c0edc2736a4c72e5c423d03/href">https://medium.com/media/543d48365c0edc2736a4c72e5c423d03/href</a></iframe><p>Here is the Dart test file. Every test file should have a main() method in which the execution starts.</p><p>We need to wrap our test case inside a function and pass the function to the test() method as an argument along with a proper description of the test case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a134b99e0e0d89da9167f81d1952903/href">https://medium.com/media/4a134b99e0e0d89da9167f81d1952903/href</a></iframe><p>This test expects the area of the circle to be 3.141592 when the radius is 1. Here the unit is the circle() method.</p><ul><li>In the Arrange(setup) phase, we created an instance for the Area class.</li><li>In the Act(run) phase, we ran the unit we wanted to test with some input.</li><li>In the Assert(verify) phase, we compared the result with the expected result.</li></ul><p>Here is one more test that just verifies the value of the getter pi:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c3ef2eae8d9c1fe8a9659cad202f1f/href">https://medium.com/media/35c3ef2eae8d9c1fe8a9659cad202f1f/href</a></iframe><p>Here we can see that arrange and act phases are not present. Since pi is a static getter, we don’t need to set up or run anything. But we need to verify it, thus only the assert phase.</p><h4>Grouping the test cases</h4><p>Often, we need to write many similar test cases. The group() method helps us group similar test cases for easy management.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f544aff71d4b4e9e500077b994a90b4/href">https://medium.com/media/4f544aff71d4b4e9e500077b994a90b4/href</a></iframe><p>Everything is fine but we created the Area instance for each test. As the test cases grow, we need to repeat this same step for every test case. It is not a good practice.</p><p>The setUpApp() method runs first before all the test cases. Using this we can reduce the repetition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72f10ba67b3cf98a23ffb2c026ce3ab6/href">https://medium.com/media/72f10ba67b3cf98a23ffb2c026ce3ab6/href</a></iframe><p>As we can see, I moved the declaration and initialization to this main method’s scope. Thus, it runs first and then runs all the test cases, i.e., it uses the same instance to all the test cases. If the object doesn&#39;t hold any state, it won’t be a problem.</p><p>If the object holds a state, then having a common instance for all the states might end up giving many problems. Thus we need separate instances for every test case.</p><p><em>It is a bad practice to have a common state among many test cases.</em></p><p><em>We need to have separate state for every test case. We usually inject the initial state for every test. That is one of the works we need to do in the Arrange phase.</em></p><p>The setUp() method is similar to the setUpAll() method but the difference is that it runs every time before a test case in the current scope. Thus every test case gets its own state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed636381ba01db7aa79bd65d29631c4c/href">https://medium.com/media/ed636381ba01db7aa79bd65d29631c4c/href</a></iframe><p>Here, setUp() method runs before each test case. Thus having separate instances for each test. Thus no state issues.</p><p><em>Always prefer the </em><em>setUp() method over the </em><em>setUpAll() method unless the callback is slow.</em></p><p>The tearDownAll() method can be used to run something after all the tests in the current scope are completed. Similarly, the tearDown() method is used to run something after every test case. Usually used to dispose instances or cancel the subscription.</p><p><em>setUp(),</em><em> setUpAll(), </em><em>tearDown(), and </em><em>tearDownAll() can be used inside the </em><em>group() to limit the scope.</em></p><h4>Good Unit Testing Practices</h4><ul><li>Unit tests should be fast</li><li>Unit tests should be simple</li><li>Unit tests should be deterministic</li><li>Unit tests should be focused</li><li>Code repetition is OK in unit tests</li><li>Test description should be easily understandable</li></ul><p>Unit tests should be fast. Our entire unit test suite should be able to run within a couple of minutes so that we will run the test suite ourselves in the development phase. This helps in fixing bugs early. If it takes longer, then we usually throw that work into some kind of pipeline.</p><p>Unit tests should be simple. When we go through a unit test case, all we need to know should be inside that test case. We don’t want to scroll around the code to understand a single test case. Unit test should be self-explanatory.</p><p>Unit tests should be deterministic. A unit test should behave exactly as before wherever or whenever it is been tested without altering the source code. Unit test should not depend on any external factors such as Current-Time, database, web, native API, etc. We usually mock those out.</p><p>Unit tests should be focused. A unit test should focus only on a single unit. We should not test the dependencies inside the unit test.</p><p>Code repetition is OK in unit tests. A unit test should focus more on simplicity rather than good coding practices. Anyone should understand the test case without searching for its dependencies or the current state of the unit. So, it is OK to repeat some parts of code if it improves easy understanding and simplicity.</p><p>Unit test description should be easily understandable. A good description must contain four parts:</p><ul><li>The unit we are gonna test</li><li>The current state of the unit</li><li>The input we are going to give</li><li>The response we are expecting</li></ul><p>In this test description, “area of the circle with radius 1 should be 3.141592,” we can break it apart like the following:</p><ul><li>“Area of the circle” is the unit we are gonna test</li><li>“Radius 1&quot; is the input we are going to use</li><li>“3.141592” is the output we are expecting</li></ul><p>This unit doesn’t have any state.</p><h3>Mocking</h3><p>The main idea behind unit testing is to isolate and focus on the current unit we are testing and not on the behavior of external dependencies. But in most cases, we need to depend on external dependencies like DB, web servers, platform API, external devices, etc.</p><p>Let’s assume that our current unit depends on a web API. The test works slowly but fine when the server is live. But when is server is offline, the unit test fails. This makes the unit test unpredictable. Because the web server won’t be in our control. It is not our fault when the web server goes down. This is where mocking comes in.</p><p><em>Mocking is just the process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested but not on the behaviour of external dependencies.</em></p><p>Let’s see an example.</p><p>We are gonna test this fetch() method in the repository class. As we can see, our unit depends on RemoteDataSource’s fetch() method which communicates with the web API, which is an external dependency. So, we need to stub the fetch() method from RemoteDataSource.</p><p><em>Stubbing refers to changing the behavior of some part of the unit without affecting anything else.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a83fde84e84b16f9e94618d5919f9b8f/href">https://medium.com/media/a83fde84e84b16f9e94618d5919f9b8f/href</a></iframe><p>There are some ways with which we could mock.</p><h4>Implementing the class we need to mock</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/326709ecb7b2e59d7ad925a8b38502aa/href">https://medium.com/media/326709ecb7b2e59d7ad925a8b38502aa/href</a></iframe><p>Here we have implemented the RemoteDateSource class on two mock classes. MockRemoteDateSourceSuccess which mocks the success case and MockRemoteDateSourceFailure which mocks the failure case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdf8b4402b2a24478623edf6aab519d7/href">https://medium.com/media/fdf8b4402b2a24478623edf6aab519d7/href</a></iframe><p>While writing test cases, we can choose what kind of implementation we need based on the test.</p><ul><li>In the first test, I used the MockRemoteDateSourceSuccess instance that mimics the success case and verified the result is an instance of Student.</li><li>In the second test, I used the MockRemoteDateSourceFailure instance that mimics the failure case and verified the method call throws an exception.</li></ul><h4>Extending an abstract class we need to mock</h4><p>This is similar to the previous method. The only difference is that, rather than implementing a concrete class, we just extend an abstract class that the concrete class is extending.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e24c3d9d9975c5b9a14fd692db4cdad0/href">https://medium.com/media/e24c3d9d9975c5b9a14fd692db4cdad0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def6216a0f2f3fb96ef1d2fd2febda12/href">https://medium.com/media/def6216a0f2f3fb96ef1d2fd2febda12/href</a></iframe><p>This helps in reducing some unnecessary implementation from a concrete class.</p><p>But both these techniques have two problems.</p><ul><li>They lack simplicity since we need to move to the mock code to know about its implementation details.</li><li>Also, we need to have separate mock classes for all the test cases. Some part of code repetition is acceptable for unit tests. But this much code repetition is hard to maintain.</li></ul><p>This is where mocking packages come into play.</p><h4><a href="https://pub.dev/packages/mockito">Mockito</a> — Mock library for Dart</h4><p>This package solves both of these problems. The idea behind the Mockito library is that we just need to use @GenerateMocks() annotation to pass on the classes we need to mock. It generates the mock class for us with the help of the <a href="https://pub.dev/packages/build_runner">build_runner</a> package (Don’t forget to include build_runner as the dev_dependency).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a91cb7b080d02a9aabcbd6cd8d077c0/href">https://medium.com/media/7a91cb7b080d02a9aabcbd6cd8d077c0/href</a></iframe><p>Here we did the stubbing part using the when() method from Mockito.</p><p>Don’t forget to generate the mock classes.</p><pre>dart run build_runner build --delete-conflicting-outputs</pre><p>build_runner will generate a file with a name based on the file containing the @GenerateMocks annotation. Here, in the repository_test.dart example, we import the generated library as repository_test.mocks.dart.</p><ul><li>We don’t need to move anywhere to see the implementation logic. Everything would be right there.</li><li>Generation of the mock class is done by mockito, thus, it is easy to maintain.</li></ul><p>We can just concentrate on stub, act, and assert. That’s it.</p><p>The only problem with Mockito is the code generation. We can overcome it with MockTail.</p><h4><a href="https://pub.dev/packages/mocktail">MockTail</a> — Without Code Generation</h4><p>Mocktail focuses on providing a familiar, simple API for creating mocks in Dart (with null safety) without the need for manual mocks or code generation.</p><p>This library is written by <a href="https://medium.com/u/bd78eebef416">Felix Angelov</a>, the same person who wrote <a href="https://pub.dev/packages/bloc">bloc</a>, <a href="https://pub.dev/packages/equatable">equatable</a>, etc. This library even has 100% code coverage like other packages he wrote.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b10ee263deee5166b014e841ba236ef/href">https://medium.com/media/1b10ee263deee5166b014e841ba236ef/href</a></iframe><p>That’s it. No annotation and no code generation. Just a single line.</p><pre>class MockRemoteDataSource extends Mock implements RemoteDateSource{}</pre><p>Well done, folks! You’re ready for unit testing.</p><p>I hope you enjoyed this article.</p><p>Connect with me</p><p><a href="https://linktr.ee/bharath.dev">Bharath | Twitter, Instagram | Linktree</a></p><figure><a href="https://www.buymeacoffee.com/bharath213"><img alt="" src="https://cdn-images-1.medium.com/max/261/1*CUbZDnk6jN2lLseiNqU4gQ.png" /></a></figure><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35105164722e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/flutter-unit-testing-the-beginners-guide-35105164722e">Flutter Unit Testing — The Beginner’s Guide</a> was originally published in <a href="https://betterprogramming.pub">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Clean Architecture — Beginner’s Guide]]></title>
            <link>https://medium.com/better-programming/the-clean-architecture-beginners-guide-e4b7058c1165?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b7058c1165</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 12:52:00 GMT</pubDate>
            <atom:updated>2023-08-31T12:09:36.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Clean Architecture — Beginner’s Guide</h3><h4>As explained with visual illustrations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2vJLKG_C3AxLLJWy4YP0w.png" /><figcaption>Source: <a href="https://undraw.co/">Undraw</a></figcaption></figure><p><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">The Clean Architecture</a> is the system architecture guideline proposed by Robert C. Martin (Uncle Bob) derived from many architectural guidelines like Hexagonal Architecture, Onion Architecture, etc... over the years.</p><p>This is one of the guidelines adhered to by software engineers to build scalable, testable, and maintainable software.</p><h4>Why do we need to architect?</h4><p>“The goal of software architecture is to minimize the human resources required to build and maintain the required system.” <em>― Robert C. Martin, Clean Architecture</em></p><h3>Advantages of Proper Architecture</h3><ul><li>Testable</li><li>Maintainable</li><li>Changeable</li><li>Easy to Develop</li><li>Easy to Deploy</li><li>Independent</li></ul><h3>The Clean Architecture</h3><p>Here’s the clean architecture illustration created by Robert Martin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0u-ekVHFu7Om7Z-VTwFHvg.png" /><figcaption>Image by <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Robert C. Martin</a></figcaption></figure><p>We can see there are four layers in the diagram. Blue layer, Green layer, Red layer, and Yellow layer.</p><p>Each circle represents different areas of the software. The outermost layer is the lowest level of the software and as we move in deeper, the level will be higher. In general, as we move in deeper, the layer is less prone to change.</p><h3><strong>The Dependency Rule</strong></h3><p>The Dependency Rule states that the source code dependencies can only point inwards.</p><p>This means nothing in an inner circle can know anything at all about something in an outer circle. i.e. the inner circle shouldn’t depend on anything in the outer circle. The Black arrows represented in the diagram show the dependency rule.</p><p>This is the important rule that makes this architecture work. Also, this is hard to understand. So I’m gonna break this rule at first to let you understand what problems it brings and then explain and let’s see how to keep up with this rule. So please bear with me.</p><p>First of all, this circular representation might be confusing for many. So let&#39;s try to represent it vertically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*COOl75XSL1xbo6Tv60D6qA.png" /><figcaption>Image by author</figcaption></figure><p>The colors represented here are the same as the colors represented in the clean architecture diagram.</p><p>Remember, the arrow should be read as “depend on”. i.e. Frameworks and Drivers should depend on Interface Adapters, which depend on Application Business Rules which depend on Enterprise Business Rules.</p><p>Nothing in the bottom layer should depend on the top layer.</p><h4>Frameworks and Drivers</h4><p>Software areas that reside inside this layer are</p><ul><li>User Interface</li><li>Database</li><li>External Interfaces (eg: Native platform API)</li><li>Web (eg: Network Request)</li><li>Devices (eg: Printers and Scanners)</li></ul><h4>Interface Adapters</h4><p>This layer holds</p><ul><li>Presenters (UI Logic, States)</li><li>Controllers (UI Logic, States)(Interface that holds methods needed by the application which is implemented by Web, Devices or External Interfaces)</li><li>Gateways (Interface that holds every CRUD operation performed by the application, implemented by DB)</li></ul><h4>Application Business Rules</h4><p>Rules which are not Core-business-rules but essential for this particular application come under this. This layer holds Use Cases<strong>. </strong>As the name suggests, it should provide every use case of the application. i.e. it holds each and every functionality provided by the application.</p><p>Also, this is the layer that determines which Controller / Gateway to be called for the particular use case. Sometimes we need controllers from different modules.</p><p>This is where different modules are coordinated. For instance, we want to apply a discount for the user who purchased for x amount within a month.</p><p>Here we need to get the amount the user has spent on this month from the purchase module and then with the result we need to apply the discount for the user in the checkout module<strong>. </strong>Here applyDiscountUseCase<strong> </strong>calls the purchase module’s controller for the data and then applies the discount in the checkout module.</p><h4>Enterprise Business Rules</h4><p>This is the layer that holds core-business rules or domain-specific business rules. Also, this layer is the least prone to change.</p><p>Change in any outer layer doesn’t affect this layer. Since Business Rules won’t change often, the change in this layer is very rare. This layer holds Entities.</p><p>An entity can either be a core data structure necessary for the business rules or an object with methods that hold business logic in it.</p><p>For example: calculating Interest module in the banking application is the core business logic that should be inside this layer.</p><p>Let’s look at a simple example to understand this well.</p><p>The example demonstrates a simple application that has only one network request.</p><p>How can we architect an app that translates the sentence given by the user using a translation API? let’s try to architect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*FeKQ3LXeEcHp7pTsgrLrTA.png" /><figcaption>Image by author</figcaption></figure><p>Each layer does a specific thing. Looks good right? Let’s check the dependency flow for this above architecture to know if anything is wrong.</p><p>Remember Dependency Rule? “The Dependency Rule states that the source code dependencies can only point inwards”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*oIe_ao4ZNEdRJb9Y8KAk8w.png" /><figcaption>Image by author</figcaption></figure><p>UI → Presenter (✅ Not Violating)</p><p>Presenter → Translate Usecase (✅ Not Violating)</p><p>Translate Usecase → Translate Controller (❌ Violating)</p><p>Translate Controller → Web (❌ Violating)</p><p>But it seems correct, right?</p><p>UI requests data from Presenter which requests data from Use Case which should request data from Controller which should request data from Web.</p><blockquote>After all, how can we expect the <em>web</em> to throw some data to<strong><em> </em></strong>the <em>Controller</em><strong><em> </em></strong>without the <em>Controller</em><strong><em> </em></strong>being dependent on it? Also, how can we expect the <em>Use Case</em> to get the proper data from the <em>Controller</em><strong><em> </em></strong>without depending on it?</blockquote><p><em>But the Dependency Rule strictly says dependencies can only point inwards. It adds up by saying this is the rule that makes the architecture work.</em></p><p>In order to pass this rule, we need to invert the arrow to the opposite direction. Is that possible? Here comes Polymorphism<strong>. </strong>When we include some Polymorphism here, something magic happens.</p><p>Simply by having an Interface<strong> </strong>between these 2 layers, we could invert the dependency. This is known as The Dependency Inversion Principle.</p><p>Let’s implement the Dependency Inversion Principle in the cases where the Dependency Rule is violated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*dmvcsbA7-pYc8KTnBWc_7w.png" /><figcaption>Image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*91OVFhAB6qsG8eibQN0xhQ.png" /><figcaption>Image by author</figcaption></figure><p>Thus the flow becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*S-r2PJO1PnAsbtONpUwNsw.png" /><figcaption>Image by author</figcaption></figure><p>Let’s check the dependency flow now to know if anything violates it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3So5c50RNeTEfcqQeIcnOQ.png" /><figcaption>Image by author</figcaption></figure><p>Now we can see that no inner layer depends on any outer layer. Rather, the outer layer depends on the inner layer.</p><blockquote><em>So why should the outer layer depend on the inner layer but not the other way around?</em></blockquote><p>Imagine you’re in a hotel. We want the hotel to serve us what we want, but not what they offer right?. The same thing is happening here, we want the DB to give the data the application needs but not the data it has.</p><p>Application orders what data it wants and it doesn’t care how DB or API prepares the data. This way, the application doesn’t depend on DB or API. If we need/want to change the DB or API Schema in the future, we can simply change it. As far as it gives what the application asks for, the application doesn’t even know the change in DB or API.</p><p>Also, the single-way dependency rule saves the application from the deadlock state. i.e. imagine in a 2 layer architecture, the first layer depends on the second layer, and the second layer depends on the first layer. In such a case, If we need to change anything in the first layer, it breaks the second layer. If we need to change anything in the second layer, it breaks the first layer. This can be rejected by following the deadlock state.</p><p>This is the clean architecture described by Uncle Bob.</p><p>We are yet to see how to move the data across the boundaries and how to handle errors. We’ll do so in future articles.</p><p>Connect with me</p><p><a href="https://linktr.ee/bharath.dev">Bharath | Twitter, Instagram | Linktree</a></p><figure><a href="https://www.buymeacoffee.com/bharath213"><img alt="" src="https://cdn-images-1.medium.com/max/261/1*CUbZDnk6jN2lLseiNqU4gQ.png" /></a></figure><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b7058c1165" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/the-clean-architecture-beginners-guide-e4b7058c1165">The Clean Architecture — Beginner’s Guide</a> was originally published in <a href="https://betterprogramming.pub">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Clock App —Pure Custom Paint with some Math]]></title>
            <link>https://bharath-dev.medium.com/flutter-clock-app-pure-custom-paint-with-some-math-294d24a6bced?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/294d24a6bced</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clock-app]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 13:42:17 GMT</pubDate>
            <atom:updated>2021-07-22T13:42:17.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PE3sIDPgcCjCrhSWute1JA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZ9eSMr1NW9Kl78HEBL6pA.png" /></figure><p>These are the clocks we are gonna build today without any widgets like Transform to manipulate the position of the hour/minute/second hands or any PNG for the minute line. It looks like a very simple design and is easy to implement. But trust me, it’s not that simple.</p><h4>What are the problems we will face while implementing it?</h4><ol><li><em>Implementing Minute lines</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*FQragihRZ5T8wwZ3lqAPAQ.png" /></figure><p>2. <em>Implementing Hour text</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*UI89TXzj5Ebjftcjf5l4IQ.png" /></figure><p>3. <em>Implementing Hour, Minute, Second hands</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*0a1IR_BtKszMlQkTm1aApQ.png" /></figure><p>4. <em>Hour hand’s position is affected by the minute and the minute hand’s position is affected by the second hand.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*J_JeFizyHPgsiMjImy2diA.png" /></figure><blockquote>Hello all guys, In this article we are gonna build these clock from scratch.</blockquote><blockquote>First of all, let me tell you how I ended up building this. I just wanted to learn about Custom Paint. While researching about that, I saw many articles and youtube videos explains about Custom Paint with Clock app.</blockquote><blockquote>But most of the articles and videos talked only about the base circle of the clock as well as the hands. That too using some widgets like <strong>Transform </strong>to rotate or translate the hour/minute/second hands. Most of the tutorials used a <strong>PNG </strong>to implement Minute Lines (First problem we are gonna face), saying it’s gonna require many <strong>Math equations </strong>to implement it.</blockquote><blockquote>That’s how I got the spark to implement the clock <strong>purely with Custom Paint</strong>, without using Transform Widget or PNG for minute lines.</blockquote><h4>Let’s solve the problems one by one.</h4><p>Before solving anything, I just moved the origin point from top left (default origin for a canvas)to the center of the circle using,</p><pre>canvas.translate(clockRadius, clockRadius);</pre><h4><em>1. Implementing Minute lines</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*FQragihRZ5T8wwZ3lqAPAQ.png" /></figure><p>I wanted to solve this problem first since it is the trickiest problem of all.</p><p>Let’s concentrate on a single line first. (5 min line)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*bfsIzUTIFw8Hj_yliHehMQ.png" /></figure><p>We all know that to draw a line we need two endpoints (Offset).</p><p>But, how are we gonna get the endpoints for 60 lines(minutes)?</p><p>Let’s say the radius of the circle is 100 Units.</p><p>Do we know anything else?</p><p>We know that angle of a circle is 360°(2π). We got 60 Minute lines.</p><p>So, if we divide 60-minute lines across 360°, we got 6°. This means each minute line is 6° apart from each other.</p><p>Thus we got,</p><ul><li>The radius of the circle r = 100,</li><li>Number of minute lines = 60,</li><li>The angle between each minute line = 6°.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*vCEkF3Lfv-jCvMi1GzbE2Q.png" /></figure><p>With this informations, we need to find the two endpoints of the minute lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*vPJrJ1yicOqsalUKGbyr9w.png" /></figure><p>Can we do anything to find the offsets for all the minute lines with these pieces of information?</p><p>Yes! Here is where <strong>Trigonometry </strong>comes in.</p><blockquote>If you guys gets shiver by the term Trigonometry, it’s not that hard. Check out my article <a href="https://bharath-dev.medium.com/is-trigonometry-that-hard-lets-build-it-from-scratch-551a14d252ec"><strong><em>Is TRIGONOMETRY that hard? Let’s build it from SCRATCH</em></strong></a><strong><em>. </em></strong><em>There I described about what</em><strong><em> </em></strong>“sin”, “cos”, “tan”, “cosec”, “sec”, “cot” are? And how can we use it?</blockquote><p>In that article, the section <a href="https://bharath-dev.medium.com/is-trigonometry-that-hard-lets-build-it-from-scratch-551a14d252ec#1b88"><strong><em>Application in programming</em></strong></a><strong><em> </em></strong>describes more about this exact scenario. I suggest you read at least this section before continuing if you are not comfortable with Trigonometry.</p><p><strong>A triangle consists of 3 lines and 3 angles.</strong></p><p><strong><em>By using Trigonometry, there are 2 ways to find these properties.</em></strong></p><ul><li><strong><em>If we know 2 lines, we could find the 3rd line and all 3 angles.</em></strong></li><li><strong><em>Or If we know 1 line and 1 angle(other than 90°), we could find the other lines and angles.</em></strong></li></ul><p>Here we are gonna use the 2nd way to find the properties of a triangle and with those properties, we are gonna find the offset of the lines.</p><p>Let’s construct a triangle with what we got for 5 min line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8dFhOFpn1RteU5qvHW8Avw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0HwQLC-v0s1UJq6MM7B5NQ.png" /></figure><p>Sorry for my drawing. Here I constructed a right angle triangle with what we got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pArfpDHaeQYvVYD4usmwtQ.png" /></figure><p>We need to find the endpoints of the 5-minute line.</p><p>We have already seen that the angle between each minute line is 6°. Thus angle between the 60-minute line and the 5-minute line is 30° ( 5 x 6° ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*H-zPguio_A1u1rRj.png" /></figure><p>Therefore, θ = 30° and r = 100 units(Radius of the circle).</p><p>Formula for (x,y) is<strong> </strong><a href="https://bharath-dev.medium.com/is-trigonometry-that-hard-lets-build-it-from-scratch-551a14d252ec#1b88"><strong>(r*cos(θ),r*sin(θ))</strong></a>.</p><p>Thus e2(x2,,y2) = (86.6,50).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUoBKeKDJu2v-Ne2yIOvOw.png" /></figure><p>Now we found the endpoint e2. How can we find the endpoint e1?</p><p>Just reducing the radius(r) we can get the endpoint of e1. Let’s say the minute line length is 10 units. Now by using radius = 90(100–10), e1 = (77.9,45).</p><p>By using this relation, we could find the minute endpoints of all minute lines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/642a49efa3c7150a3c3f714751f8801a/href">https://medium.com/media/642a49efa3c7150a3c3f714751f8801a/href</a></iframe><p>Now we obtain this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*FQragihRZ5T8wwZ3lqAPAQ.png" /></figure><p>We successfully solved our first problem.</p><h4>2. <em>Implementing Hour text</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*UI89TXzj5Ebjftcjf5l4IQ.png" /></figure><p>By using the same technique to solve our first problem, we could find the offset to point the hour text. But here we will face a small problem. Since the text paint from the top left rather than the center, some texts won’t align properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*dQl5m2Ib-heOA0Bi7r7Gqg.png" /></figure><p>By programmatically moves the hour text’s center to the offset we got, we could solve this problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efeb544cf1d2968401e643d09043540e/href">https://medium.com/media/efeb544cf1d2968401e643d09043540e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*W1HiLf6vyInI6LCtx2z8kQ.png" /></figure><p>We solved problem number 2.</p><h4>3. <em>Implementing Hour, Minute, Second hands</em></h4><p>Hour, minute, second hands need just 2 offsets. One is obviously the center point(0,0). Thus we just need to find the 2nd offset to draw a line.</p><p>To find the second offset, we need the angle of the hands.</p><p><strong>Hour hand:</strong></p><p>The Angle between each hour line is 30°(360°/12).</p><p>And since the hour we got is in 24-hour format, by hour%12 converts it into 12-hour format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/417e98bcbd1bc81ae097b945cf8a8a5b/href">https://medium.com/media/417e98bcbd1bc81ae097b945cf8a8a5b/href</a></iframe><h4>Minute Hand:</h4><p>The Angle between each minute line is 6°(360°/60).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/794babb05aed1b29749070f17dda7f80/href">https://medium.com/media/794babb05aed1b29749070f17dda7f80/href</a></iframe><p><strong>Second Hand:</strong></p><p>The Angle between each minute line is 6°(360°/60).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ade1aeeda7fd7fdc4362808e0ba7eca2/href">https://medium.com/media/ade1aeeda7fd7fdc4362808e0ba7eca2/href</a></iframe><p>Everything is good, but there is a minor issue. Since we didn’t include minute in hour hand movement and seconds in minute hand movement, Hour hand and minute hand won’t move partially based on the current time. Rather it jumps from hour to hour and minute to minute. This is the 4th problem.</p><h4><strong>4. <em>Hour hand’s position is affected by the minute and the minute hand’s position is affected by the second hand.</em></strong></h4><p>By slightly improving the θ we can resolve this issue.</p><p><strong>Hour Hand:</strong></p><p>Since minute hand affects the position of the hour hand, including the minute factor with the hour resolves this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/943ef7ee871bfd1257b4d9f591572f3b/href">https://medium.com/media/943ef7ee871bfd1257b4d9f591572f3b/href</a></iframe><p><strong>Minute Hand:</strong></p><p>Since second-hand affects the position of the minute hand, including the second hand’s factor with the minute hand resolves this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef13c6ee85501208a2e5a6bf396c0971/href">https://medium.com/media/ef13c6ee85501208a2e5a6bf396c0971/href</a></iframe><p>Now we got the clock we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*J_JeFizyHPgsiMjImy2diA.png" /></figure><p>We’ve successfully built the clock from SCRATCH with CUSTOM PAINT and TRIGONOMETRY.</p><p>If you find it hard to understand, consider looking at <a href="https://bharath-dev.medium.com/is-trigonometry-that-hard-lets-build-it-from-scratch-551a14d252ec"><strong><em>Is TRIGONOMETRY that hard? Let’s build it from SCRATCH</em></strong></a><strong><em>.</em></strong></p><p>The other 2 clocks shown initially are simple compared to this one.</p><p>Source code: <a href="https://github.com/Bharathh-Raj/clock_app"><strong>GitHub</strong></a></p><p>Follow me on <a href="https://github.com/Bharathh-Raj"><strong>GitHub</strong></a>, <a href="https://bharath-dev.medium.com/"><strong>Medium,</strong></a><strong> </strong><a href="https://www.instagram.com/bharathh_raj/"><strong>Instagram</strong></a><strong> </strong>for more such articles.</p><p><strong>If you liked this article, leave me a clap!</strong></p><h3>Thanks!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294d24a6bced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is TRIGONOMETRY that hard? Let’s build it from SCRATCH.]]></title>
            <link>https://medium.com/math-simplified/is-trigonometry-that-hard-lets-build-it-from-scratch-551a14d252ec?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/551a14d252ec</guid>
            <category><![CDATA[trigonometry]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 02:29:23 GMT</pubDate>
            <atom:updated>2022-01-13T07:14:35.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*4GRXwL8EGk7MxDlP9GDAgA.jpeg" /></figure><p>Trigonometry, one of the most hated subjects in our school days. But why?</p><p>All because of the terms “sin”, “cos”, “tan”, “cosec”, “sec”, “cot”. Are these that hard?</p><p>Hello all guys, in this article we are gonna build Trigonometry from scratch.</p><blockquote>NOTE: I’m not pretending myself as a math genius. I’m a photographer who knows the importance of Trigonometry. If you find any mistakes or something, let me know. Thanks!</blockquote><p>First of all, in this article, I’m gonna experiment with a different way of teaching. We are gonna,</p><ul><li>Face a problem</li><li>Search for the solution</li><li>see how Trigonometry offers the solution</li></ul><h4>Face a problem</h4><p>Once during monument photography, I wanted to cover the full height of the monument in my frame. <strong>So</strong> <strong>I have to find the distance I should stand from the monument to capture its entire height</strong>. I had a 24mm lens which gives the angle of view around 59°.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*VxLVhn2b_DE9fjQ9S6fSCw.png" /></figure><p>Sorry for my drawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiFrBofNLpH5pq_Lj74YJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddaSvBbUOCJgB5WfaLbkKQ.png" /></figure><p>This is the exact scenario I faced,</p><ul><li>Distance between me and the monument = x</li><li>The height of the monument I wanted to capture = 66m</li><li>The height of my camera from the floor = 1.6m</li></ul><p>Since I wanted the monument to be 90° to the frame, I didn’t tilt the camera.</p><p>So my camera is facing 90° from the ground.</p><ul><li>Camera’s angle with respect to ground = 90°</li><li>The angle of view of my 24mm lens = 59°</li></ul><p>Since my camera is facing 90° from the ground and the height of my camera from the ground is 1.6m, half of my lens’s angle of view( 59°/2 = 29.5° ) could only cover 1.6m out of 66m of the monument. i.e I should cover the remaining 64.4m with the remaining 29.5°.</p><p>Let’s revamp this diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNmYMSNxil6j5S2Bq9k1nQ.png" /></figure><p>This is all we have to focus on.</p><ul><li>Height of the monument = 64.4m</li><li>The angle of view = 29.5°</li><li>Distance between me and the monument = x</li></ul><p>This is the problem.</p><h4>Searching for the solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*L-My6Y0TKaYehN-JxUDt_A.png" /></figure><h4>How Trigonometry offers the solution</h4><p>Before talking about what Trignometry offers us, let’s try to solve it ourselves.</p><p>First of all, let’s try to learn what we could about triangles.</p><p><strong>Let’s learn about sides first</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ckNQo1mrXMhg2JFayvjtA.png" /></figure><p>We all know it has 3 sides. Let’s name them as a,b and c.</p><p>Here we need to remember the<strong> Pythagoras theorem</strong>.</p><p><strong>It states that, In a right-angled triangle, the square of the hypotenuse side is equal to the sum of squares of the other two sides.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*HC3fa4-kd5x4hlVLGyZxYg.png" /></figure><p>What does that mean?</p><p>It means that if we construct <strong>2 squares</strong> with sides <strong>a </strong>and <strong>b</strong>, the sum of the areas of two squares is equal to the area of the square we could construct with side <strong>c</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*RD_KcptF9hVPmbsC5OGF2g.png" /></figure><p><em>This means we can able to find a missing side if we know 2 other sides.</em></p><p><strong>Learn about angles in the triangle</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjH6WY0_LiS-jv9DG301pQ.png" /></figure><p><strong>The sum of the angles of any triangle is always equal to 180°.</strong></p><p>Thus for a right-angled triangle, one angle should be 90°, other 2 angles should be θ and 90-θ. So θ is the only angle we need to worry about.</p><blockquote>So far, we have seen only about the right-angled triangles. Is that mean Trigonometry is only applicable for right-angled triangles? Nooooo. Let’s worry about the non-right-angled triangle later. The solution for the non-right-angled triangle is so cool.</blockquote><h4><strong>Learn about sides in the right triangle</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad-fILZWJpp_TbsvbtcBnw.png" /></figure><p>Opposite to the <strong>θ =&gt; Opposite side</strong></p><p>Below the <strong>θ =&gt; Adjacent side</strong></p><p>Longer side =&gt; <strong>Hypotenuse side</strong></p><p><strong>Now, let’s talk about a right-angle triangle with all the required sides and angles, and let’s see what we could learn from them.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2XiaJe54mEdWRBg-qevMQ.png" /></figure><p>Here is a right-angled triangle with its sides and angle.</p><p>a = 3</p><p>b = 4</p><p>c = 5</p><p>θ = 36.87°</p><p><strong>Ok now let’s see how we could get the unknown side if we have 2 known sides with the Pythagoras theorem.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfw9ozySTL_qIyQ-inmTKw.png" /></figure><p>i.e we can find the 3rd side if we know the other 2 sides.</p><p><strong>But for our problem, we have only one side and one angle.</strong></p><ul><li><strong>Height of the monument = 64.4m</strong></li><li><strong>The angle of view = 29.5°</strong></li><li><strong>Distance between me and the monument = x</strong></li></ul><p><strong>Now, let’s learn about θ</strong></p><p>We know that to have an angle, there should be 2 intersecting lines.</p><p>Here we have 3 lines in the triangle. ( This point is more important than we think. We’ll come back to this line soon ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ad-fILZWJpp_TbsvbtcBnw.png" /></figure><p>Since we have 3 possible lines combination.</p><ul><li>Opposite side and adjacent side</li><li>Opposite side and hypotenuse side</li><li>Adjacent side and hypotenuse side</li></ul><p>Let’s see what we could learn from these 3 lines combinations.</p><p>We are gonna take each combination and <strong>assign some sample values</strong> to it and find out how this combination affects <strong>θ</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHQA_PXtkhNuBVd21-PZAA.png" /></figure><p><em>Triangle representation of the above table:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciyyWgnTivPRGnZXq7CmWA.png" /></figure><h4>Opposite side and adjacent side</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xfw1racANWJE9XXReBpSw.png" /></figure><p>As we can see opp/adj is directly proportional to θ.</p><p><strong>As opp/adj increases, the θ value gets increasing and vice versa.</strong></p><h4>Opposite side and hypotenuse side</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbJUwnKXFn9FBE-8mz_Gvg.png" /></figure><p>As we can see opp/hyp is directly proportional to θ.</p><p><strong>As opp/hyp increases, the θ value gets increasing and vice versa but not at the same rate as opp/adj.</strong></p><h4>Adjacent side and hypotenuse side</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxUeor-Hs6RRphxse0AJ_g.png" /></figure><p>Here we can see adj/hyp is inversely proportional to θ.</p><p><strong>As adj/hyp increases, the θ value gets decreasing and vice versa.</strong></p><blockquote><strong>Let’s combine the results we got.</strong></blockquote><blockquote><strong>opp/adj ∝ θ, Increasing in the rate r1.</strong></blockquote><blockquote><strong>opp/hyp ∝ θ, Increasing in the rate r2.</strong></blockquote><blockquote><strong>adj/hyp ∝ 1/ θ, Decreasing in the rate r3.</strong></blockquote><p>Thus by finding the rate, we can able to equate the relation like,</p><ul><li>opp/adj = r1 * θ</li><li>opp/hyp = r2 * θ</li><li>adj/hyp = r3 * θ</li></ul><p>Now you might have realized that these equations look familiar. Let’s see…</p><ul><li><strong>opp/adj = tan(θ)</strong></li><li><strong>opp/hyp = sin(θ)</strong></li><li><strong>adj/hyp = cos(θ)</strong></li></ul><p><strong>Yes, the rate we need is given by “sin”, “cos”, “tan”, “cosec”, “sec”, “cot”. Simple as that. It gives the value from the θ based on the sides we use.</strong></p><p>Since there are 3 sides in a triangle, It makes 3 combinations of sides. Each combination needs a different rate factor. Thus having <strong>“sin”, “cos” and “tan”.</strong></p><p>“cosec”, “sec” and “cot” are nothing but the inverses of “sin”, “cos” and “tan”.</p><p><strong>Now, let’s try to solve our problem,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNmYMSNxil6j5S2Bq9k1nQ.png" /></figure><ul><li>Height of the monument = 64.4m</li><li>The angle of view = 29.5°</li><li>Distance between me and the monument = x</li></ul><p><strong>Solution:</strong></p><p>Opposite side = 64.4m</p><p>θ <strong>= </strong>29.5°</p><p>Adjacent side = x</p><p>Since we know the opposite side and we need to find the adjacent side of the triangle, <strong>tan(θ)</strong> is the one having both opp and adj sides.</p><p><strong>tan(θ) = opp/adj</strong></p><p>=&gt; tan(29.5°) = 64.4 / x</p><p>since tan(29.5°) = 2.78</p><p>=&gt; 2.78 = 64.4/x</p><p>=&gt; x = 64.4 / 2.78</p><blockquote><strong><em>x = 23.165 m.</em></strong></blockquote><p>Thus I need to stand 23.165 m from the monument to cover the entire height.</p><blockquote><strong><em>In case you wonder, what monument I’ve photographed?</em></strong></blockquote><blockquote><strong>It’s </strong><a href="https://en.wikipedia.org/wiki/Brihadisvara_Temple,_Thanjavur"><strong>Brihadeeswara Temple</strong></a><strong> ( Thanjai periya kovil ). If you haven&#39;t seen it in person, I recommend you to take a look. It’s such a fabulous place.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ye0mEGkxJ2L4lKl_GsM7A.jpeg" /></figure><blockquote><strong>For more images of mine, </strong><a href="https://www.instagram.com/bharathh_raj/"><strong>https://www.instagram.com/bharathh_raj/</strong></a></blockquote><p><strong>Congratulations, We have successfully built (basic) Trigonometry from scratch ourselves.</strong></p><p>Now we look at an important question,</p><blockquote><strong>What is Trigonometry?</strong></blockquote><blockquote><strong>Trigonometry is a branch of mathematics that studies relationships involving the lengths and angles of triangles.</strong></blockquote><p>Thus with Trigonometry, we could find the third side if we know the other 2 sides.</p><p>Also, we could find 2 sides with one known side and θ.</p><p><strong>Real-world applications</strong></p><ul><li>Trigonometry can be used to measure the height of a building or mountains,</li><li>Trigonometry used in navigation,</li><li>It is used in the naval and aviation industries.</li></ul><p>For more use cases, <a href="https://www.mathnasium.com/real-life-applications-of-trigonometry">visit this</a>.</p><h4><strong>Do you remember I told you I will talk about how trigonometry solves non-right-angled triangles? I also told you it was so cool.</strong></h4><p>If we think about it, we can easily divide any non-right triangle into 2 right triangles. Thus we can easily solve 2 right triangles to solve the non-right triangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIXU76_iV5Qkyz6wbrBqlw.png" /></figure><h4>Application in programming</h4><p>Sometimes, we need to draw some custom shapes where we need some exact points to draw in the canvas. In such cases, we can use a circle as a reference to find the exact points we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*zFFgA56W8KXqMHqFaohyxw.png" /></figure><p>We can clearly see that the “r” radius of the circle is nothing but the hypotenuse side.</p><p>We can solve this by,</p><p><strong>x = r * cos(θ)</strong></p><p><strong>y = r * sin(θ)</strong></p><p>Let’s understand this formula,</p><ul><li>x = adj side</li><li>y = opp side</li><li>r = hyp side</li></ul><p>Revamping the formula,</p><p><strong>adj = hyp * cos(θ)</strong></p><p><strong>opp = hyp * sin(θ)</strong></p><p>Since <strong>cos(θ) = adj/hyp </strong>and <strong>sin(θ) = opp/hyp,</strong></p><ul><li><strong>x = r * cos(θ)</strong> is nothing but<strong> adj = hyp * adj/hyp</strong></li><li><strong>y = r * sin(θ) </strong>is nothing but <strong>opp = hyp * opp/hyp</strong></li></ul><p>I hope now it all makes sense.</p><p>The trigonometry I covered in this article is just the basics. There is much more to learn.</p><p><strong>Thanks for reading.</strong> <strong>If you like this kind of teaching or you have any suggestions or find any mistakes, feel free to use comments.</strong></p><p><strong>If you learn anything new from this article, just give me a clap.</strong></p><p>Follow me on <a href="https://bharath-dev.medium.com/"><strong>Medium </strong></a>and <a href="https://www.instagram.com/bharathh_raj/"><strong>Instagram</strong></a><strong> </strong>for more such articles.</p><p>If you like this article, take a look at <a href="https://bharath-dev.medium.com/why-do-we-need-the-hexadecimal-number-system-c1fc04728608">Why do we need the Hexadecimal number system?</a></p><h3>Thanks!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551a14d252ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/math-simplified/is-trigonometry-that-hard-lets-build-it-from-scratch-551a14d252ec">Is TRIGONOMETRY that hard? Let’s build it from SCRATCH.</a> was originally published in <a href="https://medium.com/math-simplified">Math Simplified</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why do we need the Hexadecimal number system?]]></title>
            <link>https://medium.com/codex/why-do-we-need-the-hexadecimal-number-system-c1fc04728608?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1fc04728608</guid>
            <category><![CDATA[hexadecimal]]></category>
            <category><![CDATA[number-system]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[binary]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 18:42:52 GMT</pubDate>
            <atom:updated>2022-01-19T04:13:52.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*W5uhFAFIbZTDEvFRt3zS8g.jpeg" /></figure><p>You all might came across the question, Why couldn’t we simply use our traditional human-understandable decimal number system instead of those complex number systems like binary, octal, hexadecimal?</p><blockquote>For example, the decimal number <strong>512 </strong>is represented as</blockquote><blockquote><strong>200</strong> in Hexadecimal number system,</blockquote><blockquote><strong>1000 </strong>in Octal number system,</blockquote><blockquote><strong>0010 0000 0000</strong> in Binary number system.</blockquote><p>It obviously doesn’t make sense right? So, why do we need them again?</p><p>Also, you might have heard that the hexadecimal is human-readable other than decimal.</p><p>Ok, let’s break it down.</p><p>We all know that computers could not able to understand any form of number system without the protocol. It knows only 2 different digits. Either 0 or 1. It is known as binary.</p><p>At the hardware-level either the current flows, which is represented as 1 or not, which is represented as 0. Yes, Computers are so dumb. But humans can understand 10 different digits(0,1,2,3,4,5,6,7,8,9).</p><p>So at the time of the dawn of computing machines, Scientists are so obsessed with solving the problem of how could we ever make the computers understand human-readable digits.</p><p>At first, they think of the solution, by varying the power passing through the wire(system bus), they can able to make the computer understand different digits.</p><p><strong>For example</strong>,</p><p>1 watt to represent the digit 0</p><p>2 watt to represent the digit 1</p><p>so on…</p><blockquote>As you might have noticed there are many cons with this approach.</blockquote><ul><li>First of all, at each level of processing and storing, we need to convert different power to a different digit.</li><li>There are not only 10 digits we need to consider. We have different symbols like , ( % &gt; “ . 26 English alphabets. There are also lower case letters. Also, there is a large number of languages with a different number of characters. In order to serve all these needs, we need to have a different power for each character. That’s hard for machines too.</li><li>Due to those large numbers of different power possibilities, we need to limit the power difference between two consecutive characters. In such a small scale difference, wire’s resistance and length of the wire can vary the current passing through them.</li></ul><blockquote>But Bharath, we have a solution to that problem right?</blockquote><ul><li>Just lower the current and increase the voltage to overcome this issue. But varying the voltage frequently causes voltage fluctuation, which is very bad for electrical components. Else we could add a transformer at every storage and processing layer. That sounds pragmatic😂😂😂.</li></ul><p><strong>Then at some point, people thought in order to represent a large decimal number, they just used a combination of the existing decimal numbers.</strong></p><p>That thought gave the idea of combining binary numbers to get large numbers. But how to combine them?</p><p>That part also comes from the traditional number system. After the decimal numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, we start to combine numbers to make 10, 11, 12…</p><p>Like that, in binary after 0 and 1, we start to combine 2 numbers(bits) to get 10 which represents 2, 11 which represents 3. Then we combine 3 bits 100 to get 4 and so on…</p><p>Now everything is fine and good. we can make the computer understand every number by combining binary digits.</p><p>Ok, the problem with this is that we need to make the computer understand when to look for the next character. For example,</p><p>For the number 1024, the binary number is 010000000000</p><p>and for number 1, the binary number is 1.</p><p>Here both numbers have different numbers of digits. Thus the computer could not understand when to look for the second number.</p><p>In order to rectify this issue, number systems were formed.</p><blockquote>Now coming to the real question. Why do we need the Hexadecimal number system?</blockquote><p>The main objective here is to have a group of bits that should more or less match the decimal number system which is human-understandable.</p><p>Which is how many binary digits we need to group to form the number system which should satisfy human needs.</p><p>Let’s start with a <strong>single bit</strong>. Obviously, it can represent either <strong>0 or 1</strong>. Which is not enough for us.</p><p>Ok, let’s move to <strong>two bits</strong>. It can represent</p><ul><li><strong>0(00)</strong></li><li><strong>1(01)</strong></li><li><strong>2(10)</strong></li><li><strong>3(11)</strong></li></ul><p>which is also not enough for us, since we do more complex math which required more digits than these.</p><p>Then we move to <strong>three bits</strong>. It can represent</p><ul><li><strong>0(000)</strong></li><li><strong>1(001)</strong></li><li><strong>2(010)</strong></li><li><strong>3(011)</strong></li><li><strong>4(100)</strong></li><li><strong>5(101)</strong></li><li><strong>6(110)</strong></li><li><strong>7(111)</strong></li></ul><p>This is better than having 2 bits. It also misses only 2 decimal digits(8 and 9). We can able to manage the shortage of 8 and 9. Thus it evolved as the octal number system Since it can represent 8 decimal digits by using 3 binary digits. This is better but not perfect, thus we move to four bits.</p><p>Let’s see what a <strong>four-bit</strong> number system can do</p><ul><li><strong>0(0000)</strong></li><li><strong>1(0001)</strong></li><li><strong>2(0010)</strong></li><li><strong>3(0011)</strong></li><li><strong>4(0100)</strong></li><li><strong>5(0101)</strong></li><li><strong>6(0110)</strong></li><li><strong>7(0111)</strong></li><li><strong>8(1000)</strong></li><li><strong>9(1001)</strong></li><li><strong>10(1010) =&gt; A</strong></li><li><strong>11(1011) =&gt; B</strong></li><li><strong>12(1100) =&gt; C</strong></li><li><strong>13(1101) =&gt; D</strong></li><li><strong>14(1110) =&gt; E</strong></li><li><strong>15(1111) =&gt; F</strong></li></ul><p>It could satisfy our needs. However, it also represents digits which we don’t need. We could simply neglect those extra digits from a to f, right?</p><p>Actually, these extra digits have some advantages.</p><p>In order to get this, we need to understand what is the advantage of using decimal over binary?</p><p>Obviously, we can represent a large number with fewer digits.</p><p>For example,</p><p>In order to represent <strong>1024 in binary, we need 11 digits. (10000000000)</strong></p><p>Same way, in order to represent <strong>999 in octal, we need 4 digits. (1747)</strong></p><p>But the number <strong>1024 in hexadecimal is 400</strong>. and the number <strong>999 in hexadecimal is 3E7. </strong>Which minimizes the number of digits we need to use. This reduces the calculation time.</p><p><strong>Thus, the hexadecimal number system is pretty much used everywhere.</strong></p><p>We can even go higher than four digits, but those could not be human-readable. So we stick with the hexadecimal number system.</p><blockquote>Now you may ask Bharath, for numbers it is ok. But for alphabets and special characters?</blockquote><p>That is where different character encoding standards came in. eg. ASCII, Unicode, etc…</p><blockquote>Additional note:</blockquote><blockquote>Quantum bit(qubit) can represent different states at once. Which is known as <strong>quantum superposition</strong>. i.e. 4 qubits can represent the same 16 combinations but <strong>all at the same time</strong>. which means it can compare all possible states at once. It sounds astonishing, right? Let’s see about that in detail in upcoming articles. Thanks!</blockquote><p>return;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1fc04728608" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/why-do-we-need-the-hexadecimal-number-system-c1fc04728608">Why do we need the Hexadecimal number system?</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Encapsulation?]]></title>
            <link>https://bharath-dev.medium.com/why-encapsulation-8f74439a27fe?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f74439a27fe</guid>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Thu, 05 Nov 2020 18:09:18 GMT</pubDate>
            <atom:updated>2020-11-05T18:09:18.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBuCRIBwKA8tI6Vip7qBHw.png" /></figure><p>First of all, If you didn&#39;t read my article “<a href="https://bharath-dev.medium.com/why-oops-efd5eff62ae4">Why OOPS?</a>” check out that one to have good continuity.</p><p>Today we are gonna learn about Encapsulation.</p><p>Encapsulation is one of the four principles of OOPS.</p><h4>So, what is Encapsulation?</h4><p>Encapsulation is just hiding the variables(properties) and functions(methods) of the same entity behind a Class. Those properties and methods can only be accessed by its object.</p><h4>So, Why to hide those?</h4><p>If we didn’t hide those, then any other variables or functions can able to access or change the data.</p><p>Ok, let’s see what was the real problem solved by encapsulation.</p><h4>Scenario:</h4><p>Let’s consider we need to process some data of a mom and her son.</p><p>For mom, we need to have her name, age, present month’s income one, present month’s income two, total savings, and the function which calculates the <strong>sum</strong> of the total amount she has.</p><p>For her son, we need to have his name, age, grade, math score, physics score, and the function which gives the total marks he scored.</p><p>Let’s solve this problem</p><ul><li>Without Encapsulation</li><li>With Encapsulation</li></ul><p>I’m using java to demonstrate these scenarios.</p><h3>Without Encapsulation:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfGdzD8TskKRzrBhiUAj1w.png" /></figure><blockquote><em>Hey Bharath, It seems like everything is clean and well organized. What’s the problem here?</em></blockquote><h4><strong>Problem One:</strong></h4><p>Accidentally/Willingly accessing the wrong function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJA3RLBwUrKqFlOQxIlTdg.png" /></figure><p>Guess what will happen if son accidentally passed <strong><em>mathScore </em></strong>and <strong><em>physicsScore </em></strong>to the function “sum”, he will get 10574 as the total mark.</p><p>Guess what will happen if mom accidentally passed <strong><em>incomeOne </em></strong>and <strong><em>incomeTwo </em></strong>to the function “total”.(“This Little Maneuver’s Gonna Cost her 51 Years”😂)</p><h4><strong>Problem Two:</strong></h4><p><strong>Your mom can access your score😱</strong> just by calling the <strong><em>mathScore </em></strong>or <strong>physicsScore </strong>variable.</p><blockquote><em>Ok Bharath, I got it. I won’t ask any other question 🤐. Just tell me how to hide.</em></blockquote><h4>Problem Three:</h4><blockquote>Caution: The <strong>stunt</strong> I’m gonna share is very dangerous and potentially fatal! Do not attempt this <strong>stunt</strong> without proper training!</blockquote><p><strong>Son can able to change his scores.</strong>(I never did that😁)</p><p>Here comes the Encapsulation part.</p><h3>With Encapsulation:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VgWNoqMW00QE9a9Fzj7kA.png" /></figure><h4>Solution for problem one:</h4><p>Encapsulation hides the variables and functions behind its object. Thus they cannot be accessed accidentally/willingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Rw18O0Re2GEnDRaxecp9w.png" /></figure><h4><strong>Solution for problem two:</strong></h4><p>No one can able to access your properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep84iHXz2rwiNi07N7VfEw.png" /></figure><h4>Solution for problem three:</h4><p>It can even be secured with private properties and accessing them using getters. So that even the son cannot change the scores once assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqiAJ6Y6JqGyamy4zcb5sA.png" /></figure><p>Bravo! We did it.</p><p>Thanks for your support guys!</p><p>return;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f74439a27fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why OOPS?]]></title>
            <link>https://bharath-dev.medium.com/why-oops-efd5eff62ae4?source=rss-a78bd0833de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/efd5eff62ae4</guid>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Bharath]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 17:23:34 GMT</pubDate>
            <atom:updated>2020-11-05T05:22:28.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*wejAi67s94h9SWG-piA-DA.png" /></figure><p>I like to divide this article into two parts.</p><ul><li>Without OOPS</li><li>With OOPS</li></ul><p>For easy understanding, I write the code snippets in java.</p><p><strong><em>Scenario:</em></strong></p><p>What if we have to process a large number of student’s details?</p><p>The details include their name, class, section, rank.</p><h3><strong>Without OOPS:</strong></h3><p>Without OOPS means obviously no classes. Then what do we got?</p><h4>Primitive data types include:</h4><ul><li>Byte</li><li>Short</li><li>Int</li><li>Long</li><li>Float</li><li>Double</li><li>Boolean</li><li>Char</li></ul><h4>Non-Primitive data types include:</h4><ul><li>String</li><li>Array</li><li>Classes ( I’ll come back to this later)</li></ul><p>In order to store the Name, <strong>String</strong> must be the best option.</p><p>For Class, we can also use <strong>String</strong>.</p><p>For Section, we can use <strong>Char</strong>.</p><p>For Rank, we can use <strong>Int</strong>.</p><p>For Simplicity&#39;s sake, we consider there are only 3 students.</p><p>In order to store data of 3 students we need</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*e6foqm6f57woTXdx2jLnfw.png" /></figure><p><strong><em>Pros:</em></strong></p><ul><li>You can call HTML as a programming language. (😂😂😂)</li></ul><p><strong><em>Cons:</em></strong></p><ul><li>As you might have guessed, for more number of students more number of variables are needed.</li><li>Keeping track of all those variables is a nightmare.</li><li>Variables are vulnerable to accidental changes.</li></ul><p>Ok, now look back at the code snippet above, and let’s try to understand something.</p><p>For all the names we used Strings, for all the classes we used int, for all the sections we used char and for all the ranks we used int.. i.e. common data type for common data. Yeah! You got it again.</p><p>It’s time for Hurray(Array😂😂).</p><p>By using Array, we can shrink the code to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sfyu5m3d80Xo-za1zZ5fEg.png" /></figure><p><strong><em>Pros:</em></strong></p><ul><li>Somewhat manageable.</li><li>It does not require too many variables.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li>If a student’s name is removed from the array, we need to move most other student’s names.</li><li>Also, we need to change the location of every other detail as well. Thus Maintainability is a dream.</li></ul><p>Now, let&#39;s move to the more pragmatic approach. “<strong>THE OOPS APPROACH”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Xsnk_gkcMvQpexrTCscZWg.png" /></figure><p>oh oh oh! wait. Don’t get scared by seeing its size. Let me explain.</p><p>Classes are nothing but to group different properties of the same entity. Here, for a student entity class, section, rank are the different properties. Of course, we can add any number of properties.</p><p>So why Classes again?</p><p><strong><em>Pros:</em></strong></p><ul><li>It does not need to have lots of variables.</li><li>It does not need to change if someone’s data is changed.</li><li>Accessing a property is very simple as &lt;Object name&gt;.&lt;Property name&gt;</li><li>Encapsulation, Inheritance, and Polymorphism (What the *hello world* are those???🙄). Let’s see in another article. But trust me they are “Hello <strong>Universe</strong>!”. <strong>OOPS!</strong> It seems like I missed one principle. Let me know in the comments.</li><li>Code reuse.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li>Honestly, I couldn’t come up with any cons. If you know any, let me know in the comments.</li></ul><p>Also, we can use a constructor to reduce boilerplate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sq6zVSZC7GEetx4Y8qopig.png" /></figure><p>Bravo! We did it.</p><p>Ok! wait, don’t forget to attend the <strong>death ceremony</strong> of those large numbers of variables and misused arrays. At least they served this long!</p><p>return;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efd5eff62ae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>