create account

Horizontal Formatting and Tricks By albro by albro

View this thread on: hive.blogpeakd.comecency.com
· @albro ·
$15.98
Horizontal Formatting and Tricks By albro
<center>![Horizontal Formatting and Tricks](https://files.peakd.com/file/peakd-hive/albro/EoibW8i1TMdR9esizdnfWcaXQYZd4KtLKMZkXywytusqxEj8Y6QV8bkTQAmgLbtvBpn.jpg)</center>

<p><a href="https://peakd.com/hive-169321/@albro/commenting-code-structure-and-tricks-by-albro">In the previous post</a>, I showed you the following code and explained why you should do vertical spacing or vertical formatting:</p>
<pre><code>const path = require('path');<br />
const fs = require('fs');<br />
class DiskStorage {<br />
  constructor(storageDirectory) {<br />
    this.storagePath = path.join(__dirname, storageDirectory);<br />
    this.setupStorageDirectory();<br />
  }<br />
  setupStorageDirectory() {<br />
    if (!fs.existsSync(this.storagePath)) {<br />
      this.createStorageDirectory();<br />
    } else {<br />
      console.log('Directory exists already.');<br />
    }<br />
  }<br />
  createStorageDirectory() {<br />
    fs.mkdir(this.storagePath, this.handleOperationCompletion);<br />
  }<br /><br />
//Continuation of codes
</code></pre>
<p>The only rule I told you about this was that vertical spacing should separate unrelated concepts (for example, we should separate methods in the above class using whitespace), but what about related concepts? Is it correct to convert the code above to the code below?</p>
<pre><code>const path = require('path');<br /><br /><br /><br />
const fs = require('fs');<br /><br /><br /><br />
class DiskStorage {<br /><br /><br /><br />
  constructor(storageDirectory) {<br />
    this.storagePath = path.join(__dirname, storageDirectory);<br /><br /><br /><br />
    this.setupStorageDirectory();<br /><br /><br /><br />
  }<br /><br /><br /><br />
  setupStorageDirectory() {<br /><br /><br /><br />
    if (!fs.existsSync(this.storagePath)) {<br />
      this.createStorageDirectory();<br />
    }<br /><br /><br />
    else {<br />
      console.log('Directory exists already.');<br />
    }<br />
  }<br /><br /><br /><br />
  createStorageDirectory() {<br />
    fs.mkdir(this.storagePath, this.handleOperationCompletion);<br />
  }<br /><br /><br /><br />
  insertFileWithData(fileName, data) {<br /><br /><br /><br />
    if (!fs.existsSync(this.storagePath)) {<br />
      console.log("The storage directory hasn't been created yet.");<br />
      return;<br />
    }<br /><br /><br /><br />
    const filePath = path.join(this.storagePath, fileName);<br /><br /><br /><br />
    fs.writeFile(filePath, data, this.handleOperationCompletion);<br /><br /><br /><br />
  }<br /><br /><br /><br />
  handleOperationCompletion(error) {<br /><br /><br /><br />
    if (error) {<br />
      this.handleFileSystemError(error);<br />
    }<br /><br /><br /><br />
    else {<br />
      console.log('Operation completed.');<br />
    }<br /><br /><br /><br />
  }<br /><br /><br /><br />
  handleFileSystemError(error) {<br /><br /><br /><br />
    if (error) {<br />
      console.log('Something went wrong - the operation did not complete.');<br />
      console.log(error);<br />
    }<br /><br /><br /><br />
  }<br />
}<br /><br /><br /><br />
const logStorage = new DiskStorage('logs');<br />
const userStorage = new DiskStorage('users');<br /><br /><br /><br />
setTimeout(function () {<br /><br /><br /><br />
  logStorage.insertFileWithData('2023-09-21.txt', 'A first demo log entry.');<br /><br /><br /><br />
  logStorage.insertFileWithData('2023-09-22.txt', 'A second demo log entry.');<br /><br /><br /><br />
  userStorage.insertFileWithData('albro.txt', 'Albro Hive Blockchain');<br /><br /><br /><br />
  userStorage.insertFileWithData('ocdb.txt', 'OCDB Hive Blog');<br />
}, 1500);</code></pre>
<p>This sample code is an unreadable code because all the lines are separated from each other and it's difficult to distinguish which of them belong to a particular method at first glance. Therefore, just as the absence of space on the vertical axis is bad, its excessive presence will also be bad and harm the readability of the code. Another point is that you should always keep related concepts close together. For example, the <code>setTimeout</code> function from the code above is a related concept or code category, so it should be written as follows:</p>
<pre><code>setTimeout(function () {
  logStorage.insertFileWithData('2023-09-21.txt', 'A first demo log entry.');
  logStorage.insertFileWithData('2023-09-22.txt', 'A second demo log entry.');
  userStorage.insertFileWithData('albro.txt', 'Albro Hive Blockchain');
  userStorage.insertFileWithData('ocdb.txt', 'OCDB Hive Blog');
}, 1500);</code></pre>
<p>As you can see, there is no space between the lines of this code because they all do a specific task together and are not separate.</p>
<h3>The process of reading the code</h3>
<p>Before I want to go into the horizontal formatting discussion, I have to explain a special point. In the above code (<code>DiskStorage</code> class), it has been tried to define related methods as close as possible. For example, the <code>handleOperationCompletion</code> method is defined right next to the method that uses it:</p>
<pre><code>  insertFileWithData(fileName, data) {
    if (!fs.existsSync(this.storagePath)) {
      console.log("The storage directory hasn't been created yet.");
      return;
    }
    const filePath = path.join(this.storagePath, fileName);
    fs.writeFile(filePath, data, this.handleOperationCompletion);
  }<br /><br /><br /><br />
  handleOperationCompletion(error) {
    if (error) {
      this.handleFileSystemError(error);
    } else {
      console.log('Operation completed.');
    }
  }</code></pre>
<p>You should also try to bring related methods and functions together as much as possible. Why? Because if someone is reading the code, they can easily find the definition of a function and not have to scroll to the end of a few hundred lines of a file.</p>
<p>The explanations I gave about this were general and for all programming languages, but some of you may have a question about how we called the method first and then defined it? In a language like JavaScript, you can do this because JavaScript has hoisting capability, that is, it loads the definition of variables and functions first and then executes the rest of the code, but in languages like Python, by doing this You will have a problem. Consider the following example:</p>
<pre><code>start();<br /><br /><br /><br />
function start() {
  console.log('start');
  next();
}<br /><br /><br /><br />
function next() {
  console.log('next');
  last();
}<br /><br /><br /><br />
function last() {
  console.log('last');
}</code></pre>
<p>If you run the javascript code above, everything will run smoothly; It means that first the <code>start</code> method will be executed, then the <code>next</code> method will be executed, and then the <code>last</code> method will be executed. Now consider the following example from the Python language:<p>
<pre><code># do't work
# start()<br /><br /><br /><br /><br /><br /><br />
def start():
    print('Start')
    next()<br /><br /><br /><br /><br /><br /><br />
# don't work
# start()<br /><br /><br /><br /><br /><br /><br />
def next():
    print('Next')
    last()<br /><br /><br /><br /><br /><br /><br />
def last():
    print('Last')<br /><br /><br /><br />
# Work
start()</code></pre>
<p>I have left a comment in this example for you to see in which places calling the <code>start</code> function will work. By looking at these codes, you will notice that calling the <code>start</code> function only works at the end of the file and after defining the functions, and we get errors in other cases. Anyway, in my opinion it's better to keep related functions as close together as possible and also if possible, define the function or method before using it even if you have hoisting because it's more readable. This is partly a matter of taste.</p>
<h3>Horizontal Formatting</h3>
<p>Horizontal molding, as the name suggests, is related to molding along the horizon line. what does it mean? That is, in horizontal formatting, all our focus is only on one line and its length. The general rule of thumb in horizontal formatting is that other programmers should be able to read your code without scrolling horizontally. Horizontal scrolling occurs when the length of your code lines (the number of characters per line) is too long, so it protrudes from the page and we have to scroll horizontally to read it.</p>
<p>The first rule to solve this problem is not to write long codes in one line. For example, consider the following code:</p>
<pre>code>class DiskStorage { constructor(storageDirectory) { this.storagePath = path.join(__dirname, storageDirectory); this.setupStorageDirectory(); } }</code></pre>
<p>This is the same <code>DiskStorage</code> class, but this time I wrote the constructor along with the class definition in one line and didn't use indentation. I don't think I need to explain why such code isn't easy to read. Whenever you notice that your codes are getting too long, it is better to break them and put them on a new line.</p>
<p>Our second rule for horizontal formatting is to use indentation. Note that in some programming languages such as Python, the use of indentation is necessary, but in languages such as JavaScript it is not necessary and you can write thousands of pages of code in one line! But you should never do such a thing. Consider the following example:</p>
<pre><code>const path = require("path");
const fs = require("fs");<br /><br /><br /><br />
class DiskStorage {
constructor(storageDirectory) {
this.storagePath = path.join(__dirname, storageDirectory);
this.setupStorageDirectory();
}<br /><br /><br /><br />
setupStorageDirectory() {
if (!fs.existsSync(this.storagePath)) {
this.createStorageDirectory();
} else {
console.log("Directory exists already.");
}
}<br /><br /><br /><br />
createStorageDirectory() {
fs.mkdir(this.storagePath, this.handleOperationCompletion);
}<br /><br /><br /><br />
insertFileWithData(fileName, data) {
if (!fs.existsSync(this.storagePath)) {
console.log("The storage directory hasn't been created yet.");
return;
}
const filePath = path.join(this.storagePath, fileName);
fs.writeFile(filePath, data, this.handleOperationCompletion);
}<br /><br /><br /><br />
handleOperationCompletion(error) {
if (error) {
this.handleFileSystemError(error);
} else {
console.log("Operation completed.");
}
}<br /><br /><br /><br />
handleFileSystemError(error) {
if (error) {
console.log("Something went wrong - the operation did not complete.");
console.log(error);
}
}
}<br /><br /><br /><br />
const logStorage = new DiskStorage("logs");
const userStorage = new DiskStorage("users");<br /><br /><br /><br />
setTimeout(function () {
logStorage.insertFileWithData("2023-09-21.txt", "A first demo log entry.");
logStorage.insertFileWithData("2023-09-22.txt", "A second demo log entry.");
userStorage.insertFileWithData("albro.txt", "Albro is Happy in Hive Blockchain");
userStorage.insertFileWithData("ocdb.txt", "Hello OCDB");
}, 1500);</code></pre>
<p>I have removed all the indentations in the above code and as you can see, this code has become many times more difficult to read and at first glance it seems like we have a very large function.</p>
<p>The third rule of horizontal formatting is to divide your statements into smaller statements. For example, in JavaScript (node.js) there is a function called <code>mkdir</code> that creates a new folder and takes two arguments: the first argument is the address of the new folder and the second argument is a callback function that is executed after the operation is completed. Pay attention to the following code:</p>
<pre><code>  createStorageDirectory() {
    fs.mkdir(path.join(__dirname, 'temp', '2023-3', 'images'), this.handleOperationCompletion);
  }</code></pre>
<p>To create the path in JavaScript, we must use <code>path.join</code> to join the folders correctly, because the way of addressing is different in Linux and Windows (using <code>/</code> and <code>\</code>), so if you do the addressing manually For example, the codes are only executed on a specific operating system. The problem with the above code is that our statement is too long, that is, we have performed the operation of generating the first argument or creating the address in the same line, which has made this line too long. We could write the above code as follows:</p>
<pre><code>  createStorageDirectory() {
    const storagePath = path.join(__dirname, "temp", "2023-3", "images");
    fs.mkdir(storagePath, this.handleOperationCompletion);
  }</code></pre>
<p>The last rule of horizontal formatting is not to use very long and overly descriptive names. Naturally, the names of various methods and variables are a little longer than other code components, and this is completely normal, but it should not exceed a reasonable limit. Example:</p>
<pre><code>  createStorageDirectory() {
    const storagePathForStoringImagesInATemporaryFolderFor2020 = path.join(__dirname, "temp", "2023-3", "images");
    fs.mkdir(storagePathForStoringImagesInATemporaryFolderFor2020, this.handleOperationCompletion);
  }</code></pre>
<p>Choosing such a name, which is too descriptive, makes the codes crowded and unreadable.</p>
<h3>Challenge and problem solving</h3>
<p>Now that we are familiar with the concepts of code structure and formatting, it's time for a challenge and problem solving. I have prepared a python code for you that has some small problems and you have to solve these problems:</p>
<pre><code># (c) @albro / peakd.com<br /><br /><br />
# *********
# Imports
# *********
from os import path, makedirs
from pathlib import Path<br /><br /><br />
# *********
# Main
# *********
# A class which allows us to create DiskStorage instances<br /><br /><br /><br /><br /><br />
class DiskStorage:
    def __init__(self, directory_name):
        self.storage_directory = directory_name<br /><br /><br />
    def get_directory_path(self):
        return Path(self.storage_directory)<br /><br /><br />
    # This function must be called before saving the file
    def create_directory(self):
        if (not path.exists(self.get_directory_path())):
            makedirs(self.storage_directory)<br /><br /><br />
    # The desired folder must already exist
    def insert_file(self, file_name, content):
        file = open(self.get_directory_path() / file_name, 'w')
        file.write(content)
        file.close()
        # Todo: Add error management system<br /><br /><br /><br /><br /><br />
log_storage = DiskStorage('logs')<br /><br /><br />
log_storage.insert_file('test.txt', 'Test')</code></pre>
<p>Note that the comments in the code above are not for you, but written by the developer. For example, in part of the code, we have a comment in the form of "Add error management system". I don't ask you to actually implement the error management system. Your task is to make the above code more readable based on the points I have explained before. Try to modify this code yourself and then compare your answer with mine. I say again that we do not have only one correct answer, but ways There are different ways to solve this problem.</p>
<p>I will start with the comments first. At first, we have a comment that identifies the author of the file and we explained that these comments are not a problem and are completely allowed. In the next step, we have comments that separate different parts of the file, and I explained to you that these comments are not appropriate at all. In addition, we have a comment that explains that the <code>DiskStorage</code> class allows us to create an object from it! This comment is also a very bad comment because all classes are the same and this class does not do anything special. The explanations written in this comment do not work at all and are not even doc strings. To write documentation comments, which are known as doc string in Python, we must use three quote marks:</p>
<pre><code>"""
the documentation goes here
"""</code></pre>
<p>Therefore, these comments are not useful and we delete them:</p>
<pre><code># (c) @albro / peakd.com<br /><br /><br />
from os import path, makedirs
from pathlib import Path<br /><br /><br /><br /><br /><br />
class DiskStorage:</code></pre>
<p>Next, we had two other comments, both of which are considered warnings:</p>
<pre><code>    # This function must be called before saving the file
    def create_directory(self):
        if (not path.exists(self.get_directory_path())):
            makedirs(self.storage_directory)<br /><br /><br />
    # The desired folder must already exist
    def insert_file(self, file_name, content):
        file = open(self.get_directory_path() / file_name, 'w')
        file.write(content)
        file.close()</code></pre>
<p>If you look at these two comments, you will notice that they both point out the same issue. Calling <code>create_directory</code> creates the directory, so it's natural that there must be a directory in that path before adding files (that is, <code>create_directory</code> has been called). In my opinion, one of these warning comments is not a problem, but both of them are overwritten, so we have to delete one of them. We need to leave a comment next to the part of the code that will cause the error, so I leave the second comment:</p>
<pre><code>    def create_directory(self):
        if (not path.exists(self.get_directory_path())):
            makedirs(self.storage_directory)<br /><br /><br />
    # The desired folder must already exist
    def insert_file(self, file_name, content):
        file = open(self.get_directory_path() / file_name, 'w')
        file.write(content)
        file.close()</code></pre>
<p>Our final comment is also a TODO comment that I have already explained how they work. The problem here is that instead of writing "Implementation of an error management system", it is better to actually implement an error management system and not postpone it to another time, but as a temporary reminder, there is no problem in using it, so leave it as well. we let. Also, in terms of vertical formatting, the codes have no problem and are considered readable, and the only problem they have is at the end of the file and the presence of a space between the two last lines of the code:</p>
<pre><code>log_storage = DiskStorage('logs')<br /><br /><br />
log_storage.insert_file('test.txt', 'Test')</code></pre>
</code></pre>
<p>These two lines are connected and adding a space to them is not interesting, so I'll remove this space. We should also listen to our warning comment and call the <code>create_directory</code> statement before inserting the files. Also, another way to think about this is to say that an instance of a different class is created by performing different operations on the object, so these two lines should be separate:</p>
<pre>code>log_storage = DiskStorage('logs')<br /><br /><br />
log_storage.create_directory()
log_storage.insert_file('test.txt', 'Test')</code></pre>
<p>Whatever way you act, you must have a reason for it.</p>
<p>In terms of horizontal formatting, we are not a long line, but it is better to break the following line to make it more readable:</p>
<pre><code>file = open(self.get_directory_path() / file_name, 'w')</code></pre>
<p>In this line, we have created the desired file path, but everything is calculated as the first argument. Although this code is not bad, it can still be improved:</p>
<pre><code>file_path = self.get_directory_path() / file_name
file = open(file_path, 'w')</code></pre>
<p>So our final corrected code will look like this:</p>
<pre><code># (c) @albro / peakd.com<br /><br /><br />
from os import path, makedirs
from pathlib import Path<br /><br /><br /><br /><br /><br />
class DiskStorage:
    def __init__(self, directory_name):
        self.storage_directory = directory_name<br /><br /><br />
    def get_directory_path(self):
        return Path(self.storage_directory)<br /><br /><br />
    def create_directory(self):
        if (not path.exists(self.get_directory_path())):
            makedirs(self.storage_directory)<br /><br /><br />
    # The desired folder must already exist
    def insert_file(self, file_name, content):
        file_path = self.get_directory_path() / file_name
        file = open(file_path, 'w')
        file.write(content)
        file.close()
        # Todo: Add error management system<br /><br /><br /><br /><br /><br />
log_storage = DiskStorage('logs')<br /><br /><br />
log_storage.create_directory()
log_storage.insert_file('test.txt', 'Test')</code></pre>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 524 others
properties (23)
authoralbro
permlinkhorizontal-formatting-and-tricks-by-albro
categoryhive-169321
json_metadata"{"app":"peakd/2023.9.1","format":"markdown","author":"albro","description":"Have you ever thought about clean coding? In this post, let's about horizontal formatting to make coding more readable.","tags":["development","programming","gosh","threads","chessbrothers","neoxag","tricks","clean-code","leofinance"],"users":["albro"],"image":["https://files.peakd.com/file/peakd-hive/albro/EoibW8i1TMdR9esizdnfWcaXQYZd4KtLKMZkXywytusqxEj8Y6QV8bkTQAmgLbtvBpn.jpg"]}"
created2023-09-21 21:30:00
last_update2023-09-21 21:30:00
depth0
children3
last_payout2023-09-28 21:30:00
cashout_time1969-12-31 23:59:59
total_payout_value7.952 HBD
curator_payout_value8.032 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length20,561
author_reputation30,477,419,385,789
root_title"Horizontal Formatting and Tricks By albro"
beneficiaries
0.
accounthive-169321
weight200
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id127,364,239
net_rshares39,825,456,178,510
author_curate_reward""
vote details (588)
@chessbrotherspro ·
<h3>Congratulations!</h3><hr /><div class="pull-right"><img src="https://images.hive.blog/DQmQLssYuuJP2neoTVUbMRzvAu4Ptg7Vwt92aTM7Z3gNovg/cb-logo-150.png" alt="You have obtained a vote from CHESS BROTHERS PROJECT"/></div><div class="text-justify"><h3>✅ Good job. Your post has been appreciated and has received support from <a href="/@chessbrotherspro"><b>CHESS BROTHERS</b></a> ♔ 💪</h3><p><br>♟ We invite you to use our hashtag <b>#chessbrothers</b> and learn more <a href="/@chessbrotherspro/introducing-chess-brothers-project-the-most-innovative-community-combining-chess-fitness-and-more"><b>about us</b></a>.</p><p>♟♟ You can also reach us on our <a href="https://discord.gg/73sK9ZTGqJ" rel="noopener" title="This is going to take you to the Discord of Chess Brothers"><b>Discord server</b></a>  and promote your posts there.</p><p>♟♟♟  Consider <a href="/@chessbrotherspro/teamwork-is-worthwhile-join-the-chess-brothers-healing-trail-supporting-the-work-being-done-and-earning-rewards"><b>joining our curation trail</b></a> so we work as a team and you get rewards automatically.</p><p>♞♟ Check out our <a href="/@chessbrotherspro"><b>@chessbrotherspro</b></a> account to learn about the curation process carried out daily by our team.</p><p><br>🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the <i>Master Investor</i> plan. <a href='/@chessbrotherspro/master-investor-plan-or-programa'>Here you can learn how to do it.</a></p></div><div class="text-center"><p><br>Kindly</p><p><strong><em>The CHESS BROTHERS team</em></strong></p></div>
👍  
properties (23)
authorchessbrotherspro
permlinkre-horizontal-formatting-and-tricks-by-albro
categoryhive-169321
json_metadata""
created2023-09-22 12:55:30
last_update2023-09-22 12:55:30
depth1
children0
last_payout2023-09-29 12:55:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,598
author_reputation78,457,664,774,713
root_title"Horizontal Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id127,380,054
net_rshares6,812,413,947
author_curate_reward""
vote details (1)
@poshthreads ·
$0.02
https://leofinance.io/threads/albro/re-leothreads-34je6vjwi
<sub> The rewards earned on this comment will go directly to the people ( albro ) sharing the post on LeoThreads,LikeTu,dBuzz.</sub>
👍  ,
properties (23)
authorposhthreads
permlinkre-albro-horizontal-formatting-and-tricks-by-albro-1568
categoryhive-169321
json_metadata"{"app":"Poshtoken 0.0.2","payoutToUser":["albro"]}"
created2023-09-22 07:39:48
last_update2023-09-22 07:39:48
depth1
children0
last_payout2023-09-29 07:39:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.019 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length193
author_reputation415,471,585,053,248
root_title"Horizontal Formatting and Tricks By albro"
beneficiaries
0.
accountnomnomnomnom
weight10,000
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id127,374,568
net_rshares98,765,276,971
author_curate_reward""
vote details (2)
@stemsocial ·
re-albro-horizontal-formatting-and-tricks-by-albro-20230922t200909779z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.&nbsp;<br />&nbsp;<br />
</div>
👍  
properties (23)
authorstemsocial
permlinkre-albro-horizontal-formatting-and-tricks-by-albro-20230922t200909779z
categoryhive-169321
json_metadata{"app":"STEMsocial"}
created2023-09-22 20:09:09
last_update2023-09-22 20:09:09
depth1
children0
last_payout2023-09-29 20:09:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,927,767,309,334
root_title"Horizontal Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id127,387,697
net_rshares6,952,363,971
author_curate_reward""
vote details (1)