{"id":938,"date":"2024-07-16T10:21:49","date_gmt":"2024-07-16T10:21:49","guid":{"rendered":"https:\/\/tbekk.com\/devstream\/?p=938"},"modified":"2024-07-16T10:21:49","modified_gmt":"2024-07-16T10:21:49","slug":"50-coding-laws-that-would-make-you-a-decent-programmer","status":"publish","type":"post","link":"https:\/\/tbekk.com\/devstream\/2024\/07\/16\/50-coding-laws-that-would-make-you-a-decent-programmer\/","title":{"rendered":"50 Coding Laws That Would Make You A Decent Programmer."},"content":{"rendered":"\n<hr class=\"wp-block-separator has-text-color has-medium-gray-color has-alpha-channel-opacity has-medium-gray-background-color has-background is-style-wide\"\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em><strong>Link:<\/strong><\/em> <a href=\"https:\/\/medium.com\/@alexobidiegwu\/50-laws-of-best-practices-in-python-6942c7cafd56\"><em>medium.com<\/em><\/a><\/li>\n\n\n\n<li><em><strong>Author:<\/strong><\/em> <a href=\"https:\/\/medium.com\/@alexobidiegwu?source=post_page-----6942c7cafd56--------------------------------\"><em>Alexander obidiegwu<\/em><\/a><\/li>\n\n\n\n<li><em><strong>Publication date:<\/strong><\/em> <em>March 2, 2024<\/em><\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-medium-gray-color has-alpha-channel-opacity has-medium-gray-background-color has-background is-style-wide\"\/>\n\n\n\n<p id=\"c1bd\">There are hundreds or probably thousands of Python best practices out there and depending on who you ask, you would get some slight variation on a given practice.<\/p>\n\n\n\n<p id=\"6d3a\">The internet has given everyone the right to voice an opinion. Including even&nbsp;<a href=\"https:\/\/www.upwork.com\/freelancers\/~01f0e41431eb01dbdd\" rel=\"noreferrer noopener\" target=\"_blank\">me<\/a>. But in this article, we will be dealing with 50 Python best practices that are set in stone.<\/p>\n\n\n\n<p id=\"d469\">These are practices that even God himself can\u2019t tweak. These practices differentiate the pro from the amateur and a lot of them can also be adapted for various programming languages.<\/p>\n\n\n\n<p id=\"1599\"><em>Most Python developers need somewhere to quickly test their code or debug errors. I developed a website called&nbsp;<\/em><a href=\"https:\/\/python-fiddle.com\/\" rel=\"noreferrer noopener\" target=\"_blank\"><em>python-fiddle.com<\/em><\/a><em>&nbsp;which you can use to quickly test out a code and it uses AI\/LLMs to help find solutions to possible errors.<\/em><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"f126\">I plan to start posting content on linkedln too so if you\u2019re interested:&nbsp;<strong>My Linkedln: https:\/\/www.linkedin.com\/in\/alexanderobidiegwu<\/strong><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ed95\">LAW 1: Avoid Comments At All Cost<\/h2>\n\n\n\n<p id=\"b5bf\">Comments have a way of being falsely true. They deviate the mind of the reader from what the code is actually doing to what someone else says it\u2019s doing.<\/p>\n\n\n\n<p id=\"198b\">This can become very problematic as time passes and the code receives updates or changes. At some point, the comment becomes a lie and everyone now has to observe the truth through the lens of the lie.<\/p>\n\n\n\n<p id=\"aca7\">Comments must be avoided at all costs. A comment forces the reader to inherit your thinking which at best is in the past. When a function or class changes, most likely, its comments do not change along with it. Most likely, they block the reader from thinking forward.<\/p>\n\n\n\n<p id=\"eeca\">A comment signifies that the writer was mentally incapable of providing a well-descriptive class, function, or variable name. It exposes the lackluster attitude of the programmer and forces the team to inherit such an attitude.<\/p>\n\n\n\n<p id=\"62a3\">Avoid comments at all costs.<\/p>\n\n\n\n<p id=\"8748\">In Law 14 and 15, you would learn when and when not to use a comment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8e57\">LAW 2: Do Not Use Type Attributes As A Name For Variables<\/h2>\n\n\n\n<p id=\"9be4\">Sometimes we want to specify that a particular variable is a string or an int. Some developers would therefore name the variable like this:&nbsp;<code>name_of_variable_str<\/code>&nbsp;or&nbsp;<code>name_of_variable_int<\/code>.<\/p>\n\n\n\n<p id=\"4892\">This can be quite redundant especially if the variable is intuitively a string. A&nbsp;<code>name<\/code>&nbsp;variable, for instance, can never be an&nbsp;<code>int<\/code>&nbsp;type.<\/p>\n\n\n\n<p id=\"df65\">But when the variable type isn\u2019t intuitive, rather than specifying the type when naming the variable, the best way to do this is to use type annotations.<\/p>\n\n\n\n<p id=\"b85d\"><code>name_of_variable:str = value<\/code>&nbsp;instead of&nbsp;<code>name_of_variable_str = value<\/code>.<\/p>\n\n\n\n<p id=\"1b18\">This way, everyone can tell the variable is a string while keeping the code neat &amp; concise.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"f4f1\">LAW 3: Class Names Should Be Nouns.<\/h2>\n\n\n\n<p id=\"431c\">It\u2019s always best practice to keep your class names as nouns.<\/p>\n\n\n\n<p id=\"7ab7\">This is mostly because a class object is used to identify or represent a bunch of characteristics and actions. Similar to how a goat represents some characteristics like&nbsp;<code>horns<\/code>&nbsp;and actions like&nbsp;<code>nod_nearby_humans<\/code>.<\/p>\n\n\n\n<p id=\"3d85\">It also makes the code very readable and less redundant. For example,&nbsp;<code>Goat.get_horn_length()<\/code>&nbsp;instead of<code>GetGoat.get_horn_length()<\/code>&nbsp;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5ddb\">LAW 4: Function Names Should Be Verbs<\/h2>\n\n\n\n<p id=\"ce1b\">Functions are best named as verbs because they help the neighboring developer clearly understand what actions they perform.<\/p>\n\n\n\n<p id=\"3d46\">It also eradicates the need for comments and allows any developer to mentally conceptualize without having to look at the raw code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8f1f\">LAW 5: Functions Should Specify The Parameter And Return Type<\/h2>\n\n\n\n<p id=\"e3ee\">When defining a function, you want to always specify what the arguments\u2019 types are and also what data type the result of the function returns.<\/p>\n\n\n\n<p id=\"da87\">This would help both you and the devs in your team know what to expect without always having to use print statements to get a visual understanding.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"ce98\">Bad Practice<\/p>\n<\/blockquote>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:963\/1*zB-VmY10b1sW6-0HxupT2A.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/m75CDULdgWID6wRPe9SD\" rel=\"noreferrer noopener\" target=\"_blank\">Run code<\/a><\/figcaption><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"d788\">Good Practice<\/p>\n<\/blockquote>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:913\/1*9KDNNZH-xGwK7ZcdtUEMnw.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/360h7AcaNWqxttUPWB16?run=true\" rel=\"noreferrer noopener\" target=\"_blank\">Run code<\/a><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b69c\">LAW 6: A function Must Perform One Functionality Only<\/h2>\n\n\n\n<p id=\"96d2\">Junior devs are fond of breaking this rule. Having a function perform one function is crucial because it helps expose where the bugs are located, enables reusability, and does exactly what the function name says.<\/p>\n\n\n\n<p id=\"793b\">You don\u2019t want to do something like this\u2026<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"9f8e\">(Note that the methods and attributes are just for example purposes.)<\/p>\n<\/blockquote>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:967\/1*ZuWHaYKcmZ41lWkW_3q0TQ.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/Gd6G9k6p8hKdo6WZUQF6\" rel=\"noreferrer noopener\" target=\"_blank\">Python fiddle<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"b8e7\">This checks if the address is valid and after checking returns the latitude and longitude. The function does two things. Checks if the address is valid and returns the geolocation of the address.<\/p>\n\n\n\n<p id=\"6672\">Here is a better way of doing this.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:893\/1*mxOdYOlU5ojDsKRmBN76aA.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/bQD3sPFuC4BWeTx1gdLr\" rel=\"noreferrer noopener\" target=\"_blank\">https:\/\/python-fiddle.com\/saved\/bQD3sPFuC4BWeTx1gdLr<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"2a81\">The above functions do only one thing and nothing more. Although it may seem more verbose, it\u2019s a lot more concise and readable.<\/p>\n\n\n\n<p id=\"38f9\">Knowing exactly what is \u201cone\u201d functionality can be a bit difficult, especially for new devs. You need to be very specific on what you want a function to do.<\/p>\n\n\n\n<p id=\"d662\">Usually, if you can extract or group some of the actions in a function as a whole other function, then it\u2019s probably doing more than one thing.<\/p>\n\n\n\n<p id=\"498c\">Another way you can tell is if it has more than one level of abstraction\u2026<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2faf\"><mark>LAW 7: Functions Should Be At The Same Level Of Abstraction<\/mark><\/h2>\n\n\n\n<p id=\"0354\">When we talk about functions being at the same level of abstraction, we\u2019re referring to the idea that a function should perform a single, well-defined task. That task should be at a consistent level of abstraction throughout the function.<\/p>\n\n\n\n<p id=\"849c\">In other words, the function should focus on a specific level of detail or complexity, and all the functions\u2019 operations should operate at that same level.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"ddfc\">Good Practice<\/p>\n<\/blockquote>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:724\/1*qggU6SP1MqB4UXvxvXgEzQ.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/ezGiYtWK72HXiVm65azM?run=true\" rel=\"noreferrer noopener\" target=\"_blank\">https:\/\/python-fiddle.com\/saved\/ezGiYtWK72HXiVm65azM?run=true<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"7c63\">This function has statements that are of a low level of abstraction. Things like&nbsp;<code>sum<\/code>,&nbsp;<code>len,<\/code>&nbsp;etc.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"286e\">Bad Practice<\/p>\n<\/blockquote>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1103\/1*vEnd7ouHN4dTO8LOGB2bNA.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/joPVBO1dQJk0bgYZsGU0?run=true\" rel=\"noreferrer noopener\" target=\"_blank\">run code here<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"4985\">This function, for instance, has a bunch of levels of abstraction.<code>&nbsp;get_numbers()<\/code>&nbsp;is a high level of abstraction, the list comprehension is an intermediate level of abstraction, and&nbsp;<code>sum<\/code>&nbsp;is a low level of abstraction.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/rest-api-why-many-programmers-might-be-frauds-5e95140db96b?source=post_page-----6942c7cafd56--------------------------------\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/rest-api-why-many-programmers-might-be-frauds-5e95140db96b?source=post_page-----6942c7cafd56--------------------------------\">Basic REST API Principles That make you a 1% programmer.<\/a><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/rest-api-why-many-programmers-might-be-frauds-5e95140db96b?source=post_page-----6942c7cafd56--------------------------------\">And it only takes 10 minutes<\/a><\/h3>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/rest-api-why-many-programmers-might-be-frauds-5e95140db96b?source=post_page-----6942c7cafd56--------------------------------\">medium.com<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fa85\">LAW 8: A Function and It\u2019s Argument(s) Should Be Like Brothers And Sisters<\/h2>\n\n\n\n<p id=\"9695\">A function name should be closely tied to its arguments. You don\u2019t want to have a function that seems to do one thing and the arguments passed do not correlate with the function name.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"b957\">Bad Practice<\/p>\n<\/blockquote>\n\n\n\n<p id=\"7f63\"><code>write(True)<\/code><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"f7d7\">Good Practice<\/p>\n<\/blockquote>\n\n\n\n<p id=\"7bca\"><code>write(name)<\/code><\/p>\n\n\n\n<p id=\"273f\">The second one is more descriptive of what exactly the function is doing. It is clear to whoever reads this that we are writing a name.<\/p>\n\n\n\n<p id=\"839d\">The first one isn\u2019t as explicit as the second. You have to make guesses and possibly even have to view the entire function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"967d\">LAW 9: Functions Should Be Small<\/h2>\n\n\n\n<p id=\"0d86\">A function is meant to be reusable. And the bigger the function gets, the less likely it is to be reusable. This also correlates to why a function should do only one thing. If it does only one thing, there\u2019s a high chance it\u2019s going to be small.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"dee4\">I plan to start posting content on linkedln too. so if you\u2019re interested:&nbsp;<strong>My Linkedln: https:\/\/www.linkedin.com\/in\/alexanderobidiegwu<\/strong><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7f4f\">LAW 10: Avoid Noise\/Redundant Words<\/h2>\n\n\n\n<p id=\"5e66\">There are times when devs use words that don\u2019t provide any further clarification on a variable or function\u2019s meaning. Things like this:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:670\/1*N4x1Fw0U_zsjdu4f-JKq_Q.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/BfPEC7YYSEHQhz2xgGTW\" rel=\"noreferrer noopener\" target=\"_blank\">https:\/\/python-fiddle.com\/saved\/BfPEC7YYSEHQhz2xgGTW<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"c165\">Without having prior knowledge of the function\u2019s implementations, a developer seeing this doesn\u2019t know which function to use.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"11d6\">LAW 11: Do Not Be A Dirty Programmer<\/h2>\n\n\n\n<p id=\"393c\">Any senior dev would tell you he only feels clean when his codes are clean. This is because a dirty code makes up a dirty programmer. A clean code encourages everyone on the team to continue writing clean code. You must aim to always write clean code.<\/p>\n\n\n\n<p id=\"6a75\">But what is a clean code? A clean code is well structured and arranged.<\/p>\n\n\n\n<p id=\"0362\">A clean code doesn\u2019t hide bugs. It exposes anywhere a bug could hide to the programmer and makes room for an easy fix without complete refactoring.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ad76\">LAW 12: Open Closed Principles<\/h2>\n\n\n\n<p id=\"a10d\">The open-closed principle (OCP) states that a class, method, or function must be open for extension but not modification. This means that any class, method, or function defined can be easily reused or extended for multiple instances without changing its code.<\/p>\n\n\n\n<p id=\"8b74\">Let\u2019s take for instance, we have a class called address.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1193\/1*GENI8yqWOC_lplpDGe0OjQ.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/6kfW6eccopYfotqaKlcR?run=true\" rel=\"noreferrer noopener\" target=\"_blank\">https:\/\/python-fiddle.com\/saved\/6kfW6eccopYfotqaKlcR?run=true<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"befd\">This fails to adhere to OCP because whenever there\u2019s a new country, we would need to write a new&nbsp;<code>if<\/code>&nbsp;statement to complement that. This might seem simple now but imagine we have 100 or more countries to take into account. How would that look?<\/p>\n\n\n\n<p id=\"00e7\">This is where OCP comes into play.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1260\/1*I5MglDAyqDeIfPqceEYymg.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\"><a href=\"https:\/\/python-fiddle.com\/saved\/AEbfUZvVQ0k55RyHcypB\" rel=\"noreferrer noopener\" target=\"_blank\">https:\/\/python-fiddle.com\/saved\/AEbfUZvVQ0k55RyHcypB<\/a><\/figcaption><\/figure>\n\n\n\n<p id=\"8de3\">This is a more robust solution because now we don\u2019t need to modify either the class or its functions. If we ever want to consider a country and its capital, we can simply adjust our&nbsp;<code>capital<\/code>&nbsp;dictionary.<\/p>\n\n\n\n<p id=\"31ac\">Another common example you would see is using class inheritance.<\/p>\n\n\n\n<p id=\"5817\">For example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1260\/1*HNehsIzSEbBV6ujfrwpe0Q.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"4d4b\">This is a wrong method because anytime we want to add a new payment method, we would always need to modify the&nbsp;<code>PaymentProcessor<\/code>&nbsp;class.<\/p>\n\n\n\n<p id=\"3cd2\">A better way to do this is:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1260\/1*uQZDRkmLFSBPnxiuSmOAng.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"58ec\">This way, whenever we need to add a new payment option, say crypto or paypal, we wouldn\u2019t need to edit or modify any class to achieve this. we could simply do this:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1260\/1*N5V-GsG7dBYefF3zg2Qlfg.png\" alt=\"\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b926\">LAW 13: Liskov Substitution Principle<\/h2>\n\n\n\n<p id=\"2dea\">If we look at the previous principle, when making payments using crypto, we don\u2019t exactly specify the cryptocurrency we are transferring. We only specify an amount. So suppose we want to specify a cryptocurrency, we would usually do something like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from abc import abstractmethod<br><br>class PaymentProcessor:<br><br>   @abstractmethod<br>   def pay_tax(amount, crypto):<br>      pass<\/pre>\n\n\n\n<p id=\"6ddf\">Then when calling each payment processor, we declare the crypto argument as a&nbsp;<code>None<\/code>&nbsp;type or give it a default value to avoid passing in any argument if not needed. Both cases fail to adhere to the Liskov Substitution Principle.<\/p>\n\n\n\n<p id=\"dbd5\">This is because the parent class or the abstract class, contains an argument that isn\u2019t relevant to most of our subclasses<\/p>\n\n\n\n<p id=\"3699\">The&nbsp;<strong>Liskov Substitution principle (LSP)<\/strong>&nbsp;states that&nbsp;<em>\u201cObjects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program\u201d<\/em>.<\/p>\n\n\n\n<p id=\"bcc9\">To adhere to LSP, we would need to define the cryptocurrency within the&nbsp;<code>CryptoPaymentProcessor<\/code>&nbsp;class to avoid any irrelevant clash with other subclasses.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class CryptoPaymentProcessor(PaymentProcessor):<br>   def __init__(self, crypto):<br>      self.crypto = crypto<br>  <br>   def pay_tax(amount):<br>      print(f'Your {self.crypto} wallet is being processed for tax payment')<br>      print(f'You are to be charged {amount}')<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"d114\">LAW 14: Know When To Use A Comment<\/h2>\n\n\n\n<p id=\"ca39\">Every time you need to use a comment, be ashamed of your inability to express yourself in code. But there are some situations whereby the use of comments can actually help to express the underlying workings of a code than the code itself. Here are 5 best examples of \u201cgood\u201d comments.<\/p>\n\n\n\n<p id=\"51bc\"><strong>Informative comments<br><\/strong>Making comments informative can always help express the code to the reader. A comment that highlights the return value of a function, for instance, would provide more clarity. But comments like this can be made redundant through the use of well-descriptive functions or variable names.<\/p>\n\n\n\n<p id=\"b57e\"><strong>TODO comments<br><\/strong>Comments like this help other programmers know that this is an unfinished function\/task or it requires modification. Maybe there\u2019s a better way to implement a certain function that wasn\u2019t taken advantage of. Maybe the code fails periodically.<\/p>\n\n\n\n<p id=\"878c\">Regardless of your reason, comments like this provide more value than they take.&nbsp;<code>TODO comments<\/code>&nbsp;are also less likely to be left untouched as the code changes or improves because they are usually remembered to be removed once the task has been completed or modified properly.<\/p>\n\n\n\n<p id=\"f9d8\"><strong>Warning of consequences<br><\/strong>Sometimes, we want to tell other developers about potential landmines. Stepping on these landmines could have some unforeseen consequences. And we want to all survive through the day. Comments can save the day in this situation.<\/p>\n\n\n\n<p id=\"d421\">Suppose a certain code takes time or has the possibility of overloading certain systems, a warning like&nbsp;<code>#CONSUMES A LOT OF COMPUTING RESOURCES<\/code>&nbsp;would be beneficial to a reader or other programmers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0b92\">LAW 15: When Is A Comment Bad?<\/h2>\n\n\n\n<p id=\"131d\"><strong>Noise comments<\/strong><br>These are comments that reinstate the obvious. They provide no further information and only increase the verbosity of the code. A lot of times, we skip through comments like this when we see one. Examples of noise comments are:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># adds to animal list<br>animal.append(dog)<\/pre>\n\n\n\n<p id=\"4e8e\"><strong>Non Local information<\/strong><br>One mistake a lot of programmers make when using comments is giving information about global information locally. When writing comments, ensure that it remains relevant only to the function or statement it is referencing. Anything outside of that should be pruned out.<\/p>\n\n\n\n<p id=\"3bab\"><strong>Unobvious comments<\/strong><br>We often write comments that seem obvious to us but not to someone else. The connection between your comments and the function referenced must be clear. They must both follow the same step or procedure at sync. You don\u2019t want your comment to need to have its comment as well.<\/p>\n\n\n\n<p id=\"6427\"><strong>Short Functions<\/strong><br>Most likely we do not need a comment for a short function. The shorter\/smaller the function, the more likely it can be described with a good name. Hence, they are usually self-descriptive.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/3-ways-to-run-a-python-function-asynchronously-b00e860fed6d?source=post_page-----6942c7cafd56--------------------------------\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/3-ways-to-run-a-python-function-asynchronously-b00e860fed6d?source=post_page-----6942c7cafd56--------------------------------\">3 Ways To Run A Python Function Asynchronously<\/a><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/3-ways-to-run-a-python-function-asynchronously-b00e860fed6d?source=post_page-----6942c7cafd56--------------------------------\">You would most likely fail as a Python programmer without understanding this ground concept. Asynchronous Programming.<\/a><\/h3>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/3-ways-to-run-a-python-function-asynchronously-b00e860fed6d?source=post_page-----6942c7cafd56--------------------------------\">medium.com<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"39ce\">LAW 16: Keep Source Files Short<\/h2>\n\n\n\n<p id=\"e31a\">A source file should be between 100\u2013200 lines with 500 lines at most. Unless you have very good reasons to choose otherwise. Keeping a source file short has various obvious benefits such as reusability and readability. They are also easier to maintain and update since we spend less time scrolling and trying to connect the dots.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"f247\">LAW 17: Know When To Use Blank Lines<\/h2>\n\n\n\n<p id=\"4685\">Blank lines are a way to tell the reader we are progressing into a new and separate concept. Each group of lines represents a complete thought. It helps readers understand when a thought ends.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c20f\">LAW 18: Keep Related Lines Of Code\/Functions\/Classes Close<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"c968\">Go where you are valued<\/p>\n<\/blockquote>\n\n\n\n<p id=\"ee61\">Can you remember when you had to scroll all the way to the top of the script, just to find out what a function does and how it relates to where it\u2019s being called?<\/p>\n\n\n\n<p id=\"e15f\">The worst part of this is you can\u2019t understand the relation in one glance. It\u2019s a back-and-forth movement. Once you\u2019ve experienced this, you\u2019ll understand how valuable it is to keep related code to each other.<\/p>\n\n\n\n<p id=\"d8a5\">A function\/Variable should be as close to where it\u2019s needed the most or has the most importance. It should be furthest away from where it has the least importance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6ede\">LAW 19: Know When To Use White Spaces<\/h2>\n\n\n\n<p id=\"8162\">We use white spaces to show that two things are not strongly related and no white space to associate things that are strongly related. For instance when defining functions\u2026<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def create(name):<br>    print(name)<\/pre>\n\n\n\n<p id=\"a500\">There exists no whitespace between the parenthesis between the function and the name variable. If there was, it would look very disjointed and uncoordinated\u2026<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def create (name):<br>    print (name)<\/pre>\n\n\n\n<p id=\"6bfc\">Arguments passed into a function, should be separated to show that the arguments are separate.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"30f4\">LAW 20: Obey Team Rules<\/h2>\n\n\n\n<p id=\"ba05\">Almost every developer has his\/her style. From the way we name our files, to the way we write print statements.<\/p>\n\n\n\n<p id=\"fd92\">But when it comes to working with other devs, you want to dumb down those personal preferences and adopt the team\u2019s preferences. Not everyone might be able to see beauty in your code the way you do.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b38f\">LAW 21: Avoid Magic Numbers<\/h2>\n\n\n\n<p id=\"1441\">A Magic Number is a hard-coded value that may change at a later stage, but that can be therefore hard to update.<\/p>\n\n\n\n<p id=\"24da\">For example, let\u2019s say you have a Page that displays the last 50 Orders in a \u201cYour Orders\u201d Overview Page. 50 is the Magic Number here because it\u2019s not set through standard or convention, it\u2019s a number that you made up for reasons outlined in the spec.<\/p>\n\n\n\n<p id=\"8642\">Now, what you do is you have the 50 in different places \u2014 your SQL script (<code>SELECT TOP 50 * FROM orders<\/code>), your Website (Your Last 50 Orders), your order login (<code>for (i = 0; i &lt; 50; i++)<\/code>) and possibly many other places.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>SELECT TOP 50 * FROM orders<br><br># Good<br>NUM_OF_ORDERS = 50<br>SELECT TOP NUM_OF_ORDERS * FROM orders<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6b01\">LAW 22: Avoid Deep Nesting<\/h2>\n\n\n\n<p id=\"d9b5\">Limit the levels of nesting within loops, conditionals, or functions to improve readability.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>if x:<br>    if y:<br>        do_something()<br><br># Good<br>if x and y:<br>    do_something()<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0080\">LAW 23: Avoid Temporary Variables<\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>temp_result = calculate(x, y)<br>final_result = temp_result * 2<br><br># Good<br>final_result = calculate(x, y) * 2<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"052f\">LAW 24: Avoid Cryptic Abbreviations<\/h2>\n\n\n\n<p id=\"0cce\">Use descriptive names instead of cryptic abbreviations to enhance readability.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>def calc(x, y):<br>    pass<br><br># Good<br>def calculate_total_price(quantity, unit_price):<br>    pass<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7641\">LAW 25: Avoid Hardcoding Paths<\/h2>\n\n\n\n<p id=\"1609\">Refrain from hardcoding file paths or URLs; use configuration files or environment variables instead.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>file_path = \"\/path\/to\/file.txt\"<br><br># Good<br>import os<br>file_path = os.getenv(\"FILE_PATH\")<\/pre>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/5-scalability-rules-to-follow-in-your-next-project-06a4b6db998b?source=post_page-----6942c7cafd56--------------------------------\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/5-scalability-rules-to-follow-in-your-next-project-06a4b6db998b?source=post_page-----6942c7cafd56--------------------------------\">10+ Scalability Laws To Follow In Your Next Project.<\/a><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/5-scalability-rules-to-follow-in-your-next-project-06a4b6db998b?source=post_page-----6942c7cafd56--------------------------------\">Don\u2019t Touch your keyboard without understanding this<\/a><\/h3>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/5-scalability-rules-to-follow-in-your-next-project-06a4b6db998b?source=post_page-----6942c7cafd56--------------------------------\">medium.com<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ab55\">LAW 26: Always use Try-Catch-Finally Statements<\/h2>\n\n\n\n<p id=\"79f2\">When writing code, it\u2019s always best to include error handling also. This can help speed up the debugging process and increase the sophistication of the code while keeping it clean and manageable.<\/p>\n\n\n\n<p id=\"6c95\">You want to use try-catch statements when a certain code is more likely to return an error.<\/p>\n\n\n\n<p id=\"bdda\">Things like API requests, file handling, etc tend to fail or raise errors due to one reason or the other. Using try-catch statements for multiplication or division is just uncalled for and creates more problems than it solves.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"83ea\">LAW 27: Provide Context with Exceptions<\/h2>\n\n\n\n<p id=\"eaa2\">Whenever you catch an exception, it should provide enough context for anyone who encounters it to know where the problem is from and debug accordingly.<\/p>\n\n\n\n<p id=\"1528\">Create informative error messages along with your exceptions which can be done when printing the error. Mention the context in which the operation failed and the type of failure.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"dd26\">Law 28: Avoid Using Multiple Exception Class<\/h2>\n\n\n\n<p id=\"997e\">Have you ever seen a code like the one below\u2026<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br> pass<br>except ValueError:<br> pass<br>except TypeError:<br> pass<br>except IndexError:<br> pass<br>except KeyError:<br> pass<br>except FileNotFoundError:<br> pass<\/pre>\n\n\n\n<p id=\"768e\">This is extremely bogus and takes away (in verbosity, complexity, and maintenance) the additional help it provides in error handling.<\/p>\n\n\n\n<p id=\"123d\">It\u2019s often better to use a more general exception to catch any sort of error we might come across. This type of exception, by default, includes the type of error we got.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:<br> pass<br>except Exception:<br> pass<\/pre>\n\n\n\n<p id=\"b836\">Only be specific about the type of error you want to catch, when you want all other errors to pass through.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"d6ae\">LAW 29: A function must either mutate or return something, but not both.<\/h2>\n\n\n\n<p id=\"52dc\">Whenever we are creating a function, we should keep in mind what exactly that function is supposed to do. Does it mutate the arguments passed? Or does it need to return something?<\/p>\n\n\n\n<p id=\"dc64\">If the function mutates the argument(s) passed, we only need to do that in that function and nothing else.<\/p>\n\n\n\n<p id=\"04d5\">But what do I mean by mutation? If the function changes the contents of the argument(s) or changes the data type of the arguments, it mutates.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def changed(array):<br>    array.append('hello')<\/pre>\n\n\n\n<p id=\"8028\">If the argument(s) is used to create another variable, then it doesn\u2019t mutate. For instance, if an argument called&nbsp;<code>time<\/code>&nbsp;was used to calculate a&nbsp;<code>distance<\/code>, then it doesn\u2019t mutate, which means distance can be returned in that function.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def calculate_distance(time, speed):<br>    distance = speed * time<br>    return distance<\/pre>\n\n\n\n<p id=\"8950\">But there\u2019s a way to get the best of both worlds. You can copy the argument(s) of the function and perform mutation on those. This way we avoid any side effects.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def changed(array):<br>    array_copy = array[:]<br>    array_copy.append(4)<br>    return array_copy<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"95ee\">LAW 30: Not all function names should be verbs<\/h2>\n\n\n\n<p id=\"b48d\">Yes, I know. I previously said all function names should be verbs, which is true generally, but there are times when a function name should take the form of a noun. And knowing when it should take either is based on the previous law\/ law 29.<\/p>\n\n\n\n<p id=\"c28e\">If a function returns something without mutating its arguments, the function\u2019s name should be a noun. If a function mutates the arguments and returns none, it should be a verb.<\/p>\n\n\n\n<p id=\"9bc3\">This is a common convention built into Python itself. Methods such as sort, and append are verbs because they mutate the data type and return&nbsp;<code>None<\/code>&nbsp;while methods like&nbsp;<code>sorted, sum, product<\/code>&nbsp;are all nouns because they don\u2019t mutate any arguments passed and return a new copy of the data.<\/p>\n\n\n\n<p id=\"1f9f\">There are obviously exceptions to this and whenever you feel you\u2019ve encountered one, feel free to fall back on using verbs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3e7d\">LAW 31: Classes should be small<\/h2>\n\n\n\n<p id=\"7ed9\">Yep! Classes should be as small as possible. Just like functions.<\/p>\n\n\n\n<p id=\"419f\">The only difference is that in functions, size is determined by the number of lines in that function while in classes, it is determined by the number of responsibilities in that class.<\/p>\n\n\n\n<p id=\"0a9b\">Usually, a class name represents the kind of responsibilities it might possess but when the name is ambiguous or too general, most likely we are giving it too much responsibility.<\/p>\n\n\n\n<p id=\"7667\">This takes us back to SRP (single responsibility principle) which states that a class should only have one reason \u2014 one responsibility \u2014 to change.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"caca\">LAW 32: Classes should have a small number of instance variables<\/h2>\n\n\n\n<p id=\"d89c\">Instance variables, in case you don\u2019t know, are variables that are defined when the class is defined or instantiated.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Animal:<br>    def __init__(self, name):<br>        self.name = name #instance variable<\/pre>\n\n\n\n<p id=\"59b6\">If all our functions are related to the class responsibility, there\u2019s no reason why we should have a lot of instance variables.<\/p>\n\n\n\n<p id=\"7aac\">When we begin to have tons of instance variables, is when certain functions in the classes deviate away from the core responsibility of the class.<\/p>\n\n\n\n<p id=\"22f8\">These functions tend to come with their own variables that other functions in the class do not need.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1b89\">LAW 33: Your classes should be cohesive.<\/h2>\n\n\n\n<p id=\"a63a\">All the functions in your class should contain one or more of the instance variables. The more your functions relate to or contain the instance variables in your class, the more cohesive your class is.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b4d4\">LAW 34: Use the with Statement for Resource Management<\/h2>\n\n\n\n<p id=\"868a\">Use the&nbsp;<code>with<\/code>&nbsp;statement to automatically manage resources like files or database connections, ensuring they are properly closed or released.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>file = open(\"example.txt\", \"r\")<br>data = file.read()<br>file.close()<br><br># Good<br>with open(\"example.txt\", \"r\") as file:<br>    data = file.read()<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4a88\">LAW 35: Avoid Complex Ternary Expressions<\/h2>\n\n\n\n<p id=\"4e5a\">Refrain from using overly complex ternary expressions; favor readability over brevity to make&nbsp;<a href=\"https:\/\/python-fiddle.com\/saved\/DVZ1May7X9VN4mZr5kqf?run=true\" rel=\"noreferrer noopener\" target=\"_blank\">code<\/a>&nbsp;more understandable.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>result = \"even\" if number % 2 == 0 else \"odd\" if number % 3 == 0 else \"neither\"<br><br># Good<br>if number % 2 == 0:<br>    result = \"even\"<br>elif number % 3 == 0:<br>    result = \"odd\"<br>else:<br>    result = \"neither\"<\/pre>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/10-hard-python-projects-for-intermediates-to-boost-your-python-skills-portfolio-79a2488ec8a4?source=post_page-----6942c7cafd56--------------------------------\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/10-hard-python-projects-for-intermediates-to-boost-your-python-skills-portfolio-79a2488ec8a4?source=post_page-----6942c7cafd56--------------------------------\">10 Hard Python Projects For Intermediates To Boost Your Python Skills &amp; Portfolio.<\/a><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/10-hard-python-projects-for-intermediates-to-boost-your-python-skills-portfolio-79a2488ec8a4?source=post_page-----6942c7cafd56--------------------------------\">Timeline to finish each project \u2014 1 month<\/a><\/h3>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/10-hard-python-projects-for-intermediates-to-boost-your-python-skills-portfolio-79a2488ec8a4?source=post_page-----6942c7cafd56--------------------------------\">medium.com<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7745\">LAW 36: Use \u2018is\u2019 and \u2018is not\u2019 for Identity Comparison<\/h2>\n\n\n\n<p id=\"53db\">Most of the time, we use&nbsp;<code>==<\/code>&nbsp;to check the comparison between two variables. This is usually okay for immutable data types like strings or integers because immutable objects with the same value are usually stored in the same memory location, so a memory location check is not needed.<\/p>\n\n\n\n<p id=\"9f0f\">But when dealing with mutable data types, such as&nbsp;<code>list, dicts&nbsp;<\/code>and custom objects, it\u2019s often better to use the&nbsp;<code>is<\/code>&nbsp;comparator because it checks the subtype of the variable and the memory location.<\/p>\n\n\n\n<p id=\"f5be\">The memory location of mutable objects are usually not the same due to the way Python works. Python stores mutable objects in different memory locations because they can be changed at any time and each of them must be independent of one another even though.<\/p>\n\n\n\n<p id=\"0eae\">Strings, tuples, and integers cannot be changed once created.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Run this using the link below:<br>https:\/\/python-fiddle.com\/saved\/nV6iEIyBuHm2mevD9Bhg<br><br># Example 2: Checking if two lists refer to the same object<br>list1 = [1, 2, 3]<br>list2 = [1, 2, 3]<br><br># Less preferred: Using ==<br>if list1 == list2:<br>    print(\"Lists are equal in value\")<br><br># Preferred: Using is<br>if list1 is list2:<br>    print(\"Lists are the same object\")<br><br># Note: In this case, list1 and list2 are different objects with the same value,<br># so using `is` would give a different result than `==`.<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c8ec\">LAW 37: Dependency Inversion Principle<\/h2>\n\n\n\n<p id=\"d0d9\">The Dependency Inversion Principle (DIP) is a fundamental principle of object-oriented design that promotes loose coupling between components and facilitates easier maintenance and extension of software systems.<\/p>\n\n\n\n<p id=\"c6ec\">It states that high-level modules should not depend on low-level modules, but both should depend on abstractions.<\/p>\n\n\n\n<p id=\"5246\">In other words, classes should depend on interfaces or abstract classes rather than on concrete implementations.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>class Logger:  <br>    def log(self, message):  <br>        with open('log.txt', 'a') as f:  <br>            f.write(message + '\\n')  <br>  <br>class Calculator:  <br>    def __init__(self):  <br>        self.logger = Logger()<br>   <br>    def add(self, x, y):  <br>        result = x + y  <br>        self.logger.log(f\"Added {x} and {y}, result = {result}\")  <br>        return result<\/pre>\n\n\n\n<p id=\"a05d\">In the example above, we define the class&nbsp;<code>Logger<\/code>&nbsp;and directly create a new instance of it in our&nbsp;<code>Calcuator<\/code>&nbsp;class. This means that&nbsp;<code>Calculator<\/code>&nbsp;now depends on&nbsp;<code>Logger<\/code>&nbsp;class and if for any reason we change&nbsp;<code>Logger<\/code>&nbsp;class, we now also have to modify&nbsp;<code>Calculator<\/code>&nbsp;class.<\/p>\n\n\n\n<p id=\"43e8\">And as you can see this also fails to adhere to the open closed principle (open for extension, closed for modification).<\/p>\n\n\n\n<p id=\"86d9\">This tight coupling makes the code harder to test because we can no longer simply use a fake logger class when testing.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># good<br>from abc import ABC, abstractmethod  <br>  <br>class LoggerInterface(ABC):  <br>    @abstractmethod  <br>    def log(self, message):  <br>        pass  <br>  <br>class Logger(LoggerInterface):  <br>    def log(self, message):  <br>      with open('log.txt', 'a') as f:  <br>          f.write(message + '\\n')  <br>  <br>class Calculator:  <br>    def __init__(self, logger: LoggerInterface):  <br>        self.logger = logger  <br>   <br>    def add(self, x, y):  <br>        result = x + y  <br>        self.logger.log(f\"Added {x} and {y}, result = {result}\")  <br>        return result<\/pre>\n\n\n\n<p id=\"a1d8\">This promotes modularity because changes to one component do not necessarily require changes to other components as long as the interface remains consistent.<\/p>\n\n\n\n<p id=\"7541\">This modularity enables easier understanding, modification, and extension of the codebase.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"19ef\">LAW 38: Avoid Using \u2018assert\u2019 for Data Validation<\/h2>\n\n\n\n<p id=\"ea60\">Use&nbsp;<code>assert<\/code>&nbsp;statements for debugging and development purposes only; avoid using them for data validation in production&nbsp;<a href=\"https:\/\/python-fiddle.com\/saved\/exTVcu23yFXkRInFhUbO\" rel=\"noreferrer noopener\" target=\"_blank\">code<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>assert x &gt; 0, \"x should be positive\"<br><br># Good<br>if x &lt;= 0:<br>    raise ValueError(\"x should be positive\")<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6486\">LAW 39: Avoid Hard-Coded Numbers<\/h2>\n\n\n\n<p id=\"dbf4\">Use named constants instead of hard-coded values. Write constants with meaningful names that convey their purpose. This improves clarity and makes it easier to modify the code.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def calculate_discount(price):  <br>    discount = price * 0.1 # 10% discount  <br>    return price - discount<\/pre>\n\n\n\n<p id=\"8240\">The example below uses the hard-coded number 0.1 to represent a 10% discount.<\/p>\n\n\n\n<p id=\"60d5\">This makes it difficult to understand the meaning of the number (without a comment) and adjust the discount rate if needed in other parts of the function.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def calculate_discount(price):  <br>    TEN_PERCENT_DISCOUNT = 0.1  <br>    discount = price * TEN_PERCENT_DISCOUNT  <br>    return price - discount<\/pre>\n\n\n\n<p id=\"a61a\">The improved code replaces the hard-coded number with a named constant&nbsp;<code>TEN_PERCENT_DISCOUNT<\/code>. The name instantly conveys the meaning of the value, making the code more self-documenting.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"40ba\">LAW 40: Follow the DRY (Don\u2019t Repeat Yourself) Principle<\/h2>\n\n\n\n<p id=\"6c85\">Avoid writing the same code more than once. Instead, reuse your code using functions, classes, modules, libraries, or other abstractions. This makes your code more efficient, consistent, and maintainable.<\/p>\n\n\n\n<p id=\"073b\">It also reduces the risk of errors and bugs as you only need to modify your code in one place if you need to change or update it.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br><br>def calculate_book_price(quantity, price):  <br>    return quantity * price  <br>def calculate_laptop_price(quantity, price):  <br>    return quantity * price<br><br># Good<br><br>def calculate_product_price(product_quantity, product_price):  <br>    return product_quantity * product_price<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0e41\">LAW 41: Follow Established Code-Writing Standards<\/h2>\n\n\n\n<p id=\"82fd\">It\u2019s important to follow commonly accepted conventions in terms of spacing, comments, and naming. Most programming languages have community-accepted coding standards and style guides, for example,&nbsp;<a href=\"https:\/\/peps.python.org\/pep-0008\/\" rel=\"noreferrer noopener\" target=\"_blank\">PEP 8 for Python<\/a><\/p>\n\n\n\n<p id=\"0f0c\">Some common conventions are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use&nbsp;<strong>snake_case<\/strong>&nbsp;for variable, function, and class names.<\/li>\n\n\n\n<li>Use spaces over tabs for indentation.<\/li>\n\n\n\n<li><a href=\"https:\/\/peps.python.org\/pep-0008\/#indentation\" rel=\"noreferrer noopener\" target=\"_blank\">Use 4 spaces per indentation level<\/a><\/li>\n\n\n\n<li>Limit all lines to a maximum of 79 characters.<\/li>\n\n\n\n<li><a href=\"https:\/\/peps.python.org\/pep-0008\/#should-a-line-break-before-or-after-a-binary-operator\" rel=\"noreferrer noopener\" target=\"_blank\">Break a line before a binary operator<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7eb0\">LAW 42: Law of Demeter<\/h2>\n\n\n\n<p id=\"5231\">The law of Demeter, in simple terms, means that a&nbsp;<code>module\/function\/class<\/code>&nbsp;can have knowledge or make reference to another&nbsp;<code>module\/function\/class<\/code>&nbsp;immediate neighbors but should not have any knowledge further than that.<\/p>\n\n\n\n<p id=\"7fee\">By immediate neighbors, this means methods or functions or variables that can be directly accessed.<\/p>\n\n\n\n<p id=\"3333\">An example should clear this up\u2026<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Order:<br>    def __init__(self, customer):<br>        self.customer = customer<br><br>    def get_customer_name(self):<br>        # Violation: Order knows too much about the customer's structure<br>        return self.customer.get_profile().get_name()<\/pre>\n\n\n\n<p id=\"a344\">In this example, the&nbsp;<code>Order<\/code>&nbsp;class directly accesses the customer\u2019s profile to retrieve the customer\u2019s name. This violates the Law of Demeter because&nbsp;<code>Order<\/code>&nbsp;is reaching into the internal structure of the&nbsp;<code>Customer<\/code>&nbsp;object to access its profile and name.<\/p>\n\n\n\n<p id=\"5fd1\">It has gone past an immediate neighbor and now knows too much about the customer\u2019s object.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Order:<br>    def __init__(self, customer):<br>        self.customer = customer<br><br>    def get_customer_name(self):<br>        # Adherence: Order only interacts with its immediate collaborator<br>        return self.customer.get_name()<\/pre>\n\n\n\n<p id=\"32be\">In this adherent example, the&nbsp;<code>Order<\/code>&nbsp;class only interacts with its immediate collaborator, the&nbsp;<code>Customer<\/code>&nbsp;object, and calls a method directly on it to retrieve the customer\u2019s name.<\/p>\n\n\n\n<p id=\"11f6\">It does not reach into the internal structure of the&nbsp;<code>Customer<\/code>&nbsp;object, thus following the Law of Demeter.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5bdd\">LAW 43: Readability over conciseness<\/h2>\n\n\n\n<p id=\"d0d0\">Code needs to work and be understood by the machine executing it. However,&nbsp;<strong>other developers also need to be able to understand the code<\/strong>, especially if you are working on a project with multiple people.<\/p>\n\n\n\n<p id=\"08ea\">That is why the readability of code is always more important than its conciseness when it comes to software development.<\/p>\n\n\n\n<p id=\"63a7\">There is no point in writing concise code if other developers cannot understand it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5ecd\">LAW 44: Keep Imports Clean<\/h2>\n\n\n\n<p id=\"fc1e\">Import only the necessary modules and symbols to keep the import section clean and improve readability. When we import everything (*) from a module, all variables, functions, and classes are also imported which can make it very difficult to know where a certain function\/class originated from and can also be a pain when using modern IDEs.<\/p>\n\n\n\n<p id=\"e713\">Imagine you want to write a function with the name&nbsp;<code>get_file<\/code>. You click&nbsp;<code>g<\/code>&nbsp;and your IDE recommends you a list of functions\/classes\/variables that start with the letter&nbsp;<code>g<\/code>. It can become quite chaotic.<\/p>\n\n\n\n<p id=\"3984\">This becomes more of a pain when you want to call that function. Your function name could be lost in between the recommendations and now your IDE becomes more of a problem than an efficient solution.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>from module import *<br><br># Good<br>from module import symbol1, symbol2<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3f5a\">LAW 45: Do Not Return Null\/None<\/h2>\n\n\n\n<p id=\"966d\">Usually, when we define functions, by default they return&nbsp;<code>None<\/code>&nbsp;if no return value is specified. But when we explicitly return&nbsp;<code>None<\/code>, we are indirectly telling the reader that the function can return something else except&nbsp;<code>None<\/code>.<\/p>\n\n\n\n<p id=\"af27\">And if this is not true, it can cause a lot of miscommunications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"88a1\">LAW 46: Separate Construction From Its Use<\/h2>\n\n\n\n<p id=\"294b\">Separation of concerns has been a very fundamental principle in software engineering. We need to know how to separate the construction of our software from how it\u2019s being used.<\/p>\n\n\n\n<p id=\"d257\">This often means separating the startup process, \u2014 which is when our dependencies and objects are wired together \u2014 , from the run time logic, \u2014 which is when the logic of the application executes based on inputs from the user or other triggers \u2014 .<\/p>\n\n\n\n<p id=\"f287\">One common way to separate construction from its use is to construct the application logic in a file\/function\/module called&nbsp;<code>main<\/code>.<\/p>\n\n\n\n<p id=\"7701\">The&nbsp;<code>main<\/code>&nbsp;function builds the objects necessary for the application to run smoothly. This frees other modules from being tightly coupled to the application and promotes reusability and modularity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"bb63\">LAW 47: Simple Design Contains All These Rules<\/h2>\n\n\n\n<p id=\"0b02\"><strong>Runs all the tests<\/strong>: A system might have a perfect design on paper but if there\u2019s no way to verify that the system actually works as intended, then the design on paper becomes questionable.<\/p>\n\n\n\n<p id=\"36f4\"><strong>Contains no duplication<\/strong>: Duplication is the primary enemy of a well designed system<\/p>\n\n\n\n<p id=\"256d\"><strong>Expresses the intent of the programmer<\/strong><\/p>\n\n\n\n<p id=\"b108\"><strong>Minimizes the number of classes and methods<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ad10\">LAW 48: Avoid Nested Try-Except Blocks<\/h2>\n\n\n\n<p id=\"1fc3\">Refrain from nesting&nbsp;<code>try-except<\/code>&nbsp;blocks excessively to prevent overly complex error handling logic.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># Bad<br>try:<br>    try:<br>        # Code that might raise errors<br>        pass<br>    except ValueError:<br>        # Handle ValueError<br>        pass<br>except Exception as e:<br>    # Handle any other unexpected errors<br>    pass<br><br># Good<br>try:<br>    # Code that might raise errors<br>    pass<br>except ValueError:<br>    # Handle ValueError<br>    pass<br>except Exception as e:<br>    # Handle any other unexpected errors<br>    pass<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"56ae\">LAW 49: Use Concurrency Only When Needed<\/h2>\n\n\n\n<p id=\"407f\">It\u2019s very easy to write bad code when implementing concurrency functionality.<\/p>\n\n\n\n<p id=\"6ffd\">It\u2019s also very easy to write clean code when implementing very faulty concurrency functionality. Usually, you might not even be aware that it is faulty until a lot of stress is put on the system.<\/p>\n\n\n\n<p id=\"64d0\">You want to pick your battles very smartly.<\/p>\n\n\n\n<p id=\"8894\">There are multiple reasons why your concurrency code might fail. Here are some:<\/p>\n\n\n\n<p id=\"90ed\"><strong>Starvation<\/strong>: Starvation occurs when a thread or process is unable to gain access to a shared resource indefinitely, despite attempting to do so. This can happen when other threads or processes continually acquire and hold the resource, preventing the starving thread from making progress.<\/p>\n\n\n\n<p id=\"c72a\"><strong>Deadlocks<\/strong>: Deadlocks occur when two or more threads or processes are blocked indefinitely, waiting for each other to release resources that they need. This can happen when each process holds one resource and waits for another resource held by another process, creating a cyclic dependency.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/processes-processor-cores-threading-parallelism-asynchronous-operations-and-how-it-all-c7f7390d7535?source=post_page-----6942c7cafd56--------------------------------\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/processes-processor-cores-threading-parallelism-asynchronous-operations-and-how-it-all-c7f7390d7535?source=post_page-----6942c7cafd56--------------------------------\">5 Concepts Every Python Engineer Should Know in 2024<\/a><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/processes-processor-cores-threading-parallelism-asynchronous-operations-and-how-it-all-c7f7390d7535?source=post_page-----6942c7cafd56--------------------------------\">In computer science, understanding how the hardware works hand in hand with software is extremely critical\u2026<\/a><\/h3>\n\n\n\n<p><a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/medium.com\/@alexobidiegwu\/processes-processor-cores-threading-parallelism-asynchronous-operations-and-how-it-all-c7f7390d7535?source=post_page-----6942c7cafd56--------------------------------\">medium.com<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fe7f\">LAW 50: Follow The 49 Rules<\/h2>\n\n\n\n<p id=\"8ad1\">These laws are only there to guide you on your journey as a software engineer. You should abide by them whenever needed.<\/p>\n\n\n\n<p id=\"ed87\">But as you grow in experience and skills, you want to be able to decide when it\u2019s best to follow a certain rule and when it\u2019s not.<\/p>\n\n\n\n<p id=\"bdff\">This gut feeling\/intuition only comes to those who have mastered their craft and if you\u2019re a newbie or you just started your career 2 years ago, it\u2019s usually best you follow these laws like it\u2019s your only ticket to heaven.<\/p>\n\n\n\n<p id=\"13cd\"><em>Most Python developers need somewhere to quickly test their code or debug errors. I developed a website called&nbsp;<\/em><a href=\"https:\/\/python-fiddle.com\/\" rel=\"noreferrer noopener\" target=\"_blank\"><em>python-fiddle.com<\/em><\/a><em>&nbsp;which you can use to quickly test out a code and it uses AI\/LLMs to help find solutions to possible errors.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are hundreds or probably thousands of Python best practices out there and depending on who you ask, you would get some slight variation on a given practice. The internet&#8230; <a class=\"read-more-link\" href=\"https:\/\/tbekk.com\/devstream\/2024\/07\/16\/50-coding-laws-that-would-make-you-a-decent-programmer\/\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[51,87,248,261],"tags":[463,74],"class_list":["post-938","post","type-post","status-publish","format-standard","hentry","category-article","category-coding","category-software-development","category-software-engineering","tag-clean-code","tag-py"],"_links":{"self":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/938","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/comments?post=938"}],"version-history":[{"count":1,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/938\/revisions"}],"predecessor-version":[{"id":939,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/938\/revisions\/939"}],"wp:attachment":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/media?parent=938"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/categories?post=938"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/tags?post=938"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}