Code formatting. What is beautiful code, and how to write it? Use shortcuts for math and string operations


Good day to everyone who is reading now this publication. Today I want to tell you about one of the website building tools that no web resource can do without. This is the site menu, or as they also say site map. Today there are an unlimited number of types and subtypes of menus.

Developers of online stores, blogs, educational services and other resources are experimenting and creating more and more new and unusual cards. After reading the article, you will learn what main groups all types of navigation panels are divided into, you will be able to try each of them, and also learn how to write menu code for an html website. Now let's get down to business!

Tools for creating a navigation bar

There are several ways to create a menu in markup language. Their basic concept is to use an unnumbered list. Thus, in html 4, which is familiar to us, developers write tags on the page

    And
  • .

    As stated in previous publications, pair element

      creates bulleted list, A
    • - one element of the list. For clarity, let's write the code simple menu:

      Navigation

      Site navigation

      • home
      • News of the week
      • Technological advances
      • Chat

      However, with the advent of the platform, the markup language was replenished additional tags. That is why the menu of modern websites is created using a special tag< menu>. In use, this element is no different from bulleted lists.

      Instead of one < ul> is prescribed < menu>. However, significant differences appear when judged from the work side. So, the second example speeds up the work of search programs and robots in . When analyzing the site structure, they immediately understand that this piece of code is responsible for the site map.

      There are horizontal, vertical and drop-down menus. Sometimes the navigation bar is designed as an image. Since the technology segment has expanded, web services are being made adaptive, i.e. The page structure automatically adapts to the device screen size. Let's look at the listed menu groups.

      Let's create a horizontal navigation model

      This type of navigation is the most popular. When the panel is designed horizontally, all menu items are located in the page header or in the “footer” (sometimes navigation elements are duplicated, appearing simultaneously both above and below).

      As an example, we will create a horizontal panel whose menu items will be styled as css help(cascading style sheets), or rather transformed. Yes, everyone separate element will be located in a beveled rectangle. Intrigued?

      For transformation we use a css property called transform. To specify a transformation, use the built-in function skewX, in which the angle of inclination is indicated in degrees.

      Unfortunately, each browser works with this property in its own way, despite the prescribed standards. Therefore, special prefixes were created to indicate this:

      • -ms- (Internet Explorer)
      • -o- (Opera)
      • -webkit- (Chrome, Safari)
      • -moz- (Firefox)

      Now let’s apply the acquired knowledge to writing an example.

      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <a href="https://gtavrl.ru/en/ochen-prostaya-gorizontalnaya-panel-navigacii-chto-znachit/">Horizontal panel</a>
    • home
    • About company
    • Products
    • Contacts
    • Horizontal panel

    • home
    • About company
    • Products
    • Contacts
    • And now vertically. I said vertical!

      For the second program we use the previous code as a basis. I wanted my items vertical menu were not beveled, but with rounded corners.

      To do this I used another css property border-radius.

      In previous articles I have already worked with this parameter, so I don’t think there will be any difficulties in understanding its functioning.

      Vertical panel

    • home
    • About company
    • Products
    • Contacts
    • As you already noticed, the main change in this code is the absence of a declaration display: inline-block, which was actually responsible for the horizontal arrangement of navigation points.

      Sub-items in the menu: drop-down list

      We have looked at the main groups navigation bars, however, there are several more varieties, or better yet, additions.

      Sometimes situations arise when some of the points complement the main ones. In this case, you cannot do without drop-down lists. They are created through transformations using css tools.

      Below I have attached the code of a small program that implements this approach.

      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 Drop-down list

      Drop-down list

      IN in this example I divided the menu units into two classes:

      1. m-menu
      2. s-menu

      The first class is responsible for the main menu, and the s-menu is responsible for the submenu.

      In the code you can find such a technique as .m-menu > li:hover or .m-menu > li.

      So, using:hover, you specify how the element will behave when you hover over it.

      In this case, the “>” sign modifies the selector so that only objects belonging to the top level are block-lowercase.

      Initially the submenu was set display:none, which notifies the hide handler this object. After hovering over a navigation element indicating hover, property value display changes to block and so a dropdown list opens.

      As you can see, the implementation of this technique is very simple.

      Now you have mastered the main types of navigation panels and can modify, supplement and modernize them yourself. If you liked my article, then subscribe to blog updates and share the source of knowledge with friends and colleagues. Bye bye!

      Best regards, Roman Chueshov

      Read: 1010 times

      To make all further descriptions more clear to you, download this PDF file or simply open this image in a new tab of your browser.

      Sometimes it's interesting to pay attention to whether a website that looks beautiful always uses "beautiful" html code, i.e. precise, structured, error-free. HTML code is a kind of art. It is not as developed and diverse as dynamic language, and yet can be written quite elegantly and masterfully.

      Here is a list of those features that can be used to determine whether the code is written with skill or not.

      1.DOCTYPE properly defined. This string not only allows you to identify your code, but also "tells" the browser how to display your page.

      2. Neat section in tags
      The header is set. The encoding has been declared. Style sheets are connected. Scripts are included, but not fully written.

      3. Assigning an ID to your document allows you to create CSS properties, which are unique for each page. For example, you may want your

      the tag looked special, for example, on the home page. In your CSS stylesheet you can write: #home h2() to achieve this.

      4. Clean menu. You've probably often seen lists being used as menus. This is very convenient, because... gives you the ability to control it.

      5. Enclosing all page content in a main tag

      . This item will give you the opportunity to control everything. That is, you can set the maximum and minimum page width.

      6. Important things should be placed at the beginning. News and important events in the code should come first, and menus and unimportant content should be placed at the end.

      7. "Inclusion" of site elements. Most site elements are repeated on every page, which means they need to be included using the include php command.

      8. The code must be tabulated into sections. If each section of code is indented, the structure of the code will be much clearer. Code that is left aligned is difficult to read and understand.

      9. Proper closing tags. Exclude end tags in unpaired tags, and check that matched tags are closed.

      10. Use title tags. The use of headers is necessary because... they show the hierarchy of sections and give them more order.

      12. No styles! Your html code should focus on structure and content, not page design! Place all styles in a separate CSS file.

      Robert Martin managed to describe the measurement of code quality perfectly:

      The only valuable measurement of code quality is WTF/min.

      I'll explain in a little more detail. When I conduct a code review, I only have three emotions:

      1. WTF (with disgust) - this code is not needed.
      2. WTF (with admiration) - this man is smart.
      3. WTF (annoyed) - this nonsense is impossible to understand.

      What is the first thing that affects us when we see any code? It is the purity and beauty of his writing. Creating clean and beautiful code is the mark of a great craftsman.

      There are two directions in learning this craft: knowledge and work. Knowledge teaches you the patterns, principles and techniques you need to become better at your profession. But this knowledge must be applied through constant practice and hard work.

      Here are a few techniques that can help you in the art of writing clean and beautiful code.

      Start with a name

      Kendrick Lamar said it well:

      If I want to tell real story, then I'll start with my name.

      The names are everywhere in the program. We name our functions, classes, arguments and many other things. We call source files, directories and everything inside them. We constantly come up with new names until they begin to clog our clean code.

      The title should show intent. Choice good names takes time, but ultimately saves it for you in the future. So think about the names and change them if you suddenly come up with a better name. Remember that the name of every variable, function, or class must answer three questions: why it exists, what it does, and what it is used for.

      This requires not only good descriptive skills, but also a broad cultural background, and this is something only you can learn.

      Functions must do one thing

      Louis Sullivan once said:

      Form follows function.

      Each system is created on the basis of a domain-specific language, which is created by programmers to be able to accurately describe it. Functions are the verbs of this language, and classes are the nouns. Functions should be the first in line to be organized in any programming language, and create good features is the essence of writing good code.

      There are only two golden rules for creating pure functions:

      • They should be small
      • They must do one thing and do it well.

      This means that your function should not contain nested structures. Thus, the indentation level in a function should not be more than one or two. This method makes the code easier to read and understand. In addition to this, we need to make sure that the statements in our function are at the same level of abstraction. Mixing levels of abstraction in a function results in code that cannot be fixed. Master programmers think of functions as stories to be told, not as code to be written.

      They use the convenience of their chosen language to create an expressive and clean block of code that tells the desired story well.

      Comments won't fix bad code

      Venus Williams remarked:

      Everyone leaves their comments. This is how rumors are born.

      Comments are a double-edged knife. A well placed comment can be very helpful. But on the other hand, nothing will clog up your code more than useless comments. And nothing can spread misinformation like comments.

      So comments are a necessary evil. Not always, but in most cases. The older a comment is, the more difficult it becomes to maintain, and many programmers do not align comments with their code. The code moves and develops. Parts of code move here and there, but comments don't, and this becomes a problem.

      Always remember that clean and expressive code with a few comments is better than cluttered and complex code with many comments. Don't waste time explaining the mess you've created, rather clean it up.

      Code formatting is always a priority

      Code formatting is communication, and communication is a priority for a professional developer, notes Robert Martin.

      Formatted code is a window into your mind. We want people to be impressed by our commitment to order, attention to detail and clarity of thought. But if they see an incomprehensible mass of code with no clear beginning or end, it will undoubtedly damage your reputation.

      If you think that the main thing is that everything works, you are wrong. The functionality you build today may be replaced in the next release, but the readability of your code will not change.

      Always know that you will be remembered for your style and discipline, not your code. Therefore you should take care that your code is well formatted and that it follows simple rules that everyone on your team understands.

      First write try-catch-finally

      Georges Canguilhem rightly said:

      To make mistakes is human, to constantly make mistakes is inhuman.

      Programmers deal with bugs all the time. Input data may be abnormal and devices may fail. As developers, we need to make sure that the code does what is expected. However, the problem is not error handling, the problem is error handling while maintaining a clean, readable appearance.

      Often bug fixes change the code a lot. Everything becomes so disjointed that it becomes difficult to understand the purpose and logic of the main code. It is not right. The code should be clean and reliable, and bugs should be fixed with grace and style. This is the sign of a master in development.

      One way to achieve this is to properly place all errors in try-catch blocks. These blocks define the scope of your code. When you execute a piece of code in a try clause, you are stating that execution can be interrupted at any time and continue in a catch.

      So when you write code, it's a good practice to start with a try-catch-finally statement. This will help you determine what the user expects, regardless of what goes wrong with the code in the try section.

      Remember that for each exception, you must provide enough context to determine the source and location of the error. Creative, informative error messages will be remembered long after the code has been written and the programmers have left the organization.

      Conclusion

      What word can summarize everything said here?

      It's code sense, the equivalent of common sense in software.

      According to Robert Martin, “Writing clean code requires the disciplined use of a myriad of small techniques applied to create a sense of cleanliness. These little techniques together form a sense of code.”

      Some of us are born with it, and some of us persistently acquire it through practice. This sense of code not only helps us differentiate between good and bad code, but also allows us to formulate strategies for transforming bad code into good code. Code sense helps the programmer to choose best tools available to create valuable, pure and nice code.

      It can be summed up in the words of Harold Abelson:

      Programs must be written first for the people who will read them, and only then for the machines that will execute them.

      Knowing how to write code does not mean being able to do it correctly. Good code- it’s like a beautifully designed post - it’s easy to read, easy to navigate, and the developer always understands how to expand it, debug it, or use it for other purposes.
      Therefore, it is always important to pay attention to the design of the code and comment on complex sections of the code.

      First, a little theory. You can write the same code different ways. The code may be procedural, functional And object-oriented.

      Procedural approach

      The procedural approach is the simplest. It means a script in which commands are written and elementary PHP functions are called.
      For example:

      $a = 10;
      $c = $a % $b;
      $e + $d;
      echo round($e);
      ?>

      This approach is appropriate if you have a very small code or it performs strictly one task (for example, generating a picture), as they say, “neither step to the right, nor step to the left.”

      Functional approach

      In the functional approach, your code is divided into parts and each part is placed in its own function. This will avoid code duplication, make the code concise and easier to read.
      Also, each function will have its own variable scope. That is, variables “living inside it” will never leak outside and variables used outside the function will also not end up in the function itself.
      By defining a function, you yourself can specify which variables should go into the function and what it should return, that is, you strictly control this process.

      Now let's try functional.

      //will return the cost
      function getPrice($price, $weight) (
      $result_price * $weight;
      return $result_price;
      }
      //return all weights
      function getWeights() (
      return array(5, 12, 14, 16, 22, 135, 150, 200, 254, 300, 400);
      }

      //get the weights into the variable
      $weights all fruits
      foreach ($fruits as $fruit) (
      foreach ($weights as $weight) (
      echo $fruit["name"] . " " . $weight. "kgs cost". getPrice($fruit["price"], $weight) . "rub.
      ";
      }
      }
      ?>

      The code came out much more readable. The weights are specified in the function getWeights And by simple addition count them there, how much would a different weight of each fruit cost.
      I went through all the fruits and with each search I went through all the weights. It could have been done the other way around.
      Source on pastebin http://pastebin.com/07QTBihX

      And finally the implementation on OOP.

      class Fruiting (
      public $fruits;
      public $weights;

      public function setData($fruits, $weights) (
      $this->fruits = $fruits;
      $this->weights = $weights;
      }

      private function getPrice($price, $weight) (
      $result_price = $price * $weight;
      return $result_price;
      }

      public function getResult() (
      //sort through all the fruits
      foreach ($this->fruits as $fruit) (
      // iterate through all the weights for each fruit
      foreach ($this->weights as $weight) (
      echo $fruit["name"] . " " . $weight. "kgs cost". self::getPrice($fruit["price"], $weight) . "rub.
      ";
      }
      }
      }
      }

      $fruiting = new Fruiting();
      $fruiting->setData($fruits, array(5, 12, 14, 16, 22, 135, 150, 200, 254, 300, 400));
      $fruiting->getResult();
      ?>

      As you can see, the code is more voluminous. At simple calculations You can get by with a functional approach, but all really large and complex projects are written using OOP.

      When writing the material, I tried to follow the advice of @ontofractal :)

      P.S. When you write code, imagine that it will be maintained by a mentally unstable maniac who knows where you live.







2024 gtavrl.ru.