<?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 Daniel Pham on Medium]]></title>
        <description><![CDATA[Stories by Daniel Pham on Medium]]></description>
        <link>https://medium.com/@danillion?source=rss-9cb46516a598------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*omT_VgbytRVxoByRKi2cyQ.jpeg</url>
            <title>Stories by Daniel Pham on Medium</title>
            <link>https://medium.com/@danillion?source=rss-9cb46516a598------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 14:18:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danillion/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[Building and Testing a Chinese Auction DApp with Solidity and Truffle (p.2)]]></title>
            <link>https://medium.com/coinmonks/building-and-testing-a-chinese-auction-dapp-with-solidity-and-truffle-p-2-b1e9c6b3fec4?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1e9c6b3fec4</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 15:31:21 GMT</pubDate>
            <atom:updated>2024-01-29T07:34:32.817Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Building on our previous work, this article delves into extending the Chinese auction smart contract implementation by leveraging the Truffle development framework. We’ll turn it into a DApp by utilizing Truffle’s capabilities and rigorously testing the contract’s functionalities.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*bCEl-A8GmpWxZfAj.jpeg" /></figure><h3>Prerequisites</h3><p>If you have not read through part 1 of this article, you can browse through this link for more on the smart contract and its implementation:</p><blockquote><a href="https://medium.com/coinmonks/building-a-chinese-auction-smart-contract-with-solidity-and-remix-ide-8b242fbcaf3b"><strong>Building a Chinese Auction Smart Contract with Solidity and Remix IDE (p.1)</strong></a></blockquote><p>Now, let’s recap the design process we’ve followed so far. Essentially, we begin by defining the problem we’re trying to solve, then we implement the smart contract logic using Solidity and write it in the Remix IDE. Once we’ve verified that the contract works correctly in Remix, we incorporate the smart contract code into our Dapp codebase and perform testing using Truffle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*TwAQYwtIQpC4kXFE2chz3A.png" /></figure><p>Follow the steps you’ve learned to create a Truffle project. Ensure that you can successfully initialize the project and deploy the Auction contract to the test blockchain using the following commands (truffle init, truffle compile, truffle development, truffle migrate — reset). More detailed information about each command can be found in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0aFuGFjR5o6xEqH5A45Jg.png" /></figure><h3>Test-driven Development Guidelines</h3><h4>1. Imports and variables</h4><p>To set up the testing environment, we need to import the Auction smart contract artifact:</p><pre>let Auction = artifacts.require(&quot;./Auction.sol&quot;);</pre><p>Declaring an instance variable to represent the deployed contract is also necessary. The auctionInstance variable is used to store the reference to the deployed Auction contract on the test blockchain.</p><pre>let auctionInstance;</pre><p>Once initialized, our test.js file looks like this:</p><pre>let Auction = artifacts.require(&quot;./Auction.sol&quot;);<br><br>let auctionInstance;<br><br>contract(&#39;AuctionContract&#39;, function (accounts) {<br>    // Insert code here<br>});</pre><h4>2. Test Case: Contract Deployment</h4><p>This test case checks if the contract has been deployed. If it has, it returns the instance in the callback function. We simply store the instance in a global variable for future use and also assert it to check if it is indeed not null.</p><pre>it(&quot;Contract deployment&quot;, async function () {<br>  // Fetching the contract instance of our smart contract<br>  const instance = await Auction.deployed();<br><br>  // We save the instance in a global variable and all smart contract functions are called using this<br>  auctionInstance = instance;<br><br>  // Assert that the instance is defined<br>  assert.isTruthy(auctionInstance !== undefined, &#39;Auction contract should be defined&#39;);<br>});</pre><h4>3. Test case: Should set bidders</h4><p>This test case creates a call to the register() function. Then, we call the getPersonDetails() function to retrieve the person&#39;s details. The person&#39;s details will appear in the callback function and we assert whether it is correct with the address that we have registered.</p><pre>it(&quot;Should set bidders&quot;, async function () {<br>  // Register a bidder<br>  const result = await auctionInstance.register({ from: accounts[1] });<br><br>  // Get the bidder details<br>  const personDetails = await auctionInstance.getPersonDetails(0);<br><br>  // Assert that the bidder address is correct<br>  assert.equal(personDetails[2], accounts[1], &#39;bidder address set&#39;);<br>});</pre><p>At this point, run the command truffle testand you will see two tests pass if your <strong>Auction.sol</strong> is correct and the Truffle commands are correct. You will see the two tests pass as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*77FvBqFxTSY4ufss" /></figure><p>After passing the first two sample test cases, we will continue to the main test scripts. There are three test cases, and require a total of approximately 19 lines of code. If you increase the development of the scripts for the test cases, you will only focus on that test case and therefore less code.</p><h4>4. Test Case: Should Not Allow to Bid More Than Remaining Tokens</h4><p>This test case checks for an unsuccessful or negative condition (a condition that should trigger a rollback). It attempts to bid more than the remaining tokens, which should result in a rollback error.</p><pre>it(&quot;Should Not Allow to Bid More Than Remaining Tokens&quot;, async function () {<br>  // Attempt to bid more than the remaining tokens<br>  const result = await auctionInstance.bid(0, 6, { from: accounts[1] });<br><br>  try {<br>    // If the bid was successful, it means the rollback mechanism failed. Throw an error and catch it to assert false.<br>    if (result.status === 0) {<br>      throw new Error(&quot;Failed to check remaining tokens less than count&quot;);<br>    }<br>  } catch (error) {<br>    // Catch the error and assert true if the rollback mechanism correctly prevented the bid.<br>    if (error.message === &quot;Failed to check remaining tokens less than count&quot;) {<br>      assert(false, &quot;Rollback mechanism failed&quot;);<br>    } else {<br>      assert(true, &quot;Rollback mechanism successfully prevented invalid bid&quot;);<br>    }<br>  }<br>});</pre><h4>5. Test Case: Should Not Allow Non-owner to Reveal Winners</h4><p>This test case checks for an unsuccessful or negative condition (a condition that should trigger a rollback). It attempts to reveal the winners from a non-owner account, which should result in a rollback error.</p><pre>it(&quot;Should NOT allow non owner to reveal winners&quot;, async function () {<br>  // Attempt to reveal the winners from a non-owner account<br>  const result = await auctionInstance.revealWinners({ from: accounts[1] });<br><br>  try {<br>    // If the reveal was successful, it means the authorization mechanism failed. Throw an error and catch it to assert false.<br>    if (result.status === 0) {<br>      throw new Error(&quot;Failed to check owner in reveal winners&quot;);<br>    }<br>  } catch (error) {<br>    // Catch the error and assert true if the authorization mechanism correctly prevented the reveal.<br>    if (error.message === &quot;Failed to check owner in reveal winners&quot;) {<br>      assert(false, &quot;Authorization mechanism failed&quot;);<br>    } else {<br>      assert(true, &quot;Authorization mechanism successfully prevented unauthorized reveal&quot;);<br>    }<br>  }<br>});</pre><h4>6. Test Case: Should Set Winners</h4><p>This test case verifies the proper functioning of the contract by registering three accounts, bidding on items using them, and revealing the winners from the authorized account. It then asserts that the winner address is not the default address for each item.</p><pre>it(&quot;Should set winners&quot;, async function () {<br><br>  // Register three accounts<br>  await auctionInstance.register({ from: accounts[2] });<br>  await auctionInstance.register({ from: accounts[3] });<br>  await auctionInstance.register({ from: accounts[4] });<br><br>  // Bid on items using registered accounts<br>  await auctionInstance.bid(0, 5, { from: accounts[2] });<br>  await auctionInstance.bid(1, 5, { from: accounts[3] });<br>  await auctionInstance.bid(2, 5, { from: accounts[4] });<br><br>  // Reveal the winners from the authorized account<br>  await auctionInstance.revealWinners({ from: accounts[0] });<br><br>  // Assert that the winner address is not the default address for item 0<br>  const winnerAddress0 = await auctionInstance.winners(0, { from: accounts[0] });<br>  assert.notEqual(winnerAddress0, &quot;0x0000000000000000000000000000000000000000&quot;, &quot;Winner address for item 0 should not be the default address&quot;);<br><br>  // Assert that the winner address is not the default address for item 1<br>  const winnerAddress1 = await auctionInstance.winners(1, { from: accounts[0] });<br>  assert.notEqual(winnerAddress1, &quot;0x0000000000000000000000000000000000000000&quot;, &quot;Winner address for item 1 should not be the default address&quot;);<br><br>  // Assert that the winner address is not the default address for item 2<br>  const winnerAddress2 = await auctionInstance.winners(2, { from: accounts[3] });<br>  assert.notEqual(winnerAddress2, &quot;0x0000000000000000000000000000000000000000&quot;, &quot;Winner address for item 2 should not be the default address&quot;);<br>});</pre><p>If all the tests in test.js and the code you entered are correct, when you run truffle test, you will see the following results: (times may vary)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s4eTuuuaGIuCFJIS" /></figure><h3>Conclusion</h3><p>Combining all the codes together, our full-fledged test scripts now include in total 5 tests as followed:</p><pre>let Auction = artifacts.require(&quot;./Auction.sol&quot;);<br><br>let auctionInstance;<br><br>contract(&#39;AuctionContract&#39;, function (accounts) {<br>  //accounts[0] is the default account<br><br>  //Sample test case 1<br>  it(&quot;Contract deployment&quot;, async function () {<br>    // Fetching the contract instance of our smart contract<br>    const instance = await Auction.deployed();<br><br>    // We save the instance in a global variable and all smart contract functions are called using this<br>    auctionInstance = instance;<br><br>    // Assert that the instance is defined<br>    assert.isTruthy(auctionInstance !== undefined, &#39;Auction contract should be defined&#39;);<br>  });<br><br>  //Sample test case 2<br>  it(&quot;Should set bidders&quot;, async function () {<br>    // Register a bidder<br>    const result = await auctionInstance.register({ from: accounts[1] });<br><br>    // Get the bidder details<br>    const personDetails = await auctionInstance.getPersonDetails(0);<br><br>    // Assert that the bidder address is correct<br>    assert.equal(personDetails[2], accounts[1], &#39;bidder address set&#39;);<br>  });<br><br>  //Test Case for checking if the bid is more than the token amount<br>  it(&quot;Should Not Allow to Bid More Than Remaining Tokens&quot;, async function () {<br>    // Attempt to bid more than the remaining tokens<br>    const result = await auctionInstance.bid(0, 6, { from: accounts[1] });<br><br>    try {<br>      // If the bid was successful, it means the rollback mechanism failed. Throw an error and catch it to assert false.<br>      if (result.status === 0) {<br>        throw new Error(&quot;Failed to check remaining tokens less than count&quot;);<br>      }<br>    } catch (error) {<br>      // Catch the error and assert true if the rollback mechanism correctly prevented the bid.<br>      if (error.message === &quot;Failed to check remaining tokens less than count&quot;) {<br>        assert(false, &quot;Rollback mechanism failed&quot;);<br>      } else {<br>        assert(true, &quot;Rollback mechanism successfully prevented invalid bid&quot;);<br>      }<br>    }<br>  });<br><br>  //Modifier Checking<br>  it(&quot;Should NOT allow non owner to reveal winners&quot;, async function () {<br>    // Attempt to reveal the winners from a non-owner account<br>    const result = await auctionInstance.revealWinners({ from: accounts[1] });<br><br>    try {<br>      // If the reveal was successful, it means the authorization mechanism failed. Throw an error and catch it to assert false.<br>      if (result.status === 0) {<br>        throw new Error(&quot;Failed to check owner in reveal winners&quot;);<br>      }<br>    } catch (error) {<br>      // Catch the error and assert true if the authorization mechanism correctly prevented the reveal.<br>      if (error.message === &quot;Failed to check owner in reveal winners&quot;) {<br>        assert(false, &quot;Authorization mechanism failed&quot;);<br>      } else {<br>        assert(true, &quot;Authorization mechanism successfully prevented unauthorized reveal&quot;);<br>      }<br>    }<br>  });<br><br>  // Test case for winners and bid amount<br>  it(&quot;Should set winners&quot;, async function () {<br>    // Register three accounts<br>    await auctionInstance.register({ from: accounts[2] });<br>    await auctionInstance.register({ from: accounts[3] });<br>    await auctionInstance.register({ from: accounts[4] });<br><br>    // Bid on items using registered accounts<br>    await auctionInstance.bid(0, 5, { from: accounts[2] });<br>    await auctionInstance.bid(1, 5, { from: accounts[3] });<br>    await auctionInstance.bid(2, 5, { from: accounts[4] });<br><br>    // Reveal the winners from the authorized account<br>    await auctionInstance.revealWinners({ from: accounts[0] });<br><br>    // Assert that the winner address is not the default address for item 0<br>    const winnerAddress0 = await auctionInstance.winners(0, { from: accounts[0] });<br>    assert.notEqual(winnerAddress0, &quot;0x0000000000000000000000000000000000000000&quot;, &quot;Winner address for item 0 should not be the default address&quot;);<br><br>    // Assert that the winner address is not the default address for item 1<br>    const winnerAddress1 = await auctionInstance.winners(1, { from: accounts[0] });<br>    assert.notEqual(winnerAddress1, &quot;0x0000000000000000000000000000000000000000&quot;, &quot;Winner address for item 1 should not be the default address&quot;);<br><br>    // Assert that the winner address is not the default address for item 2<br>    const winnerAddress2 = await auctionInstance.winners(2, { from: accounts[3] });<br>    assert.notEqual(winnerAddress2, &quot;0x0000000000000000000000000000000000000000&quot;, &quot;Winner address for item 2 should not be the default address&quot;);<br>  });<br>});</pre><p>In short, we have explored the process of testing a smart contract, which is the core of a Dapp in a blockchain-based system. By emphasizing the importance of rigorous smart contract testing, we learned that it is never safe to deploy any code without testing it thoroughly.</p><h3>📚 Resources 📚</h3><ul><li><strong><em>🔗 </em></strong><a href="https://github.com/danillionbits/chinese-auction-contract"><strong><em>Github Source</em></strong></a></li><li><strong><em>📝 </em></strong><a href="https://danillion.medium.com/"><strong><em>Medium Article Source</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1e9c6b3fec4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/building-and-testing-a-chinese-auction-dapp-with-solidity-and-truffle-p-2-b1e9c6b3fec4">Building and Testing a Chinese Auction DApp with Solidity and Truffle (p.2)</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Chinese Auction Smart Contract with Solidity and Remix IDE (p.1)]]></title>
            <link>https://medium.com/coinmonks/building-a-chinese-auction-smart-contract-with-solidity-and-remix-ide-8b242fbcaf3b?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b242fbcaf3b</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 14:12:46 GMT</pubDate>
            <atom:updated>2024-01-25T19:05:10.254Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this article, we’ll delve into the implementation of a Chinese auction smart contract using Solidity, the programming language for writing smart contracts on the Ethereum blockchain.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Kag39K3lLzm-Vqa0ikDDg.jpeg" /></figure><h3>Overview of the Auction Smart Contract</h3><p>Chinese social auctions are a type of auction commonly used to raise funds for charity. Organizers gather items to be auctioned and place bowls in front of each item. Bidders purchase tickets, which they place in the bowls of the items they wish to bid on. The auctioneer selects a ticket from each bowl at random to determine the winner. The winner receives the item, and the proceeds are used to support the cause.</p><h4>1. Assumptions</h4><p>The project overview outlines a standard monetary auction. To effectively implement it, we’ll introduce several simplifying assumptions:</p><ul><li>A fixed number of bidders, initialized to four. All four bidders must register themselves. Money transfer between bidders is automated and falls outside the scope of this application.</li><li>A fixed number of items, initialized to three.</li><li>Items are indexed from 0 to N-1, where N represents the number of auctioned items. N is two.</li><li>Each bidder purchases only one token ticket or token code, each containing five tokens.</li><li>Assume a simple serial number for token tickets: 0, 1, 2, 3. The token codes for bidders 0 and 1 are displayed.</li></ul><pre><br>+-----+-----+-----+-----+-----+<br>| 0   | 0   | 0   | 0   | 0   |<br>| 1   | 1   | 1   | 1   | 1   |<br>| ... | ... | ... | ... | ... |<br>| n-1 | n-1 | n-1 | n-1 | n-1 |<br>+-----+-----+-----+-----+-----+</pre><h4>2. Data Structures</h4><p>The first step is to define the data structures that we will need. We will need the following:</p><ul><li>Item: Store information about each item being auctioned, such as its ID, description, and starting price.</li><li>Person: Store information about each bidder, such as their ID, address, and the number of tokens they have remaining.</li></ul><h4>3. Functions</h4><p>Four functions are required in this particular Chinese auction smart contract:</p><ul><li>Auction(): Initialize the contract as constructor function.</li><li>register(): Allow a user to register as a bidder.</li><li>bid(): Allow a bidder to place a bid on an item.</li><li>revealWinner(): Randomly select winners for each item.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*WWtQ74Pp01TnQref" /></figure><h3>Implementation Guidelines</h3><h4>Contract Structures</h4><p>The Item structure holds the details of an item being auctioned. It includes an itemId (a unique identifier for the item) and itemTokens (an array holding the tokens bid in favor of the item).</p><pre>struct Item {<br>  uint itemId; // id of the item<br>  uint[] itemTokens; //tokens bid in favor of the item<br>}</pre><p>Meanwhile, the Person structure holds the details of a person (or bidder). It includes remainingTokens (the number of tokens remaining with the bidder), personId (which also serves as the token ID), and addr (the address of the bidder).</p><pre>struct Person {<br>  uint remainingTokens; // tokens remaining with bidder<br>  uint personId; // it serves as tokenId as well<br>  address addr; //address of the bidder<br>}</pre><h4>Contract Initialization</h4><p><strong>Variables</strong></p><p>In the auction contract, the tokenDetails mapping links an Ethereum address to a Person struct, storing bidder details.</p><pre>mapping(address =&gt; Person) tokenDetails;</pre><p>We also initialize the bidders array and the items array, which can store four Person structs and three Item structs, respectively, with the latter representing the items being auctioned.</p><pre>Person [4] bidders;<br>Item [3] public items;</pre><p>Additionally, the beneficiary variable represents the contract owner’s Ethereum address, and the bidderCount variable is a counter that tracks the number of registered bidders. The winners array stores the winners’ addresses.</p><pre>address[3] public winners;<br>address public beneficiary;<br>uint bidderCount=0;</pre><p><strong>Constructor</strong></p><p>The contract is initialized with the constructor() function. Here, the beneficiary (the owner of the smart contract) is set to the address that deploys the contract (msg.sender). Two items are then initialized with IDs 1 and 2, and both items are assigned an empty array of tokens.</p><pre>constructor() payable{    <br>  beneficiary = msg.sender;<br>  uint[] memory emptyArray;<br>  items[0] = Item({itemId:0,itemTokens:emptyArray});<br>  items[1] = Item({itemId:1,itemTokens:emptyArray});<br>  items[2] = Item({itemId:2,itemTokens:emptyArray});<br>}</pre><h4>register()</h4><p>The register() function allows a user to register as a bidder. They are assigned a personId (which is also their token ID), their address is stored, and they are given 5 tokens.</p><pre>function register() public payable{<br>    bidders[bidderCount].personId = bidderCount;<br>    bidders[bidderCount].addr = msg.sender;<br>    bidders[bidderCount].remainingTokens = 5; // only 5 tokens<br>    tokenDetails[msg.sender]=bidders[bidderCount];<br>    bidderCount++;<br>}</pre><h4>bid()</h4><p>The bid() function allows a registered user to place a bid on an item. The function takes in the item ID and the count of tokens to bid. It ensures that the user has enough tokens to bid and that the item ID is valid. Then, it deducts the bid amount from the user&#39;s remaining tokens and adds the tokens to the item&#39;s itemTokens array.</p><pre>function bid(uint _itemId, uint _count) public payable{<br>    require(tokenDetails[msg.sender].remainingTokens &gt;= _count);<br>    require(tokenDetails[msg.sender].remainingTokens &gt; 0);<br>    require(_itemId &lt;= 2);<br>    uint balance= tokenDetails[msg.sender].remainingTokens - _count;<br>    tokenDetails[msg.sender].remainingTokens=balance;<br>    bidders[tokenDetails[msg.sender].personId].remainingTokens=balance;<br>    Item storage bidItem = items[_itemId];<br>    for(uint i=0; i&lt;_count;i++) {<br>        bidItem.itemTokens.push(tokenDetails[msg.sender].personId);    <br>    }<br>}</pre><h4>onlyOwner</h4><p>The onlyOwner modifier ensures that only the owner of the contract (the beneficiary) can call certain functions.</p><pre>modifier onlyOwner {<br>    require(msg.sender == beneficiary);<br>    _;<br>}</pre><h4>revealWinners()</h4><p>Finally, the revealWinners() function selects a winner for each item. It iterates over all the items, and if at least one person has placed a bid on an item, it randomly selects a winner. The selected winner&#39;s address is then stored in the winners array.</p><pre>function revealWinners() public onlyOwner{<br>    for (uint id = 0; id &lt; 3; id++) {<br>        Item storage currentItem=items[id];<br>        if(currentItem.itemTokens.length != 0){<br>            uint randomIndex = (block.number / currentItem.itemTokens.length)% currentItem.itemTokens.length; <br>            uint winnerId = currentItem.itemTokens[randomIndex];<br>            winners[id] = bidders[winnerId].addr;<br>        }<br>    }<br>}</pre><h4>Testing the Auction Smart Contract</h4><p>Once you have completed the implementation of the Auction smart contract, it is important to test it to ensure that it is working correctly. You can do this by using the Remix JavaScript VM.</p><p>To test the contract on Remix, follow these steps:</p><ol><li>Compile and deploy the contract to the Remix VM.</li><li>Account 0 provided by the Remix VM is the Auction beneficiary and will not bid. Navigate to each of the other accounts and “register”. This will register four bidders using the register() function.</li><li>The next step is for the bidders to place a bid for each item. For testing purposes, you can execute the bid() function with {{0, 1} {1, 1} {2, 1}} for each of the four accounts. This will place a bid of 1 token for each item for each bidder.</li><li>Next, execute the revealWinner() function to randomly determine the winner for each item. This will return the address of the winning bidder for each item.</li><li>The getter of the winners data can be executed with {0, 1, and 2} as sequential parameters to display the winners sequentially. This will return the addresses of the winners of the auction, in order of the items they won.</li></ol><h3>Conclusion</h3><p>Combining all the codes together, we create a simple yet practical and fully functional Auction smart contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/052490414e3d12618cce156efa749bd4/href">https://medium.com/media/052490414e3d12618cce156efa749bd4/href</a></iframe><p>In conclusion, we’ve successfully implemented a Chinese auction smart contract using Solidity and Remix IDE. This smart contract enables users to participate in an auction where bids are placed in tokens rather than traditional currency. By combining the power of Solidity and Remix IDE, we’ve created a user-friendly and secure platform for conducting Chinese auctions on the Ethereum blockchain.</p><h3>📚 Resources 📚</h3><ul><li><strong><em>🔗 </em></strong><a href="https://github.com/danillionbits/chinese-auction-contract"><strong><em>Github Source</em></strong></a></li><li><strong><em>📝 </em></strong><a href="https://danillion.medium.com/"><strong><em>Medium Article Source</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b242fbcaf3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/building-a-chinese-auction-smart-contract-with-solidity-and-remix-ide-8b242fbcaf3b">Building a Chinese Auction Smart Contract with Solidity and Remix IDE (p.1)</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Potential of DApps: A Practical Guide to Truffle IDE]]></title>
            <link>https://medium.com/coinmonks/unleashing-the-potential-of-dapps-a-guide-to-development-with-truffle-c5e14b98041a?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5e14b98041a</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 13:12:47 GMT</pubDate>
            <atom:updated>2024-01-18T14:43:35.533Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of decentralized applications (Dapps), Truffle stands as a prominent development framework, empowering developers to craft innovative and secure Dapps on the Ethereum blockchain. This article delves into the fundamentals of Dapp development and Truffle’s role in streamlining the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aBG2pBVakBAMGGzQ.png" /></figure><h3>Decentralized applications — Dapps</h3><h4>1. Blockchain server</h4><p>At its core, a decentralized application (DApp) consists of two primary components: a client-facing interface known as the front-end, and a back-end infrastructure comprising a blockchain and a smart contract. While DApps typically utilize blockchain technology for their backend, they can also function with non-blockchain backends.</p><p>Each DApp network is assigned a unique identifier, known as a network ID, to distinguish it from others. For instance, the Ethereum main network, including Metropolis, has a network ID of 1, while the public cross-client Ethereum testnet, Ropsten, carries a network ID of 3. Rinkeby, another Ethereum testnet, boasts a network ID of 4. Interestingly, the music blockchain, Musicoin, has a distinctive network ID of 7762959.</p><h4>2. Dapp</h4><p>Decentralized applications, or DApps, are software applications that utilize blockchain technology to operate without the need for centralized servers or intermediaries. They typically consist of three main components:</p><ol><li><strong>Front-end</strong>: The user interface, which can be a simple command-line interface, a web application, or a mobile app, allows users to interact with the DApp.</li><li><strong>Blockchain backend</strong>: The underlying blockchain network serves as a secure and transparent record of all DApp transactions and data.</li><li><strong>Connecting code</strong>: This middleware bridges the gap between the front-end and the blockchain backend, enabling seamless interaction and data exchange.</li></ol><p>The architecture of Dapps can be illustrated as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*shBmvanO7pcvilgp9sDyKw.png" /></figure><h4>3. Ethereum APIs</h4><p>Ethereum APIs, akin to familiar tools like Twitter API or Google Maps API, provide a standardized means to interact with the Ethereum blockchain. These APIs empower developers to construct decentralized applications (DApps) that use the power of blockchain technology.</p><p>Ethereum APIs fall into two primary categories:</p><ul><li><strong>Management APIs</strong>: These APIs focus on managing the geth node, the software that operates the Ethereum blockchain. For instance, the admin API facilitates node configuration, while the miner API manages mining activities.</li><li><strong>Web3 API</strong>: This API delivers methods specifically designed for DApp development. It encompasses the web3 object, the primary interface for blockchain interaction, as well as the eth and net objects for managing Ethereum addresses, transactions, and network information.</li></ul><p>The Web3 API stands as the cornerstone of DApp development, enabling developers to bridge their front-end applications to the blockchain and engage with the Ethereum ecosystem. The geth client establishes this connection by exposing an RPC endpoint using the RPC port command.</p><h4>JavaScript Encounters Blockchain: web3.js</h4><p>web3.js is a JavaScript library that streamlines web3 API utilization. Developers can instantiate a web3 object in their web page scripts, enabling them to make requests to the blockchain using its methods. These requests are transmitted in a JSON or RPC pipeline format between the web client and the geth client.</p><h3>Truffle Development</h3><h4>1. Truffle IDE</h4><p>Truffle is a one-stop IDE that simplifies the creation of decentralized applications (DApps) on the Ethereum blockchain. It offers a consistent workflow, providing everything from an initial application template to a local blockchain for testing the completed DApp.</p><h4>Designing Before Coding: A Structured Approach</h4><p>Before delving into the technical aspects of development, it’s essential to adopt a structured design methodology. Truffle carries out this approach by incorporating a four-step design process:</p><ol><li><strong>Defining Data and Operations</strong>: Clearly define the data structures and operations that your DApp will utilize.</li><li><strong>Implementing Modifiers and Validations</strong>: Ensuring data integrity is crucial. Introduce modifiers and validation checks to enforce rules specified in the problem definition.</li><li><strong>Designing Test Smart Contracts</strong>: Create test smart contracts to verify that all stated requirements are met. This serves as a form of unit testing.</li><li><strong>Incorporating Front-end Components</strong>: Once unit testing is complete, seamlessly integrate the front-end component and test the overall DApp. This represents integration testing.</li></ol><h4>Efficiently Initializing and Deploying DApps</h4><p>To start developing DApp, initialize a Truffle project using the truffle init command. This generates a boilerplate structure, including:</p><ul><li>contracts directory: Housing your Solidity smart contracts</li><li>migrations directory: Storing migrations, which are special contracts that manage changes to your DApp&#39;s smart contracts</li><li>test directory: Encompassing both JavaScript and Solidity tests for your smart contracts</li><li>truffle.js: Configuration file that specifies blockchain network details, such as network ID, IP address, and RPC port</li></ul><p><em>Development phase:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9SP2JHlbNfUT4GwJ" /></figure><p><em>Hint:</em></p><p>Truffle’s console provides an interactive command-line interface that enhances the development experience. You can interact with the accounts created on the test chain and access management APIs directly from the console.</p><h4>2. Test-Driven Development (TDD)</h4><p>Software testing is a crucial aspect of the development process, and it becomes even more essential when dealing with smart contracts, which form the core logic of decentralized applications (DApps).</p><h4>Why TDD is needed?</h4><p>Smart contracts resemble hardware chips in that they become immutable once deployed. They cannot be modified without implementing specific terms or exceptions, making testing a mandatory component of smart contract development. Truffle, in turn, supports both JavaScript and Solidity for testing.</p><p>Smart contract testing involves both positive and negative testing approaches. Positive testing ensures that the contract functions as expected when provided with valid inputs. Negative testing, on the other hand, verifies how the contract handles invalid inputs and unexpected scenarios.</p><h4>Testing Commands with Truffle</h4><p>Truffle provides a suite of commands for comprehensive testing:</p><ol><li>truffle compile: Compiles the smart contract code to ensure syntactical correctness</li><li>truffle migrate: Deploys the smart contracts to the Ethereum blockchain</li><li>--reset: Overwrites the previous version of the smart contract</li><li>truffle test: Executes the test suite to verify the contract’s behavior</li></ol><h4>3. Web interface and Testing</h4><p>A DApp’s web interface serves as the user-facing layer, enabling interaction with the application’s functionalities.</p><h4>Structure of a DApp Web Interface</h4><p>A DApp web interface typically follows a well-organized structure:</p><ul><li><strong>Source Directory</strong>: Housing web content, including JavaScript, CSS, and index HTML files.</li><li><strong>App.js</strong>: Initializing the necessary objects for the web client to interact with the blockchain.</li><li><strong>Test.js</strong>: Encapsulating test cases to ensure the web interface functions flawlessly.</li><li><strong>MetaMask Integration</strong>: Leveraging MetaMask, a browser extension, as a bridge between the blockchain server and the web interface.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2BgdhrFnB38h0Oo0" /></figure><h4>MetaMask: Facilitating Blockchain Communication</h4><p>MetaMask operates as a digital wallet, connecting users to the blockchain network and managing their accounts, transaction gas estimation, and balances. It also provides a user-friendly interface for signing transactions and providing gas fees.</p><h4>Local Testing with Truffle Develop</h4><p>Here are some key points to remember when using Truffle:</p><ul><li>The command truffle develop facilitates local deployment of a test network. The default port for this test chain is 9545.</li><li>Truffle’s truffle test command executes the test suite to verify the interface&#39;s behavior.</li><li>To deploy updated smart contracts, Truffle provides the truffle migrate --reset command. It effectively wipes the existing blockchain state and deploys the latest smart contract version.</li></ul><h3>Conclusion</h3><p>Truffle emerges as a beacon of simplicity and efficiency, guiding developers through the intricate world of decentralized application (DApp) development. Its comprehensive toolkit, coupled with a structured workflow, empowers developers to create innovative and secure DApps on the Ethereum blockchain. As the decentralized landscape expands, Truffle stands ready to empower developers to shape the future of a borderless and democratized digital world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5e14b98041a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/unleashing-the-potential-of-dapps-a-guide-to-development-with-truffle-c5e14b98041a">Unleashing the Potential of DApps: A Practical Guide to Truffle IDE</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development for Beginners: Building a Checkout Cart]]></title>
            <link>https://danillion.medium.com/test-driven-development-for-beginners-building-a-checkout-cart-bd17ba8d812d?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd17ba8d812d</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 13:54:39 GMT</pubDate>
            <atom:updated>2024-01-14T13:56:21.833Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will implement a simple Checkout Cart using the Test-Driven Development (TDD) method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*CtiA0DpdnJL6bQHM" /></figure><h3>Overview of Checkout class</h3><h4>1. Requirements</h4><p>Checkout Cart is a shopping cart that contains items that are being prepared for checkout. It will provide an interface to:</p><ul><li>Define prices for items.</li><li>Add items for checkout.</li><li>Calculate the current total value of the added items.</li><li>Allow multiple types of items to be added to the cart, and each item can have multiple copies.</li><li>If an item is added to the cart without a price, an error should be reported.</li></ul><h4>2. Methodology</h4><p>We will follow these steps:</p><ol><li>Identify the necessary test cases.</li><li>Implement the Checkout class to meet the test cases.</li><li>Retest the Checkout class.</li><li>Improve the source code.</li></ol><h4>3. Identifying the necessary test cases</h4><p>Based on the requirements, we can identify the following necessary test cases:</p><ul><li>Can create an instance of Checkout class</li><li>Can add item price</li><li>Can add item</li><li>Can calculate the current total</li><li>Can add multiple items and get correct total</li><li>Can add multiple items of each product and get correct total</li><li>Exception is thrown when adding item without price</li></ul><h3>Project setup and install libraries</h3><p>Create the project directory and install the mocha and chai libraries following the instructions below:</p><ol><li>Open the terminal, navigate to the directory dedicated to the subject, create a new directory if you don’t have one.</li><li>Initialize a new NodeJS project using the command npm init -y.</li><li>Install the mocha and chai libraries for the project using the command npm install --save-dev mocha chai.</li><li>Create two directories in the project directory, src (to contain class source code) and test (to contain test cases).</li></ol><h3>Implementing the Checkout class</h3><p>We will use the Red-Green-Refactor method to implement the Checkout class.</p><h4>1. Test case: Can create an instance of Checkout class</h4><p><em>Red phase:</em></p><ul><li>Create the checkout.spec.js file with the following content:</li></ul><pre>import { expect } from &#39;chai&#39;;<br><br>let checkout;<br><br>it(&#39;Can create an instance of Checkout class&#39;, () =&gt; {<br>  const checkout = new Checkout();<br>  expect(checkout).to.be.an.instanceOf(Checkout);<br>});</pre><ul><li>Run the test case, and the test case will fail (Red) because there is no source code for the Checkout class yet.</li></ul><p><em>Green phase:</em></p><ul><li>Create the checkout.js file with the following content:</li></ul><pre>export default class Checkout {<br>  constructor() {}<br>};</pre><ul><li>In the test case file, import the newly created Checkout class into the test case by adding the following line to the beginning of the file (library import area)</li></ul><pre>import Checkout from &quot;../src/checkout.js&quot;;</pre><ul><li>Run the test case again, and this time the test case will pass (Green).</li></ul><p><em>Hint:</em></p><ul><li>The content of the file checkout.spec.js at this time is as follows:</li></ul><pre>import { expect } from &#39;chai&#39;;<br>import Checkout from &quot;../src/checkout.js&quot;;<br><br>let checkout;<br><br>it(&#39;Can create an instance of Checkout class&#39;, () =&gt; {<br>  const checkout = new Checkout();<br>  expect(checkout).to.be.an.instanceOf(Checkout);<br>});</pre><h4>2. Test case: Can add item price</h4><p><em>Red phase:</em></p><ul><li>Add the following test case content:</li></ul><pre>it(&#39;Can add item price&#39;, () =&gt; {<br>  const checkout = new Checkout();<br>  checkout.addItemPrice(&#39;A&#39;, 50);<br>});</pre><ul><li>Run the test case, and the new test case will fail because the Checkout class does not yet have an addItemPrice function.</li></ul><p><em>Green phase:</em></p><ul><li>Add the following code to the Checkout class:</li></ul><pre>addItemPrice(item, price) {}</pre><ul><li>Run the test case again, and this time the test case will pass (even though we haven’t implemented the addItemPrice function yet).</li></ul><p><em>Refactor phase:</em></p><ul><li>We noticed that with each test case, we had to initialize an instance of the Checkout class and assign it to the checkout variable. Therefore, we used beforeEach() to optimize.</li><li>Add beforeEach to the test case file, and remove the initialization of Checkout at each test case just written.</li></ul><pre>beforeEach(() =&gt; {<br>  checkout = new Checkout();<br>});</pre><ul><li>Re-run the test cases to ensure that the test cases still pass.</li></ul><p><em>Hint:</em></p><ul><li>At this point, the checkout.js and checkout.spec.js files have the following contents, respectively:</li></ul><pre>export default class Checkout {<br>  constructor() { }<br>  addItemPrice(item, price) { }<br>};</pre><pre>import { expect } from &#39;chai&#39;;<br>import Checkout from &quot;../src/checkout.js&quot;;<br><br>let checkout;<br><br>beforeEach(() =&gt; {<br>  checkout = new Checkout();<br>});<br><br>it(&#39;Can create an instance of Checkout class&#39;, () =&gt; {<br>  const checkout = new Checkout();<br>  expect(checkout).to.be.an.instanceOf(Checkout);<br>});<br><br>it(&#39;Can add item price&#39;, () =&gt; {<br>  const checkout = new Checkout();<br>  checkout.addItemPrice(&#39;A&#39;, 50);<br>});</pre><h4>3. Test case: Can add item</h4><p>Implement the Red phase and Gren phase similarly to the above with this test case. Remember to re-run the test case after each phase:</p><p><em>Test case:</em></p><pre>it(&quot;Can add item&quot;, () =&gt; {<br>  checkout.addItemPrice(&quot;A&quot;, 50);<br>  checkout.addItem(&quot;A&quot;);<br>});</pre><p><em>Source code:</em></p><pre>addItem(item) { }</pre><h4>4. Test case: Can calculate the current total</h4><p>Continue implementingcRed-Green-Refactor:</p><p><em>Red phase:</em></p><ul><li>Write a test case with the following content:</li></ul><pre>it(&quot;Can calculate the current total&quot;, () =&gt; {<br>  checkout.addItemPrice(&quot;A&quot;, 50);<br>  checkout.addItem(&quot;A&quot;);<br>  expect(checkout.calculateTotal()).to.equal(50);<br>});</pre><ul><li>Run the test case, ensure the test case fails.</li></ul><p><em>Green phase:</em></p><ul><li>Implement the calculateTotal function by hardcoding the return value to 30.</li></ul><pre>calculateTotal() {<br>  return 30;<br>}</pre><ul><li>Run the test case again, this time the test case will pass.</li></ul><p><em>Refactor phase:</em></p><ul><li>At this point, we realize that the total variable will change when we call the addItem function, and it will change exactly by the price passed to the addItemPrice function. So we will use one variable to store the list of prices of the items, the total variable to store the total amount of money in the cart.</li><li>Before making any code changes, in the current test case, change the price of “A” to 50, run the test case again, and make sure the test case fails.</li><li>Proceed to add the following code snippets to the corresponding positions:</li></ul><pre>export default class Checkout {<br>  constructor() {<br>    this.prices = new Object();<br>    this.total = 0;<br>  }<br><br>  addItemPrice(item, price) {<br>    this.prices[item] = price;<br>  }<br><br>  addItem(item) {<br>     this.total += this.prices[item];<br>  }<br><br>  calculateTotal() {<br>    return this.total;<br>  }<br>};</pre><ul><li>Run the test case again, this time the test case will pass.</li></ul><h4>5. Test cases: Can add multiple items and get correct total</h4><p><em>Test cases:</em></p><ul><li>With the next two test cases, we will write test cases with the following content:</li></ul><pre>it(&quot;Can add multiple items and get correct total&quot;, () =&gt; {<br>  checkout.addItemPrice(&quot;A&quot;, 50);<br>  checkout.addItemPrice(&quot;B&quot;, 30);<br>  checkout.addItemPrice(&quot;C&quot;, 20);<br>  checkout.addItemPrice(&quot;D&quot;, 15);<br>  checkout.addItem(&quot;A&quot;);<br>  checkout.addItem(&quot;B&quot;);<br>  checkout.addItem(&quot;C&quot;);<br>  checkout.addItem(&quot;D&quot;);<br>  expect(checkout.calculateTotal()).to.equal(115);<br>});</pre><pre>it(&quot;Can add multiple items of each product and get correct total&quot;, () =&gt; {<br>  checkout.addItemPrice(&quot;A&quot;, 50);<br>  checkout.addItemPrice(&quot;B&quot;, 30);<br>  checkout.addItemPrice(&quot;C&quot;, 20);<br>  checkout.addItemPrice(&quot;D&quot;, 15);<br>  checkout.addItem(&quot;A&quot;);<br>  checkout.addItem(&quot;A&quot;);<br>  checkout.addItem(&quot;A&quot;);<br>  checkout.addItem(&quot;B&quot;);<br>  checkout.addItem(&quot;B&quot;);<br>  checkout.addItem(&quot;C&quot;);<br>  checkout.addItem(&quot;C&quot;);<br><br>  checkout.addItem(&quot;C&quot;);<br>  checkout.addItem(&quot;D&quot;);<br>  checkout.addItem(&quot;D&quot;);<br>  checkout.addItem(&quot;D&quot;);<br>  checkout.addItem(&quot;D&quot;);<br>  expect(checkout.calculateTotal()).to.equal(330);<br>});</pre><ul><li>Run the test case to ensure the test case passes.</li><li>As the two new test cases added, both of them passed on the first try, so we don’t need to update the source code.</li></ul><h4>6. Test case: Exception is thrown when adding item without price</h4><p>We continue implementing the Red-Green-Refactor.</p><p><em>Red Phase:</em></p><ul><li>Add a test case with the following content:</li></ul><pre>it(&quot;Exception is thrown when adding item without price&quot;, () =&gt; {<br>  expect(() =&gt; {<br>    checkout.addItem(&quot;A&quot;);<br>  }).to.throw();<br>});</pre><ul><li>Run the test case, ensure the test case fails.</li></ul><p><em>Green Phase:</em></p><ul><li>Edit by adding the following code to the beginning of the addItem function:</li></ul><pre>if (this.prices[item] === undefined) {<br>  throw &quot;No price for item &quot; + item;<br>}</pre><ul><li>Run the test case again, ensure the test case passes.</li></ul><h4>7. Improving the source code</h4><p>After retesting the Checkout class, we can improve the source code to optimize or enhance its features.</p><pre>export default class Checkout {<br>  constructor() {<br>    this.prices = new Object();<br>    this.items = new Object();<br>  }<br><br>  addItemPrice(item, price) {<br>    this.prices[item] = price;<br>  }<br><br>  addItem(item) {<br>    if (this.prices[item] === undefined) {<br>      throw &quot;No price for item &quot; + item;<br>    }<br>    if (this.items[item] === undefined) {<br>      this.items[item] = 1;<br>    } else {<br>      this.items[item]++;<br>    }<br>  }<br><br>  calculateTotal() {<br>    let total = 0;<br><br>    for (let item in this.items) {<br>      total += this.prices[item] * this.items[item];<br>    }<br><br>    return total;<br>  }<br>};</pre><h3>Conclusion</h3><p>This article has introduced how to implement a Checkout Cart using the TDD method. The TDD method helps us ensure the quality of our code and minimize errors during development.</p><p>For a more detailed look at the implementation of the Checkout Cart class, please visit the <a href="https://github.com/danillionbits/checkout-cart-tdd">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd17ba8d812d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development (TDD): A Comprehensive Guide to Clean Code and Predictability]]></title>
            <link>https://danillion.medium.com/test-driven-development-tdd-a-comprehensive-guide-to-clean-code-and-predictability-0e90c0c66530?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e90c0c66530</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 10:07:27 GMT</pubDate>
            <atom:updated>2023-12-30T10:07:27.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Test-driven development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LjRBomMzO52kttQx" /></figure><h4>Origins and Terminology</h4><p>Test-driven development (TDD) has revolutionized the software development landscape, and its roots can be traced back to Kent Beck’s seminal 2003 book, ‘Test-Driven Development: By Example.’ While Beck introduced the term ‘test-first development’ in 1999, it was the publication of this book that truly catapulted TDD into the mainstream.</p><p>The core principle of TDD is deceptively simple: write tests before you write the code that will make them pass. This seemingly straightforward approach has far-reaching implications for software development practices.</p><h4>Refactoring, Clean Code, and DRY</h4><p>To effectively grasp TDD, it’s essential to understand a few key terms:</p><ul><li><strong>Refactoring</strong>: This involves improving the internal structure of the code without changing its external behavior. It’s like giving your code a makeover without altering its functionality.</li><li><strong>Clean Code</strong>: Code that has undergone refactoring and embodies best practices. It’s easy to understand, maintain, and modify.</li><li><strong>DRY (Don’t Repeat Yourself)</strong>: A fundamental coding principle that emphasizes avoiding duplication in code. Refactoring is often employed to achieve DRY code.</li></ul><h4>Using TDD: Achieving Clean Code and Predictability</h4><p>TDD’s primary goal is to produce clean code that works as intended. By embracing this iterative approach, developers can reap numerous benefits:</p><ul><li><strong>Predictability</strong>: TDD fosters predictability, allowing developers to confidently move forward knowing that their code adheres to the desired behavior.</li><li><strong>Clear Finish Line</strong>: TDD provides a clear and definitive finish line — all tests passing consistently. This serves as a measurable milestone, ensuring code quality.</li><li><strong>Reduced Bugs</strong>: TDD’s emphasis on testing upfront discourages buggy code from entering the codebase, leading to fewer surprises.</li><li><strong>Safe Improvability</strong>: Clean, well-tested code is more amenable to modifications, making it easier to adapt to changing requirements.</li></ul><p>Adopting TDD instills confidence in developers, enabling them to take breaks or handle interruptions without disrupting their progress. The tests serve as a roadmap, guiding developers through the development process.</p><h4>Organization-Wide Benefits</h4><p>The benefits of TDD extend beyond individual developers and permeate entire organizations:</p><ul><li><strong>Reduced Reliance on Quality Assurance</strong>: TDD’s focus on early testing minimizes the burden on quality assurance teams, allowing them to focus on more complex issues.</li><li><strong>Improved Estimates</strong>: With fewer surprises, developers can provide more accurate estimates, enabling better project planning and customer involvement.</li><li><strong>Increased Collaboration</strong>: Smaller development cycles fostered by TDD promote frequent collaboration among developers.</li><li><strong>Rapid Code Deployment</strong>: Enhanced code quality enables frequent code deployments, seizing more customer opportunities.</li></ul><h4>TDD’s Adoption in Major Tech Giants</h4><p>Numerous tech giants, including Google, Facebook, Microsoft, and IBM, have embraced TDD, recognizing its potential to revolutionize software development practices. These companies have incorporated TDD into their development methodologies, reaping the benefits of improved code quality, reduced bugs, and increased developer productivity.</p><h3>Core Concepts of TDD</h3><h4>1. Clean-code and TDD Mantra</h4><h4>Key Principles of TDD</h4><ul><li><strong>Write Tests</strong>: TDD mandates writing tests that describe the desired behavior of the code before implementing it. These tests serve as a safety net, ensuring that new code conforms to requirements.</li><li><strong>Grow Code Incrementally</strong>: TDD encourages incremental development, building upon existing code and incorporating new features gradually. This approach fosters better understanding and maintainability of the codebase.</li><li><strong>Act Only on Red</strong>: TDD dictates that new code is written only if an existing test fails. This principle ensures that every change is thoroughly scrutinized and validated.</li><li><strong>Eliminate Code Duplication</strong>: TDD advocates for refactoring, which involves streamlining and simplifying the code to remove redundancies and improve readability.</li><li><strong>Demand Rapid Response</strong>: TDD requires an environment that provides quick feedback on code changes. This enables developers to detect and resolve issues promptly.</li></ul><h4>Essential Code Qualities</h4><p>TDD emphasizes writing code that adheres to specific qualities:</p><ul><li><strong>Testability</strong>: Code should be designed in a manner that facilitates automated testing. This allows for efficient test creation and maintenance.</li><li><strong>Cohesiveness</strong>: Code should be focused on a single purpose, avoiding unnecessary complexity and reducing the risk of side effects.</li><li><strong>Loose Coupling</strong>: Code should be independent of other modules, minimizing interdependencies and enhancing flexibility.</li></ul><h4>TDD Mantra: Red-Green-Refactor</h4><p>TDD practitioners follow the mantra “Red, Green, Refactor” to guide their development process:</p><ol><li><strong>Red</strong>: Create a test that fails, representing the desired behavior not yet implemented.</li><li><strong>Green</strong>: Write the minimum amount of code to make the test pass, even if it’s not the most elegant or maintainable solution.</li><li><strong>Refactor</strong>: Refine the code, improving its structure, clarity, and adherence to best practices, while preserving the test’s functionality.</li></ol><h4>2. How Test-driven Development works?</h4><p>Let’s examine the visual process of TDD through this diagram ‘The TDD Workflow’:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOSvxUnWv9XkUyNSnknMZA.png" /></figure><p>Another more detailed diagram for the process is illustrated as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3dujpEnufi324TsCF6OJA.png" /></figure><h4>3. Job of a Test-Driven Developer</h4><p>Test-driven developers play a crucial role in bridging the gap between business requirements and software development. Their primary responsibility lies in translating business goals into functional requirements, which are then translated into automated tests. This iterative approach ensures that the software being developed aligns with the specific needs of the business.</p><h4>The Four Levels of Testing</h4><p>To effectively assess the quality and functionality of software, test-driven developers adhere to a structured approach that encompasses four distinct levels of testing:</p><ol><li><strong>Unit Testing</strong>: Unit tests aim to verify the behavior of individual software components in isolation. They serve as the foundation for ensuring that the software’s building blocks are functioning correctly.</li><li><strong>Integration Testing</strong>: Integration testing focuses on validating interactions between multiple software components. It verifies that the components work together seamlessly as intended.</li><li><strong>System Testing</strong>: System testing evaluates the overall functionality and performance of the software system as a whole. It ensures that the system meets the specified requirements and can handle real-world scenarios.</li><li><strong>Acceptance Testing</strong>: Acceptance testing involves the customer or designated stakeholders evaluating the software from their perspective. It assesses whether the software meets their expectations and fulfills their business needs.</li></ol><h4>Unit Tests in Test-Driven Development</h4><p>TDD places a strong emphasis on unit tests, as they provide a fine-grained approach to testing individual components. By writing tests before implementing the code, TDD encourages developers to think about the desired behavior and design accordingly, leading to more robust and maintainable code.</p><p>While all TDD tests are unit tests, not all unit tests are TDD. TDD goes beyond writing unit tests; it encompasses the entire process of translating business requirements into functional requirements, designing and implementing code, and writing automated tests.</p><h4>Manual vs. Automated Testing</h4><p>Software testing encompasses both manual and automated testing. Manual testing involves executing tests manually, often by a human tester. Automated testing, on the other hand, utilizes scripts or frameworks to execute tests repeatedly and efficiently.</p><p>While manual testing is still valuable for certain types of testing, automated testing provides several advantages:</p><ul><li><strong>Repeatability</strong>: Automated tests can be run repeatedly without the need for human intervention, ensuring consistency and accuracy.</li><li><strong>Efficiency</strong>: Automated tests can be executed in parallel, reducing the overall testing time.</li><li><strong>Scalability</strong>: Automated tests can be easily scaled to accommodate larger codebases and increasing test volumes.</li></ul><p><strong>💡 Note: </strong>User interface (UI) testing can be challenging to automate due to the complexity of interacting with graphical elements and simulating user actions. However, advancements in automated testing tools and frameworks are making it increasingly feasible to automate UI tests.</p><h3>Conclusion</h3><p>Test-driven development (TDD) has emerged as a cornerstone of modern software development, providing a structured approach to producing high-quality, maintainable code. Its emphasis on testing, incremental development, and refactoring fosters predictability, enhances developer confidence, and promotes organization-wide benefits. By embracing TDD, developers can harness its power to create software that meets the needs of businesses and users alike.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e90c0c66530" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CryptoSims: Building a CryptoKitties Clone Made Simple]]></title>
            <link>https://medium.com/coinmonks/cryptosims-building-a-cryptokitties-clone-made-simple-ebe48d98ecc4?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe48d98ecc4</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 20:41:24 GMT</pubDate>
            <atom:updated>2023-11-03T09:16:24.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>From CryptoKitties to CryptoSims</h3><p><a href="https://www.cryptokitties.co/">CryptoKitties </a>is one of the world’s first blockchain games and an early form of NFT. It is a virtual cat breeding game where players breed a variety of cats called CryptoKitties and then exchange and trade them using virtual currency. These cats are one-of-a-kind and 100% owned by the players. They have different characteristics, with some being exceptionally rare, setting them apart from the rest. Most users attempt to breed or collect rare cats because they are highly valuable. Some particularly rare cats have been sold for over a hundred thousand dollars. In fact, the total sales of these cats amounted to approximately 3 million dollars in the first week after their launch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hcXp3Fj67CKdSI4Z.png" /></figure><p>Today, with standards like ERC20, ERC721, ERC1155, and, especially, open-source implementations of these standards like OpenZeppelin, developing a game similar to CryptoKitties has become easier than ever.</p><p>In this article, we will develop the smart contract for a simple collectible game on the Ethereum platform — The CryptoSims, inheriting from OpenZeppelin’s ERC721 standard implementation.</p><h3>Understading ERC-721</h3><p>According to the content of the standard, ERC721 defines a fundamental interface that a smart contract must implement to allow management, ownership, and exchange of unique, non-interchangeable tokens, often referred to as NFTs (Non-fungible tokens). This interface comprises:</p><ul><li>balanceOf(_owner) - Returns the number of tokens in the owner’s wallet.</li><li>ownerOf(_tokenId) - Returns the wallet address of the token&#39;s owner.</li><li>totalSupply() - Returns the total number of tokens that have been created.</li><li>transfer(_to, _tokenId) - Transfers a token from the sender&#39;s wallet to another wallet.</li><li>takeOwnership(_tokenId) - Receives ownership rights of a token.</li><li>approve(_to, _tokenId) - Approves another address to take ownership of the token.</li></ul><p>In addition, two events are defined:</p><ul><li>Transfer event is emitted when a token is transferred from one wallet to another.</li><li>Approval event is emitted when an entity (user) at an address approves another address to take ownership of the tokens owned by that entity.</li></ul><h3>OpenZeppelin ERC721</h3><p><a href="https://github.com/OpenZeppelin/openzeppelin-contracts">OpenZeppelin </a>offers reusable smart contracts and adheres to established standards such as ERC20 and ERC721. In this project, we’ll incorporate OpenZeppelin’s existing ERC721 smart contract implementation to avoid starting development process entirely from the ground up.</p><h3>Walkthrough of CryptoSims</h3><p>CryptoSims is an immersive virtual character game built on Smart Contracts. In this world, each virtual character, known as CryptoSim, is a unique creation solely possessed by a single user. Moreover, these captivating CryptoSims can be easily exchanged and shared among users, thanks to the versatile ERC721 standard.</p><h4>Rule #1</h4><p>Each CryptoSim is distinguished by an unchanging, distinctive ID. Moreover, every CryptoSim possesses a set of inherent traits defined within its “gene code,” which remains unalterable once created. These traits include:</p><ul><li>matronId, sireId: The identification codes of two CryptoSims used to create a new CryptoSim.</li><li>generation: The generation of the CryptoSim, calculated based on the generation of the two CryptoSims used for its creation (with a maximum of 255 generations). The first two CryptoSims (Genesis CryptoSims) have a generation of 0, with IDs of 0 and 1, respectively.</li><li>body: Defines the body shape and color (with 4 types).</li><li>eye: Defines eye style and color (with 8 types).</li><li>hairstyle: Defines hair style and color (with 128 types).</li><li>outfit: Defines clothing (with 32 types).</li><li>accessory: Defines additional accessories (with 32 types).</li><li>hiddenGenes: Defines hidden genes used to determine the inherited characteristics of future-generation CryptoSims.</li></ul><p>By combining all these characteristics, the entire CryptoSims universe can have various shapes and forms. In tandem with hidden genes, this can potentially produce over 16 billion unique combinations of CryptoSim.</p><h4>Rule #2</h4><p>There are three ways for players to own a Sim:</p><ul><li><strong>Purchase</strong>: Players receive a new CryptoSim, which is bred between the Genesis CryptoSim (CryptoSim #0) and the latest CryptoSim created. The cost of purchasing any CryptoSim is 0.02 Ether. This amount will be transferred to the main account (the CryptoSim deployment account).</li><li><strong>Breed</strong>: Players use two CryptoSims (knowing the IDs of both CryptoSims) to breed and create a new CryptoSim. Ownership of the newly created CryptoSim belongs to the breeder. The cost of breeding two CryptoSims is 0.05 Ether. This amount will be transferred to the main account (the CryptoSim deployment account).</li><li><strong>Transfer: </strong>Players can transfer CryptoSims according to the ERC721 protocol. The cost will be negotiated between the two players and transferred to the seller’s account.</li></ul><h4>Rule #3</h4><p>Creating new CryptoSims involves a special, isolated contract algorithm. This setup ensures that CryptoSims are both secure and truly random in their properties.</p><h4>Rule #4</h4><p>CryptoSims will be exported as images using the gene set stored in the smart contract. The gene code will be displayed as a 48x48 pixel graphic in a web app.</p><h4>Rule #5</h4><p>Owners can use CryptoSims as avatars for social media profiles or as in-game characters in The CryptoSims ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vSSJp7Hb6Jf5U8vs" /></figure><h3>Assumption for the project</h3><p>For simplification, the following assumptions will be applied in this project:</p><ol><li>Only the smart contract implementation will be realized. The actual image rendering will be handled by an existing website to make it easier for development and testing.</li><li>The process of purchasing and breeding CryptoSims is free. The transfer of CryptoSims will be performed by executing commands in Remix IDE.</li><li>The breeding algorithm will be implemented within the main smart contract (instead of a separate smart contract), and the breeding algorithm will be defined in a later section.</li></ol><h3>Breeding algorithm to create 2 CryptoSims</h3><h4>Rule #1</h4><p>Determine a pair of CryptoSims, namely the Matron (M) and Sire (S), used to create a new CryptoSim (N).</p><h4>Rule #2</h4><p>Determine the hidden gene (hiddenGene — x):</p><ul><li>If xM = xS, then x = (xM * xS + 3) % 4.</li><li>If xM &gt; xS, then x = xM.</li><li>If xM &lt; xS, then x = xS.</li></ul><h4>Rule #3</h4><p>Based on the hidden gene (x), calculate the remaining indices according to the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jh33gf3m9zSMkPLZ-O_jOQ.png" /></figure><h3>Code implementation</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d298133515271923496137ac56f126ab/href">https://medium.com/media/d298133515271923496137ac56f126ab/href</a></iframe><h3>Advanced solution: Optimizing data storage</h3><p>Optimizing data storage capacity on a smart contract is extremely important. In the basic exercise part, each property of CryptoSim is stored in individual uint8 variables.</p><p>Advanced requirement: optimize by using only the uint32 variable “genes” to store all properties in the following order: Generation, HiddenGene, Body, Eye, Hairstyle, Outfit, Accessory.</p><h4>Encoding attributes</h4><p>We will implement encoding using two operations:</p><ul><li>Bitwise OR (|) Operation: The | operator is used to combine two binary numbers by performing a logical OR operation on each pair of corresponding bits.</li><li>Bitwise Left Shift (&lt;&lt;) Operation: The &lt;&lt; operator is used to shift the bits of a binary number to the left by a specified number of positions.</li></ul><p>In details, suppose you have a SimAttributes structure with the following attributes (values are represented in binary for clarity):</p><ul><li>attributes.body: 5 (in binary, 0101, 4 bits)</li><li>attributes.eye: 6 (in binary, 110, 3 bits)</li><li>attributes.hairstyle: 93 (in binary, 1011101, 7 bits)</li><li>attributes.outfit: 13 (in binary, 01101, 5 bits)</li><li>attributes.accessory: 20 (in binary, 10100, 5 bits)</li><li>attributes.hiddenGenes: 2 (in binary, 10, 2 bits)</li><li>attributes.generation: 229 (in binary, 11100101, 8 bits)</li></ul><p>You want to encode these attributes into a single uint32 variable called genes. Here&#39;s how it&#39;s done:</p><ol><li>Initialize genes as a uint32 with all bits set to 0 (32 bits in total).</li><li>Encode attributes.body (5) into genes: genes = 0 | 0101 = 0101.</li><li>Encode attributes.eye (6) into genes: genes = 0101 | (110 &lt;&lt; 2) = 0101 | 1100 = 1001.</li><li>Encode attributes.hairstyle (93) into genes: genes = 1001 | (1011101 &lt;&lt; 5) = 1001 | 101110100000 = 100110111001.</li><li>Encode attributes.outfit (13) into genes: genes = 100110111001 | (01101 &lt;&lt; 12) = 100110111001 | 011010000000 = 100110111001.</li><li>Encode attributes.accessory (20) into genes: genes = 100110111001 | (10100 &lt;&lt; 17) = 100110111001 | 1010000000000 = 100110111001.</li><li>Encode attributes.hiddenGenes (2) into genes: genes = 100110111001 | (10 &lt;&lt; 22) = 100110111001 | 100000000000000 = 100110111001.</li><li>Encode attributes.generation (229) into genes: genes = 100110111001 | (11100101 &lt;&lt; 24) = 100110111001 | 1110010100000000000000 = 111111111100110111001.</li></ol><p>The final value of genes is 100110111001 in binary, which is a compact representation of all the attributes in a single uint32 variable. This allows for efficient storage of multiple attributes in a blockchain smart contract, saving space and reducing storage costs.</p><h4>Decoding attributes</h4><p>We will implement decoding using two operations:</p><ul><li>Bitwise AND (&amp;) Operation: The &amp; operator is used to perform a logical AND operation on each pair of corresponding bits in two binary numbers.</li><li>Bitwise Right Shift (&gt;&gt;) Operation: The &gt;&gt; operator is used to shift the bits of a binary number to the right by a specified number of positions.</li></ul><p>In detail, let’s decode the previously encoded genes value (100110111001) back into the individual attribute values:</p><ol><li>Initialize a SimAttributes structure with default values for all attributes.</li><li>Decode attributes.body (4 bits) from genes: attributes.body = uint8(genes &amp; 0x3); // binary 11.</li><li>Decode attributes.eye (3 bits) from genes: attributes.eye = uint8((genes &gt;&gt; 2) &amp; 0x7); // binary 111.</li><li>Decode attributes.hairstyle (7 bits) from genes: attributes.hairstyle = uint8((genes &gt;&gt; 5) &amp; 0x7F); // binary 1111111.</li><li>Decode attributes.outfit (5 bits) from genes: attributes.outfit = uint8((genes &gt;&gt; 12) &amp; 0x1F); // binary 11111.</li><li>Decode attributes.accessory (5 bits) from genes: attributes.accessory = uint8((genes &gt;&gt; 17) &amp; 0x1F); // binary 11111.</li><li>Decode attributes.hiddenGenes (2 bits) from genes: attributes.hiddenGenes = uint8((genes &gt;&gt; 22) &amp; 0x3); // binary 11.</li><li>Decode attributes.generation (8 bits) from genes: attributes.generation = uint8((genes &gt;&gt; 24) &amp; 0xFF); // binary 11111111.</li></ol><p>The resulting SimAttributes structure now contains the individual attribute values that were originally encoded into the genes value. This decoding process efficiently extracts the attributes from the compact uint32 variable, allowing you to work with the individual attribute values.</p><h4>Example code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74c7e0be03fdd47e7f9ac31099cd8b89/href">https://medium.com/media/74c7e0be03fdd47e7f9ac31099cd8b89/href</a></iframe><h3>Conclusion</h3><p>I trust you’ve had an enjoyable experience checking out this project. Thanks to standards such as ERC721 and readily available open-source tools, the creation and enjoyment of digital collectibles have become more accessible than ever. With CryptoSims, you have the opportunity to own, breed, and trade these efficiently encoded virtual characters, so feel free to customize the code to your liking and craft your very own CryptoSim Smart Contract.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe48d98ecc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/cryptosims-building-a-cryptokitties-clone-made-simple-ebe48d98ecc4">CryptoSims: Building a CryptoKitties Clone Made Simple</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Tests Cheat Sheet for Paging Library and Room Database — Kotlin made simpler]]></title>
            <link>https://danillion.medium.com/unit-tests-cheat-sheet-for-paging-library-and-room-database-kotlin-made-simpler-91566d695fe8?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/91566d695fe8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 11:46:54 GMT</pubDate>
            <atom:updated>2023-10-25T13:50:07.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin 101: Unit Tests Cheat Sheet for Paging Library and Room Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*Xto8jdYym7U5aBGm.jpg" /></figure><p>Recently, I started a new job as a mobile developer. My first assignment: write unit tests for an application that leveraged Paging Library. If you’re unfamiliar with this powerful tool, you can delve deeper into its info here: <a href="https://developer.android.com/topic/libraries/architecture/paging/v3-overview">Paging Library Overview</a>.</p><p>To give you a quick snapshot, the Paging Library is an integral part of Android’s Architecture Components, designed to streamline the handling of large datasets in a mobile application. While it indeed interfaces with the RecyclerView, it goes well beyond simple extension. What truly distinguishes it is the intricately engineered approach it adopts for data management. Here’s a breakdown of how it operates:</p><ul><li><strong>Efficient Data Retrieval</strong>: The Paging Library is designed to lessen the burden on the backend server. In situations with a limited user base, data retrieval may seem straightforward. However, when the user count scales up, the strain on the backend becomes evident. By systematically fetching data and storing it locally, we reduce the demand on the server, making the application more scalable and responsive.</li><li><strong>Enhanced User Experience</strong>: Waiting for data to load is a common frustration for users. The Paging Library addresses this by ensuring that users don’t have to endure lengthy loading times. Data stored in the local Room database is readily available, resulting in a faster, more seamless user experience.</li><li><strong>Optimized Network Connectivity</strong>: In addition to alleviating server strain, the library enhances network efficiency. By storing data locally, the application minimizes the need for frequent network requests. This not only conserves bandwidth but also ensures a smoother experience for users, especially in areas with limited connectivity.</li><li><strong>Offline Accessibility</strong>: One of the most significant advantages of employing Room for data storage is the potential for complete offline functionality. In the event of server downtime, users can continue to access data seamlessly from the local database.</li></ul><p>Now that you’ve got a handle on how the application’s main interface looks like, a significant question arises: “How do you write unit tests for fetching and storing data in the Room Database”?</p><h3>Database</h3><p>For the purpose of testing, it’s a good practice to set up an in-memory version of your database. This approach offers several advantages, including:</p><ul><li><strong>Isolation</strong>: In-memory databases allow you to keep your tests completely isolated from the actual data stored on the device. This ensures that your tests don’t accidentally affect or rely on real data.</li><li><strong>Speed</strong>: In-memory databases are considerably faster to work with in a testing context. They don’t involve disk I/O, which can be a performance bottleneck, making your tests more efficient.</li><li><strong>Predictability</strong>: With an in-memory database, you can easily set up a known state for your tests. You can pre-populate it with specific data to simulate various scenarios and ensure consistent and predictable test outcomes.</li></ul><p>Here’s a simple example of how to create an in-memory database for your tests:</p><pre>class CarTest {<br>    private lateinit var carDao: CarDao<br>    private lateinit var db: TestDatabase<br><br>    // Set up the in-memory database before each test.<br>    @Before<br>    fun createDb() {<br>        val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()<br><br>        // Create an in-memory test database.<br>        db = Room.inMemoryDatabaseBuilder(<br>                context, TestDatabase::class.java).build()<br>        carDao = db.getCarDao()<br>    }<br><br>    // Close and release the test database after each test.<br>    @After<br>    @Throws(IOException::class)<br>    fun closeDb() {<br>        db.close()<br>    }<br>}</pre><h3>Unit tests</h3><p>Now, when it comes to testing, there are three types of returned values that I need to take into consideration:</p><h4>1. PagedResource</h4><blockquote>PagedResource is a versatile data structure optimized for managing paged data within the Android Paging Library. Configured via the store function, it encapsulates key attributes, including a Flow for observing paged data, data refresh functions, and an indicator for data emptiness.</blockquote><pre>data class PagedResource&lt;Type, QueryParameters&gt;  (<br>    // A Flow of paged data, ready for UI observation.<br>    val resource: Flow&lt;PagingData&lt;Type&gt;&gt;,<br>    // Initiates a full data refresh from the source.<br>    val refresh: (QueryParameters) -&gt; Unit,<br>    // Enforces a complete data refresh, regardless of the page size configuration.<br>    val refreshAll: suspend (QueryParameters) -&gt; Unit,<br>    // Indicates if the paged list is currently empty.<br>    val isEmpty: Flow&lt;Boolean&gt;<br>) where Type: Any, Type: Identifiable</pre><p>To ensure the data in UI aligns with expectations, you can make use of the paging-testing dependency along with the asSnapShot() extension for PagedResource flows. This extension equips you with convenient APIs within a lambda receiver, enabling you to simulate interactions like refreshing or scrolling. As these interactions generate a list of Values, you can confidently confirm that your UI is operating as intended.</p><p>There are other layer tests available, as can be found <a href="https://developer.android.com/topic/libraries/architecture/paging/test">here</a>. In our project, however, we’ve found that concentrating on UI layer testing suffices already, following this approach:</p><pre>fun shouldFetchAllCars() = runTest {<br>    // Logic function for remote and local calls<br>    val call: PagedResource&lt;Car, Unit&gt; = store.cars.all(pageSize = 10)<br>  <br>    val itemsSnapshot: List&lt;Car&gt; = call.resource.asSnapshot {<br>        refresh()<br>    }<br>  <br>    // With the asSnapshot complete, you can now verify that the snapshot<br>    // has the expected values<br>    Assert.assertFalse(&quot;No cars were fetched&quot;, itemsSnapshot.isEmpty())<br>}</pre><h4>2. ListResource</h4><blockquote>ListResource is a data structure and utility designed to efficiently manage and observe non-paginated lists of data within your application. It provides a Flow of lists, making it ideal for scenarios where data doesn’t need to be retrieved in pages.</blockquote><p>In contrast to <strong>PagedResource</strong>, which is tailored for managing paged data using the Paging Library, <strong>ListResource</strong> focuses on non-paginated lists. The key distinctions include the type of data they handle, with ListResource dealing with lists of data List&lt;Type&gt;, while PagedResource works with paged data via PagingData&lt;Type&gt;. Moreover, ListResource introduces the networkState feature to track network request statuses, which isn’t present in PagedResource.</p><pre>data class ListResource&lt;Type, QueryParameters&gt;(<br>    // A Flow of lists, ready for UI observation.<br>    val resource: Flow&lt;List&lt;Type&gt;&gt;,<br>    // A Flow representing network request status, providing user feedback.<br>    val networkState: Flow&lt;NetworkState&gt;,<br>    // A function to trigger a complete data refresh from the source.<br>    val refresh: (QueryParameters) -&gt; Unit<br>) where Type: Any, Type: Identifiable</pre><h4>UnconfinedTestDispatcher</h4><blockquote>A specialized dispatcher used in testing scenarios with the Kotlin Coroutines library. Some key features of it includes:</blockquote><ul><li>Similar to Dispatchers.Unconfined but skips delays for predictability.</li><li>Convenient for testing where specific thread management isn’t required.</li><li>Ensures prompt execution of launch and async blocks in runTest.</li><li>Valuable for quickly launching and resuming child coroutines in tests, especially for Channel and StateFlow.</li></ul><p><strong>💡 Note:</strong><em> </em>UnconfinedTestDispatcher is designed for testing functionality with predictable execution order, simplifying scenarios where <em>precise control isn’t necessary</em>. For further details, you can find additional information <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-test/kotlinx.coroutines.test/-unconfined-test-dispatcher.html">here</a>.</p><p>In the context of writing unit tests, the UnconfinedTestDispatcher is a valuable tool for integration with the Paging Library. The test scenario involves calling a function to retrieve a list of values from store, with the fetched data being observed using a CompletableDeferred.</p><pre>fun shouldFetchCarsWithoutPaging() = runTest {<br>    // Logic function for remote and local calls<br>    val call = hybridStore.cars().allList(pageSize = 10)<br>    val deferred = CompletableDeferred&lt;List&lt;Car&gt;&gt;()<br><br>    // Launch a coroutine to collect and complete data for testing.<br>    val job = launch(UnconfinedTestDispatcher(testScheduler)) {<br>        call.resource.collect { list -&gt;<br>            deferred.complete(list)<br>        }<br>    }<br><br>    // Wait for the data to be fetched and cancel the job when done.<br>    val cars = deferred.await()<br>    job.cancel()<br><br>    Assert.assertFalse(&quot;No cars were fetched&quot;, cars.isEmpty())<br>}</pre><h4>3. SingleResource</h4><blockquote>SingleResource serves as a versatile utility for handling and observing individual pieces of data. It offers a Flow that provides access to a single data item, which can be efficiently observed by the user interface. Additionally, it optionally includes a Flow for remote data, which can be valuable in cases where local caching is not needed or desired.</blockquote><p>In comparison to ListResource, <strong>SingleResource</strong> is basically the same but tailored for scenarios where you’re working with single pieces of data rather than lists. While <strong>ListResource</strong> handles Flow of list, SingleResource provides a Flow of a single data item.</p><pre>data class SingleResource&lt;Type, QueryParameters&gt;(<br>    // A Flow for observing a single data item.<br>    val resource: Flow&lt;Type?&gt;,<br>    // Optional Flow for remote data when local caching is unnecessary.<br>    val remoteResource: Flow&lt;Type?&gt;?,<br>    // Network request status for user feedback.<br>    val networkState: Flow&lt;NetworkState&gt;,<br>    // Function to trigger a full data refresh from the source.<br>    val refresh: (QueryParameters) -&gt; Unit<br>) where Type: Any</pre><p>Creating unit tests for <strong>SingleResource</strong> follows the same approach as that for <strong>ListResource</strong>, with the only distinction being in using CompletableDeferred for a single value instead of a list:</p><pre>fun shouldFetchCarById() = runTest {<br>    // Logic function for remote and local calls<br>    val call = store.cars().car(id= 15, pageSize = 10)<br>    val deferred = CompletableDeferred&lt;Car?&gt;()<br><br>    // Launch a coroutine to collect and complete data for testing.<br>    val job = launch(UnconfinedTestDispatcher(testScheduler)) {<br>        call.resource.first()<br>        call.resource.collect { it -&gt;<br>            deferred.complete(it)<br>        }<br>    }<br><br>    // Wait for the car data to be fetched and cancel the job when done.<br>    val car = deferred.await()<br>    job.cancel()<br>    Assert.assertNotNull(&quot;No car was fetched&quot;, car)<br>}</pre><h3>Conclusion</h3><p>I hope that this article has proven to be a valuable resource for your unit testing trials. While it may not encompass every conceivable testing scenario, it should have provided you with a solid grasp of the fundamentals. Armed with this newfound knowledge, you’ll find that writing unit tests becomes a more approachable and less daunting aspect of your development work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91566d695fe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Insights into Object-Oriented Programming Concepts]]></title>
            <link>https://danillion.medium.com/essential-insights-into-object-oriented-programming-concepts-433b601424b?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/433b601424b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 12:38:50 GMT</pubDate>
            <atom:updated>2023-08-15T12:38:50.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OWCX6fmxrHPY6FJR" /></figure><h3>Intro to Object-Oriented Concepts and Design</h3><h4>1. Essence of Object-Oriented Technology</h4><blockquote>“OO technology” encompasses languages, frameworks, and tools shaping Object-Oriented programming. It transforms code into tangible entities called objects, each with unique attributes and behaviors.</blockquote><p>At the core of OO technology is Object-Oriented Programming (OOP). It structures code around real-world elements, enhancing reusability and manageability. Objects encapsulate data and behavior, managing complexity effectively.</p><h4>2. Historical Footprints</h4><ul><li>Rooted in pioneering languages, OO technology traces back to <strong>Simula’s</strong> introduction of classes and objects. <strong>Smalltalk </strong>elevated OOP with dynamic typing and object-centric development.</li><li>Prominent languages like C++, Java, Angular, Python, and C# dominate OO programming, each excelling in specific areas.</li><li><strong>Unified Modeling Language (UML) </strong>serves as a practical tool for designing OO systems. Its diagrams illuminate relationships, aiding well-structured designs.</li></ul><h4>3. Designing for Object-Oriented Programming</h4><blockquote>OOAD, short for Object Oriented Analysis and Design, is a pivotal process. It revolves around crafting software solutions by dissecting problems into tangible objects and designing their interactions. This systematic approach ensures robust, maintainable, and efficient systems.</blockquote><p>The S.O.L.I.D principles encapsulate a set of guidelines for robust Object-Oriented design:</p><ul><li><strong>Single Responsibility Principle (SRP)</strong>: Each class should have only one responsibility.</li><li><strong>Open/Closed Principle (OCP)</strong>: A class should be open for extension but closed for modification.</li><li><strong>Liskov Substitution Principle (LSP)</strong>: Subtypes must be substitutable for their base types.</li><li><strong>Interface Segregation Principle (ISP)</strong>: Clients should not be forced to depend on interfaces they do not use.</li><li><strong>Dependency Inversion Principle (DIP)</strong>: High-level modules should not depend on low-level modules. Both should depend on abstractions.</li></ul><h4>4. Fundamental Concepts of OOP</h4><p>In object-oriented programming, there are several key concepts that form the foundation of the approach:</p><ul><li><strong>Objects</strong>: Objects are individual building blocks that make up our solutions.</li><li><strong>Inheritance</strong>: We can create hierarchical structures of types using inheritance.</li><li><strong>Liskov Substitution Principle</strong>: With specialized classes or subclasses inheriting from a common superclass, we can substitute any of these specialized classes whenever the client references the superclass.</li><li><strong>Refactoring</strong>: Refactoring is the process of reorganizing object representation, analysis, design, and programming to adjust common characteristics that lead to hierarchy and inheritance usage.</li><li><strong>Encapsulation</strong>: Encapsulation involves packaging data and code together not only into a unified entity but also hiding the data and code behind an interface.</li><li><strong>Messages</strong>: Messages are used to invoke behavior on an object and send messages from one object to another, requesting the object to execute a specified or identified code.</li></ul><h4>5. Structured methodology vs Object-Oriented methodology</h4><h4>Waterfall Model</h4><blockquote>The Waterfall model is a well-known structured methodology in software development. It follows a sequential approach, where each phase is completed before moving on to the next one.</blockquote><p>While the Waterfall model offers a clear process, it comes with some trade-offs. Extensive time is dedicated to planning, analysis, design, and implementation. This extended timeline makes it challenging to predict delivery dates accurately and may not align with the demand for rapid development.</p><h4>Four Life Cycle Phases</h4><ul><li><strong>Inception Phase:</strong> In the inception phase, the project’s objectives and plan are established. All stakeholders collaborate to define a cohesive project plan that aligns with the envisioned outcomes.</li><li><strong>Elaboration Phase:</strong> During the elaboration phase, the focus is on understanding the system’s functionalities. Use cases are developed to outline what the system should accomplish under various scenarios, involving relevant stakeholders.</li><li><strong>Construction Phase: </strong>The construction phase emphasizes the creation of a robust architecture. Activities are fine-tuned, interaction diagrams are refined, and class diagrams are developed, laying the groundwork for implementation.</li><li><strong>Transition Phase:</strong> The transition phase shifts the focus towards system deployment. Resource utilization is evaluated to ensure a seamless deployment process without resource constraints.</li></ul><p>Each phase can involve one or multiple iterations, depending on various factors. Evaluation occurs at the end of each iteration to assess progress and determine the need for further iterations.</p><h4>Comparing the Waterfall Model and Modern Iterative Approach</h4><p>The Waterfall model is characterized by its structured process, following a linear path through multiple phases, with each phase dedicated to a single aspect.</p><p>On the other hand, the modern iterative approach, often used in Object-Oriented Programming, is designed for early delivery, user acceptance, and rapid feedback.</p><h3>Understanding Core Object-Oriented Programming Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*wyUiYHP4YMKJt1S3.png" /></figure><h4>1. Classes / Objects</h4><ul><li>Programmers create classes using OOP syntax. A class serves as a blueprint, defining an object’s structure and behavior.</li><li>Classes offer reusability. They can be utilized at runtime to create multiple instances or individual objects as needed.</li><li>Instances are dynamic entities created from classes. Each instance has its memory allocation, preserving its state.</li></ul><h4>2. Message &amp; Behavior</h4><ul><li>In OOP, objects invoke behaviors on other objects by sending messages. This concept drives interactions between entities in the system.</li><li>In modern Object-Oriented programming languages, invoking a method is akin to calling a function. This action triggers the execution of the associated behavior within the object.</li></ul><h4>3. Relationships</h4><p>During development, relationships are established between classes and instances. Even before formal design methodologies, the concepts of “is-a” and “has-a” relationships were inherent in Object-Oriented programming.</p><h4>Collaboration and Association</h4><p>Collaboration involves interaction among different classes to accomplish tasks. Association is a form of relationship, and a set is a specific type of association.</p><h4>Aggregation vs. Composition</h4><p>Aggregation represents a specific type of association where an object has a reference to another object. This relationship is often referred to as “has-a” in the Object-Oriented programming community.</p><p>Aggregation implies that if the owner object is destroyed, the owned object doesn’t necessarily get destroyed. Composition, on the other hand, means that if the owner object is destroyed, the owned object is also destroyed.</p><p>💡 Note<em>: </em>To differentiate between aggregation and composition, consider whether destroying the owner object implies destroying the owned object. If the owned object can exist independently, it’s aggregation; if its existence is tied to the owner’s, it’s composition.</p><h4>4. Encapsulation</h4><ul><li>Encapsulation involves hiding details within objects, exposing only an interface while preventing direct access to data from other classes.</li><li>Encapsulation empowers us to freely modify a class’s internal structure while keeping its interface intact. Data and method code are concealed, with only the interface visible and accessible from external code.</li></ul><h4>5. Inheritance</h4><ul><li>Inheritance establishes a relationship between a parent class and a child or subclass. All attributes of parent classes are inherited by their children, becoming progressively more specialized as we move from parent to child, and even further to grandchildren.</li><li>The term “is-a” captures the essence of inheritance. Inheritance signifies that all attributes of the parent class hold true for all its child classes.</li><li>Inheritance ensures that a parent class’s attributes are shared among all its child classes. The needs of a parent class are fulfilled by all child classes, but the reverse is not necessarily true.</li></ul><h4>6. Polymorphism</h4><ul><li>Polymorphism refers to the ability to use a common interface across diverse objects. Different object types can implement the same interface in distinct ways.</li><li>Multiple object types can implement the same interface with varying implementations. The client sends a message to the interface, and the recipient handles it through code linkage.</li><li>The transmitted code doesn’t concern itself with the recipient’s specific type; it’s only important that the recipient supports the message.</li><li>Polymorphism manifests differently in various programming languages. Object-oriented languages can be categorized into runtime-dispatch languages and statically-typed languages.</li></ul><h3>Creating a Visual Model using UML</h3><h4>1. Exploring Visual Modeling</h4><p>Visual models are essential for understanding complex systems, such as object-oriented ones. They simplify reality, aiding comprehension as we transition from the current to the desired system state. These models act as proxies, representing software components and capturing crucial real-world concepts. While precision varies among models, our overview of UML will explore different types, each providing unique insights into the intricate world of object-oriented programming and design.</p><h4>2. Unified Modeling Language</h4><blockquote>UML, or Unified Modeling Language, is a visual graphic language used to model various components and interactions within a software system.</blockquote><p>In 1994, Grady Booch, James Rumbaugh, and Ivar Jacobson successfully merged different methodologies into a single graphical modeling language, UML.</p><p>Today, UML remains a widely accepted industry standard. It serves as a visual language enabling us to analyze, document, build, and comprehend software systems. Developed by capitalizing on strengths and addressing weaknesses, UML is a powerful tool though it still strives for perfection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U_5cecuGItdDqE9e.png" /><figcaption>Example of a UML Diagram Created Using <a href="https://app.diagrams.net/">draw.io</a></figcaption></figure><h4>3. Key Aspects of UML Unveiled</h4><p>UML delineates two primary class diagrams: structural diagrams, portraying the static composition of system components, and behavioral diagrams, capturing operational or runtime facets of the system.</p><p>Class diagrams unveil the essence and components of classes, encompassing class names, attributes, and methods. These diagrams also illustrate inheritance and aggregation relationships. Package diagrams elucidate relationships between groups of classes.</p><p>Composite structure diagrams allow us to scrutinize interactions between services at a higher level of component interaction.</p><p>BPMN (Business Process Model and Notation) stands as a robust standard for symbolizing and modeling business processes, maintained by an object management group.</p><p>UML state diagrams visually manage intricate complexities by amalgamating multiple states into coherent visual components. UML also supports concurrent states, allowing multiple states to function simultaneously.</p><h4>4. UML Class Diagram</h4><p>UML class diagrams stand as one of the most commonly used diagram types, with class diagrams being the backbone of this category. The only other type that frequently emerges is UML sequence diagrams. Class diagrams capture the relationships between classes and their collaborators, establishing connections among their instances at runtime.</p><h4>Connections and Relationships</h4><p>The interconnections in class diagrams are depicted through lines connecting classes. Various types of links, such as inheritance and aggregation, signify different relationships between classes.</p><p>One crucial concept in this context is Multiplicity, representing the quantity of associations — an essential notion to comprehend when transitioning to diverse functionalities (with the default being one).</p><h4>Understanding Relationships</h4><p>Within class diagrams, relationships like Aggregation indicate that two objects have a “has-a” relationship. However, the destruction of the owning object doesn’t necessarily imply the destruction of the owned object.</p><p>Inheritance, another form of linkage, signifies that subclasses inherit all attributes and behaviors from their parent class. By grasping the nuances of these relationships, developers can construct accurate and insightful class diagrams that enhance their understanding of complex software structures.</p><h3>Developing Object-Oriented Programming</h3><h4>1. Transitioning from Design to Code</h4><p>In practice, each use case must lead to corresponding tests, forming the foundation for thorough testing. Adopting a test-driven development approach encourages leveraging visual models to facilitate communication. As object-oriented designers, we should focus on reusing existing classes and assessing the creation of new ones for potential reusability.</p><h4>A Test-Driven Journey</h4><p>One way to delineate a test-driven development journey is by starting with writing tests based on use cases. For each new test, as we write the accompanying code and develop it to pass that test, we view the process as an iterative step forward. This iterative cycle fosters a methodical progression, ensuring that code remains robust and functionality is systematically verified.</p><h4>2. Transitioning from Use Case to Design</h4><p>A well-structured use case culminates in a detailed use case diagram that delineates the steps, actions, and activity diagram of the scenario. High-level interaction diagrams are crafted based on the interactions identified within the use case description.</p><h4>Striking a Balance</h4><p>It’s essential to strike a balance between fully defined designated concepts and the flexibility required for programming. Overemphasizing predefined notions without accommodating programming adaptability could inadvertently lead to a waterfall approach, impeding agility.</p><h4>Avoiding Premature Development</h4><p>Avoiding scenarios where coding precedes testing is crucial. Utilizing use cases as a foundation, we pinpoint the tests required to validate each scenario. These tests drive the development of classes and methods tailored to fulfill the demands of each use case.</p><h4>3. Defining Classes</h4><p>Beyond a class’s name, the next natural focus is on its methods. These methods are unveiled by examining sequence diagrams, communication diagrams, activity diagrams, and state machine diagrams. Real-world data must remain private, except for showcased constants. All data types must be given meaningful names and types.</p><h4>Supporting Test-Driven Programming</h4><p>For test-driven development, maximum deployment is aimed at transforming a “Fail” into a “Pass.” UML supports the concept of visibility similar to Java. When programming with a test-driven approach, we can officially recognize reuse and inheritance as part of the restructuring phase following testing.</p><h4>Holistic Data Gathering</h4><p>A comprehensive class diagram draws from various UML diagrams to gather the information needed. “Public” provides a documented interface for a class, while “private” encapsulates a class’s internal implementation. In UML, public attributes can be visualized as public data.</p><h4>4. Distributed Processing &amp; Distributed Components</h4><h4>Distributed Processing</h4><p>Distributed processing involves physically partitioning elements of a solution across multiple computers. The term “client-server” is broadly applicable to various use cases, with client-server processing being one of the most prevalent forms of distributed processing.</p><p>Typically, the client system is less powerful compared to the server system. In a Three-Tier solution, we have a client, a customized application logic layer on the server side, and a shared data layer on the server side.</p><p>In contrast, peer-to-peer structures differ from asymmetric interaction and emphasize symmetrical relationships. In modern service-oriented architectures, including microservices, relationships truly manifest as n-tier configurations. These distributed approaches optimize performance and resource utilization across a network of interconnected components.</p><h4>Component Architectures</h4><p>A component is an object that can be automatically composed at runtime with other components to form a solution. Components are objects hidden behind an interface.</p><p>Modern component architectures are often built around the concept of managed containers. These containers are responsible for providing a range of services that components can rely on when accessed within that environment.</p><h4>Distributed Components</h4><p>Distributed Components involve creating reusable and language-independent components that can be executed on various hosts, allowing them to interact seamlessly. These components rely on interfaces to facilitate behavior invocation across different components.</p><p>An object broker acts as a technology bridge, enabling remote method calls on objects located in separate processes or platforms. This process involves intermediary objects, ensuring that the invoking client and the invoked server remain oblivious to the remote interaction, resulting in a seamless and transparent distributed computing experience.</p><h4>5. Persistance</h4><p>Persistence involves the ability to store an object’s data in a storage system or retrieve data into an object from a store. Persistent classes must handle both has-a and is-a relationships. Relational databases are not designed to store object graphs. One approach to storing object graphs is serializing them into a stream and then persisting the stream as a binary large object (blob). In the spirit of object-oriented programming, we should consider persistence as a capability provided by objects, a responsibility of objects, and an integral part of the domain.</p><h3>Conclusion</h3><p>Here are the key takeaways summarizing the content of our lessons that you should keep in mind:</p><ol><li>We’ve covered fundamental concepts, the process of object-oriented design, and essential design principles.</li><li>Differentiated between two approaches: structured and object-oriented methodologies.</li><li>Explored core OOP concepts: classes/objects, encapsulation, messages &amp; behavior.</li><li>Gained insights into Inheritance and Polymorphism, and how they relate.</li><li>Discussed the essentials of UML and popularly used UML class diagrams.</li><li>Discovered UML design techniques.</li><li>Explored the basics of design and code development processes.</li></ol><p>By internalizing these fundamental concepts and principles, you’ve laid a strong foundation for your development journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=433b601424b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Idea to Execution: Developing Your First Auction Smart Contract as a Beginner]]></title>
            <link>https://danillion.medium.com/from-idea-to-execution-developing-your-first-auction-smart-contract-as-a-beginner-f8eaefe059f0?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8eaefe059f0</guid>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 07:35:26 GMT</pubDate>
            <atom:updated>2023-10-22T19:10:50.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Auctions in the Digital Age: Crafting Your Debut Smart Contract as a Novice Developer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qv8Asoy1ykIpsA43.png" /></figure><h3>Walkthrough of the Auction Smart Contract</h3><p>In the landscape of decentralized commerce, auctions play a pivotal role in enabling transparent and competitive transactions. Imagine a scenario where participants compete to place their bids, aiming to win an item up for grabs. The power of smart contracts allows us to create a robust and automated system for conducting auctions, revolutionizing the way assets change hands within the digital realm.</p><h3>Coding Phase: Initiating the Implementation Process</h3><h4>Variables and Constructors</h4><p>The owner, whose address will deploy the contract, is owner. We will declare two variables of type uint as startBlock and endBlock. These will be used to calculate the start and end times of the auction.</p><p>The item listed for auction will also have a description, and the product will include some descriptive images. Storing this information on the blockchain is costly, so we will use an alternative off-chain solution.</p><p>For instance, we can store all information about the item on IPFS or a file system. We will use an IPFS Hash to uniquely identify the information, setting the variable as ipfsHash.</p><pre>address payable public owner;<br>uint public startBlock;<br>uint public endBlock;<br>string public ipfsHash;</pre><p>We declare an enum type called State to store the status of the auction session: enum State {Started, Running, Ended, Canceled}.</p><p>We declare a variable named auctionState of the type State to represent the status of the auction session, and a public uint variable named highestBindingBid to hold the highest bidding price.</p><p>There’s also a variable named highestBidder to store the address of the highest bidder.</p><pre>enum State {Started, Running, Ended, Canceled}<br>State public auctionState;<br>uint public highestBindingBid;<br>address payable public highestBidder;</pre><p>We require mapping variables referred to as bids to store the bids for each bidder’s address and the corresponding value sent in the auction. The variable indicating the bidding price increment is bidIncrement and the variable ownerFinalized marks the completion of the highest bid.</p><pre>mapping(address =&gt; uint) public bids;<br>uint bidIncrement;<br>// the owner can finalize the auction and get the highestBindingBid only once<br>bool public ownerFinalized = false;</pre><p>We initialize the owner to the deploying contract’s address: owner = payable(msg.sender) and set the auction status to “Running”: auctionState = State.Running .</p><p>Next, we establish the start and end dates of the auction. Considering that an Ethereum block time is around 15 seconds, a new block is added to the blockchain approximately every 15 seconds. Using block intervals, we can calculate the start and end times of the auction. So, startBlock = block.number, where block.number is a global variable in Solidity.</p><p>To determine the number of blocks, we divide the time in seconds by 15. In a week, around 40,320 blocks are generated, indicating the auction’s duration for a week. For our smart contract testing purposes, let’s use 3 blocks: endBlock = startBlock + 3 .</p><p>We initialize other state variables: ipfsHash = “” (an empty string), and the bidding price increment bidIncrement will be 10¹⁸ wei.</p><pre>constructor() {<br>    owner = payable(msg.sender);<br>    auctionState = State.Running;<br><br>    startBlock = block.number;<br>    endBlock = startBlock + 3;<br><br>    ipfsHash = &quot;&quot;;<br>    bidIncrement = 1000000000000000000; // bidding in multiple of ETH<br>}</pre><p>The function min(uint a, uint b) serves as a simple utility. It compares the minimum value between “a” and “b,” returning the smaller value as the result.</p><pre>function min(uint a, uint b) pure internal returns(uint) {<br>    if (a &lt;= b) {<br>        return a;<br>    } else {<br>        return b;<br>    }<br>}</pre><h4>Function Modifiers</h4><p>Modifier functions are employed to modify the behavior of a function. The body of the function is executed only if the required condition of the modifier returns true. We require four modifier functions as follows:</p><ul><li>notOwner() executes when (msg.sender != owner) .</li><li>onlyOwner() executes when (msg.sender == owner) .</li><li>afterStart() executes when (block.number &gt;= startBlock) .</li><li>beforeEnd() executes when (block.number &lt;= endBlock) .</li></ul><pre>modifier notOwner() {<br>    require(msg.sender != owner);<br>    _;<br>}<br><br>modifier onlyOwner() {<br>    require(msg.sender == owner);<br>    _;<br>}<br><br>modifier afterStart() {<br>    require(block.number &gt;= startBlock);<br>    _;<br>}<br><br>modifier beforeEnd() {<br>    require(block.number &lt;= endBlock);<br>    _;<br>}</pre><h4>cancelAuction</h4><p>In case of emergencies, such as discovering a vulnerability in the code or any adverse events, the owner has the capability to cancel the auction. This allows all bidders to request refunds for their contributions.</p><pre>function cancelAuction() public beforeEnd onlyOwner {<br>    auctionState = State.Canceled;<br>}</pre><h4>placeBid</h4><p>We will declare a function named placeBid, which will be called when someone intends to place a buying bid.</p><p>There are certain limitations when calling this function. We do not permit the owner to place a buying bid as they might artificially inflate the price. Therefore, a modifier function named notOwner will be applied to this function.</p><p>Another constraint is that the auction can only occur within the start and end ranges. So, additional modifier functions are applied: afterStart and a second modifier function applied on the end: beforeEnd.</p><p>We add another restriction that the auction session must be in the “Running” state: require(auctionState == State.Running) .</p><p>Adding a local uint variable named currentBid. This value includes the amount sent by the current address plus the value sent with this transaction: uint currentBid = bids[msg.sender] + msg.value .</p><p>Next, we update the bidding price for the current user, hence: bids[msg.sender] = currentBid .</p><p>Now, there are two possibilities:</p><ol><li>The current bidding price is higher than highestBindingBid but less than bids[highestBidder]. In this case, the highest bidder remains unchanged. highestBindingBid = min(currentBid + bidIncrement, bids[highestBidder]) .</li><li>Another possibility is that currentBid &gt; bids[highestBidder]. In this case, highestBindingBid = min(currentBid, bids[highestBidder] + bidIncrement) .</li></ol><pre>function placeBid() public payable notOwner afterStart beforeEnd returns(bool) {<br>    require(auctionState == State.Running);<br><br>    uint currentBid = bids[msg.sender] + msg.value;<br><br>    require(currentBid &gt; highestBindingBid);<br>    bids[msg.sender] = currentBid;<br><br>    if (currentBid &lt;= bids[highestBidder]) {<br>        highestBindingBid = min(currentBid + bidIncrement, bids[highestBidder]);<br>    } else {<br>        highestBindingBid = min(currentBid, bids[highestBidder] + bidIncrement);<br>        highestBidder = payable(msg.sender);<br>    }<br>    return true;<br>}</pre><h4>finalizeAuction</h4><p>The function finalizeAuction checks whether the auction is canceled or has ended. If the auction was canceled or ended by the owner, they can finalize it. We define two variables: recipient to store the address to receive the money sent in the auction, and value to store the amount.</p><p>In the case of a canceled auction, if auctionState == State.Canceled, the recipient is set to the sender, and the value is the bid amount placed by the sender.</p><p>If the auction has ended (not canceled), meaning it was concluded by the owner, they will receive the highest binding bid.</p><p>The funds are then transferred to the recipient, and the auction state is set to State.Ended.</p><p>There is another branch; the auction finalization could be requested by an address that is not the owner, but a bidder who wants to claim their own funds. In this case, there are also two possibilities:</p><ol><li>If the caller is the highest bidder, they will receive the difference between the value they bid and the highest binding bid: recipient = highestBidder and value = bids[highestBidder] — highestBindingBid .</li><li>If the caller is neither the owner nor the highest bidder, they are one of the bidders in the auction: recipient = payable(msg.sender) and value = bids[msg.sender] .</li></ol><pre>function finalizeAuction() public {<br>    require(auctionState == State.Canceled || block.number &gt; endBlock);<br>    require(msg.sender == owner || bids[msg.sender] &gt; 0);<br><br>    address payable recipient;<br>    uint value;<br>    if (auctionState == State.Canceled) {<br>        recipient = payable(msg.sender);<br>        value = bids[msg.sender];<br>    } else {<br>        if (msg.sender == owner &amp;&amp; ownerFinalized == false) {<br>            recipient = owner;<br>            value = highestBindingBid;<br>            ownerFinalized = true;<br>        } else {<br>            if (msg.sender == highestBidder) {<br>                recipient = highestBidder;<br>                value = bids[highestBidder] - highestBindingBid;<br>            } else {<br>                recipient = payable(msg.sender);<br>                value = bids[msg.sender];<br>            }<br>        }<br>    }<br>    bids[recipient] = 0;<br>    recipient.transfer(value);<br>}</pre><h3>Conclusion</h3><p>Combining all the codes together, we create a simple yet practical and fully functional Auction smart contract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db270c7290ea4ab536263f63fa9a0b5c/href">https://medium.com/media/db270c7290ea4ab536263f63fa9a0b5c/href</a></iframe><p>Congratulations on successfully designing and implementing the Auction Smart Contract! Feel free to explore and experiment with more advanced concepts as you continue your venture in blockchain development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8eaefe059f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevate Your Projects: Developing a Crowdfunding Smart Contract for Beginners]]></title>
            <link>https://danillion.medium.com/elevate-your-projects-developing-a-crowdfunding-smart-contract-for-beginners-653b8e36117a?source=rss-9cb46516a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/653b8e36117a</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Daniel Pham]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 13:31:56 GMT</pubDate>
            <atom:updated>2023-08-10T13:31:56.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NL3cG9PA_Tya6xma" /></figure><h3>Walkthrough of the Crowdfunding Mechanisms</h3><p>In the domain of project financing, the Crowdfunding Smart Contract emerges as an empowering and revolutionary tool . It streamlines the fundraising process and provides a transparent platform for creators and supporters. Imagine a world where ideas come to life with the collective support of backers, all orchestrated through a secure and automated system.</p><h4>Smart Contract Empowerment</h4><p>The Crowdfunding Smart Contract harnesses the power of smart technology to redefine the way projects are funded. It lays the foundation for secure and automated fund management, ensuring that contributions are accurately tracked and utilized according to the project’s defined parameters.</p><p>With the rapid advancement of blockchain and smart contract technology, the Crowdfunding Smart Contract is poised to revolutionize the world of project financing. It introduces transparency, security, and efficiency into the fundraising landscape, empowering creators and backers alike to turn dreams into reality.</p><h3>Coding Phase: Initiating the Implementation Process</h3><h4>Variables and Constructors</h4><p>Contributors named in the constructor, which includes mapping variables (address and uint), will be made public: mapping(address =&gt; uint) public contributors.</p><p>The address of the manager or administrator is set as address public admin .</p><p>We require other public variables:</p><ul><li>Number of collaborators: uint public noOfContributors.</li><li>Minimum contribution amount: uint public minimumContributors.</li><li>Deadline: uint public deadline.</li><li>Goal amount: uint public goal.</li><li>Raised amount: uint public raisedAmount.</li></ul><pre>mapping(address =&gt; uint) public contributors;<br>address public admin;<br>uint public noOfContributors;<br>uint public minimumContribution;<br>uint public deadline;<br>uint public goal;<br>uint public raisedAmount;</pre><p>The structured variable Request consists of the following components:</p><ul><li>Description: string description .</li><li>Address of the recipient: address payable recipient.</li><li>Value in wei: uint value.</li><li>A variable to track completion: bool completed, when a contributor has been voted on.</li><li>The number of voters: uint noOfVoters.</li><li>A mapping that stores addresses of voters with values of true/false: mapping(address =&gt; bool) voters,</li></ul><pre>struct Request {<br>    string description;<br>    address payable recipient;<br>    uint value;<br>    bool completed;<br>    uint noOfVoters;<br>    mapping(address =&gt; bool) voters;<br>}</pre><p>We need to add variables to store requests as requests and the number of requests as numRequests.</p><pre>mapping(uint =&gt; Request) public requests;<br>uint public numRequests;</pre><p>The constructor function takes two values, _goal and _deadline, to set the goal and deadline variables. The admin variable and the minimumContribution value are also initialized.</p><pre>constructor(uint _goal, uint _deadline) {<br>    goal = _goal;<br>    deadline = block.timestamp + _deadline;<br>    admin = msg.sender;<br>    minimumContribution = 100 wei;<br>}</pre><h4>Events</h4><p>This contract has three events established. Pay attention to the events emitted within the statements of functions, indicated by the “<strong>emit</strong>” keyword followed by the event name and the parameter values.</p><pre>event ContributeEvent(address _sender, uint _value);<br>event CreateRequestEvent(string _description, address _recipient, uint _value);<br>event MakePaymentEvent(address _recipient, uint _value);</pre><h4>Function Modifiers</h4><p>We have one funcion modifier named onlyAdmin:</p><pre>modifier onlyAdmin() {<br>    require(msg.sender == admin, &quot;Only admin can execute this&quot;);<br>    _;<br>}</pre><h4>contribute</h4><p>This function is executed when the<strong> block.timestamp</strong> has not reached the <strong>deadline </strong>and the <strong>msg.value</strong> is equal to or greater than the <strong>minimumContribution </strong>threshold.</p><pre>function contribute() public payable {<br>    require(block.timestamp &lt; deadline, &quot;The deadline has passed!&quot;);<br>    require(msg.value &gt;= minimumContribution, &quot;The minimum contribution not met!&quot;);<br><br>    // incrementing the no. of contributors the first time when<br>    // someone sends eth to the contract<br>    if (contributors[msg.sender] == 0) {<br>        noOfContributors++;<br>    }<br>    <br>    contributors[msg.sender] += msg.value;<br>    raisedAmount += msg.value;<br><br>    emit ContributeEvent(msg.sender, msg.value);<br>}</pre><h4>getBalance</h4><p>This function returns the remaining value of the contract.</p><pre>function getBalance() public view returns(uint) {<br>    return address(this).balance;<br>}</pre><h4>getRefund</h4><p>The function needs to verify three input conditions to execute:</p><ul><li>block.timestamp &gt; deadline.</li><li>raisedAmount &lt; goal.</li><li>contributors[msg.sender] &gt; 0.</li></ul><p>After that, the necessary commands of getRefund are carried out:</p><pre>function getRefund() public {<br>    require(block.timestamp &gt; deadline, &quot;Deadline has not passed&quot;);<br>    require(raisedAmount &lt; goal, &quot;The goal was met&quot;);<br>    require(contributors[msg.sender] &gt; 0);<br><br>    address payable recipient = payable(msg.sender);<br>    uint value = contributors[msg.sender];<br>    recipient.transfer(value);<br>    // equivalent to:<br>    // payable(msg.sender).transfer(contributors[msg.sender]);<br><br>    contributors[msg.sender] = 0;<br>}</pre><h4>createRequest</h4><p>The function createRequest can only be executed by the admin under the control of onlyAdmin. The parameters _description, _recipient, and _value are used to set the values of a newRequest.</p><pre>function createRequest(string calldata _description, address payable _recipient, uint _value) public onlyAdmin {<br>    // numRequests starts from zero<br>    Request storage newRequest = requests[numRequests];<br>    numRequests++;<br><br>    newRequest.description = _description;<br>    newRequest.recipient = _recipient;<br>    newRequest.value = _value;<br>    newRequest.completed = false;<br>    newRequest.noOfVoters = 0;<br><br>    emit CreateRequestEvent(_description, _recipient, _value);<br>}</pre><h4>voteRequest</h4><p>The function takes the input value _requestNo, and the user must be a contributor to participate in voting. The function also checks and notifies if the user has already voted for thisRequest. Finally, thisRequest will be voted on, and the number of users who have voted for the request will be incremented.</p><pre>function voteRequest(uint _requestNo) public {<br>    require(contributors[msg.sender] &gt; 0, &quot;You must be a contributor to vote!&quot;);<br><br>    Request storage thisRequest = requests[_requestNo];<br>    require(thisRequest.voters[msg.sender] == false, &quot;You have already voted!&quot;);<br><br>    thisRequest.voters[msg.sender] = true;<br>    thisRequest.noOfVoters++;<br>}</pre><h4>makePayment</h4><p>The functionmakePayment can only be executed by the admin under the control of onlyAdmin. The function takes the input value _requestNo , checks and executes if thisRequest.completed == false. It also requires that the number of users who have voted is more than 50% before processing the payment.</p><p>Finally, the payment value will be transferred, and the voting process will be marked as completed.</p><pre>function makePayment(uint _requestNo) public onlyAdmin {<br>    Request storage thisRequest = requests[_requestNo];<br>    require(thisRequest.completed == false, &quot;The request has been already completed!&quot;);<br><br>    require(thisRequest.noOfVoters &gt; noOfContributors / 2, &quot;The request needs more than 50% of the contributors.&quot;);<br>    thisRequest.recipient.transfer(thisRequest.value);<br>    thisRequest.completed = true;<br><br>    emit MakePaymentEvent(thisRequest.recipient, thisRequest.value);<br>}</pre><h3>Conclusion</h3><p>Combining all the codes together, we create a simple yet practical and fully functional Escrow smart contract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ef1fa826cdcfb078467124eba6f74ff/href">https://medium.com/media/2ef1fa826cdcfb078467124eba6f74ff/href</a></iframe><p>Congratulations on successfully designing and implementing the Crowfunding Smart Contract! Feel free to explore and experiment with more advanced concepts as you continue your venture in blockchain development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653b8e36117a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>