DEV Community

Cover image for How to Write Efficient Code
Masih Abjadi
Masih Abjadi

Posted on

How to Write Efficient Code

This article is provided from the research and experience of full-stack developer and alumni Masih Abjadi
While this article focuses mainly on web technologies, the same concepts can be applied to any programming language.

DRY


(Image credit: Anas Alshanti)

According to Wikipedia, Don't repeat yourself (DRY), is a principle of software development aimed at reducing repetition of software patterns by replacing it with abstractions or using data normalization to avoid redundancy.

Often in web development, I have seen many developers repeating themselves, most commonly when using UI libraries such as Bootstrap and Foundation. In this case, developers end up using the full library (not the customized version), rather than the selected parts they need.
For example, unfortunately, many developers will only use the grid system or some component of that library and when they start to customize the UI they start to write their own stylesheet while many of them already exist! And what they are doing is duplicating the code and increase the file size and load time.

Lets take a look at an example of centering a div element both horizontally and vertically.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Center the div</title>
    <!-- Styles -->
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link href="style.css" rel="stylesheet" />
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="card">
          <h5 class="card-header">Featured</h5>
          <div class="card-body">
            <h5 class="card-title">Special title treatment</h5>
            <p class="card-text">
              With supporting text below as a natural lead-in to additional
              content.
            </p>
            <a href="#" class="btn btn-primary">Go somewhere</a>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

style.css:

html,
body {
  height: 100%;
}

.card {
  width: 400px;
}

These are the initial setup files.

Now we want to center the div element, there are many methods available to achieve this. You may have noticed we are using the Bootstrap 4 library, this means we can use a utility class to do this for us:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Center the div</title>
    <!-- Styles -->
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link href="style.css" rel="stylesheet" />
  </head>
  <body>
    <div class="container h-100">
      <div class="row h-100 justify-content-center align-items-center">
        <div class="col-md-6">
          <div class="card">
            <h5 class="card-header">Featured</h5>
            <div class="card-body">
              <h5 class="card-title">Special title treatment</h5>
              <p class="card-text">
                With supporting text below as a natural lead-in to additional
                content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

The above example shows how easy this is, all we needed to do is make use of a few built in utility classes.

The main mistake developers make when using UI frameworks is not using all of the features, this is an example of one of the more underrated features of Bootstrap 4. By using the utility classes we save ourselves from having to write our own CSS, reducing the code required for the application.

Advantages of DRY

Maintainability:
The biggest benefit of using DRY is maintainability. If the logic of checking permissions is repeated all over the codebase, it becomes difficult to fix issues that arise in the repeated code.

Readability:
More often than not, DRY code is more readable. This is not because of the DRY principle itself, but rather because of the extra effort the developer put into the code to make it.

Reuse:
DRY inherently promotes reuse of code because we are merging 2 or more instances of repeating code into a single block. Reusable code pays off in the long run as it speeds up development time.

Cost:
If management needs to be convinced to spend more time on improving the quality of code, this is it. More code costs more. More code takes more people more time to maintain and to address bugs. More time to develop and more bugs leads to a very unhappy customer. Enough said!

Testing:
We are talking about unit tests and integration tests here, not manual testing. The more paths and functions you have to cover using the tests, the more code you have to write for tests. If code is not repeated, you just have to test one main path. Of course, different behaviors still need to be tested.

Is Your Code DRY or WET? - DZone DevOps


Writing Semantic Code

Speaking about the semantic code in HTML, many developers think this only means using HTML5 semantic elements (header, nav, section, article, aside, footer) instead of div elements but that's not true! Semantic code means to write code that describes the content rather than how that content should look.

team.png
I got this image from a real website but for privacy reasons, I changed names and pictures.
the code for each team is:

<div class="col-md-4 bottommargin">
  <div class="team">
    <div class="team-image">
      <img src="images/team1.jpg" alt="Josh Clark" />
      <div class="team-overlay">
        ..........
      </div>
    </div>
    <div class="team-desc team-desc-bg">
      <div class="team-title">
        <h4>JOHN DOE</h4>
        <span>Co-Founder</span>
      </div>
    </div>
  </div>
</div>

Lots of div, right?

We can reach the same outcome by using figure Tag, to better understand this concept I will show you one of my projects:
events

<div class="col-sm-4">
  <figure class="event">
    <img
      src="assets/img/event1.jpg"
      alt=""
      class="animated pulse"
      data-animated="pulse"
    />
    <figcaption>
      <time datetime="2017-11-12">12 November 2017</time>
      <p class="lead">Moscow Never Slip Party</p>
      <a href="#">Read more</a>
    </figcaption>
  </figure>
</div>

In this example I used semantic code, which is very neat and easy to understand just from looking at the markup.

Why semantic code matters

Accessibility:

  • Many visually impaired people rely on text to speech browsers to read pages back to them. These programs cannot interpret pages very well unless they are clearly explained by semantic markup.

SEO:

  • Search engines need to understand what your content is about in order to rank you properly on search engines. Semantic code tends to improve your placement on search engines, as it is easier for the "search engine spiders" to understand.

Maintainability:

  • Semantic code makes site updates easier because you can apply design style to headings across an entire site instead of on a per page basis.

Teamwork:

  • Semantic code is much more expressive and easier for people to understand, so if a new web designer picks up the code they can understand it much faster.

Design:

  • Because semantic code does not contain design elements it is possible to change the look and feel of your site without recoding all of the HTML.
  • Once again, because design is held separately from your content, semantic code allows anybody to add or edit pages without having to have a good eye for design. You simply describe the content and the cascading style sheet defines what that content looks like.

"Any fool can write code that a computer can understand. good programmers write code that humans can understand" - Martin Fowler


Accessibility

webaccessibility2.jpg?itok=RKiSkBoW
(Image credit: "newtarget")

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."
-Tim Berners-Lee, W3C Director and inventor of the World Wide Web

Accessibility by itself is a huge topic and I'm not going to cover it all.

Even if your website is well coded and well designed, you are still targeting a limited amount of users.

How Many Disabled Web Users Are There?

Accessibility is essential for developers and organizations that want to create high-quality websites and web tools, and not exclude people from using their products and services.

The Web is fundamentally designed to work for all people, whatever their hardware, software, language, location, or ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability.

Unfortunately, when we are talking about Accessibility we will think about people with disabilities but it doesn't mean that exactly! For example, the color combination choice might work well on large screens and indoors but be more difficult to see on smaller screens or outside with the glare of the sun, or the color Color Contrast during the day and night.

Here I just pointed to a small part of accessibility, I highly encourage you to use the links below and gain more information about this.

Web Content Accessibility Guidelines (WCAG) 2.0
https://developers.google.com/web/fundamentals/accessibility/
Introduction to Web Accessibility | Web Accessibility Initiative (WAI) | W3C

Conclusion

"The sooner you start to code, the longer the program will take" - Roy Carlson
"There's a big difference between knowing how to code and understanding it! " - Masih Abjadi

Before writing code always try to think about it, I'm not talking about making a design or wireframe before you start coding, I mean when you are ready for the coding stage take some time and think about the elements you want to build.

If you want to use a framework, make sure you spend a little time reading the documentation, next see if you can build that element a better way using semantic code or with regards to accessibility, even if it's a simple project make a habit of writing efficient code!

Top comments (2)

Collapse
 
thedan84 profile image
Dennis Parussini

Great read.
Although this post is about web development most of the principles discussed here are also applicable to other areas of software development.

Collapse
 
masihtak profile image
Masih Abjadi

Glad to see you find this article useful _^