Monday, July 24, 2023
HomeProgrammingCode Feedback: Find out how to Write Clear and Maintainable Code

Code Feedback: Find out how to Write Clear and Maintainable Code


When you spend an affordable period of time programming, you’re positive to come across code feedback. You’ll have even written some your self. These tiny items of textual content are embedded inside the program, however they’re ignored by the compiler or interpreter. They’re supposed for the people who work with the code, they usually have many purposes. They might even reshape your code or create documentation for others routinely. Need to know methods to use them correctly? Then you definately’re in the precise place!

Time to discover feedback, methods to use them and likewise how not to make use of them.

What You’ll Be taught:
By studying this text, you’ll study:

  • What a remark is, sorts and methods to use them.
  • The place they started and the place they’re now.
  • The distinction between good and unhealthy feedback.
  • Sensible purposes from the previous and current.

By the tip of the article, you’ll know why code feedback are essential, greatest practices for writing efficient feedback, some frequent pitfalls and errors to keep away from and the instruments and assets you should utilize to optimize your code commenting course of, together with automated documentation turbines, remark linters and code evaluation platforms.

You’ll begin with an in-depth have a look at what code feedback are.

What Are Code Feedback?

Feedback inside a software program program are human-readable annotations that programmers add to offer details about what the code is doing. Feedback take many types, relying on the programming language and the intent of the remark.

They’re categorized into two sorts: block feedback and line feedback.

  • Block feedback delimit a area inside the code by utilizing a sequence of characters in the beginning of the remark and one other character sequence on the finish. For instance, some use /* in the beginning and */ on the finish.
  • Line feedback use a sequence of characters to ask the compiler to disregard the whole lot from the beginning of the remark till the tip of the road. For instance: #, or //. Find out how to point out line feedback is determined by the programming language you’re utilizing.

Right here’s an instance of how every type of remark seems to be in Swift:


struct EventList: View {
  // THIS IS A LINE COMMENT @EnvironmentObject var userData: UserData
  @EnvironmentObject var eventData: EventData
  /* THIS IS A BLOCK COMMENT
  @State personal var isAddingNewEvent = false
  @State personal var newEvent = Occasion()
  */
  var physique: some View {
       ...
  }
}

Some programming languages solely assist one sort of remark sequence, and a few require workarounds to make a sequence work. Right here’s how some languages deal with feedback:

Language Line Remark Sequence Block Remark Sequences
Swift, Java, JavaScript, Kotlin, C, C++ // /* */
HTML <!-- –->
SQL --
ZSH, Bash, Perl # requires workarounds
Primary REM
AppleScript (* *)
Fortran !
Lua –[[ ]]
Ruby # =start =finish

Take into consideration the way you’d use a sticky observe. For programmers, a remark is a sticky observe with limitless makes use of.

Feedback have taken on extra significance over time as their makes use of have expanded and standardized. You’ll study many of those makes use of on this article.

A Temporary Historical past of the Remark

Not so way back, computer systems weren’t programmed utilizing a display screen and a keyboard. They have been programmed utilizing punch playing cards: small items of stiff paper with holes punched in a sequence to point directions for a pc. These would change into large stacks that have been fed right into a reader, and the pc would run this system.

It was exhausting to know at a look what every card or a set of playing cards did. To unravel this, programmers would write notes on them. These notes have been ignored by the machine reader as a result of it solely learn the holes on the cardboard. Right here’s an instance:

A punch card with a comment written on it

Right this moment, most feedback serve the identical function: to help in understanding what code does.

Code With out Feedback

A typical saying amongst programmers is, “Good code doesn’t want a proof”. That is true to a sure extent, and a few programmers don’t write feedback of their code.

However what occurs when that code will get actually large? Or it incorporates a number of enterprise guidelines and logic? Or different folks want to make use of it? It will be attainable to decipher the uncommented code, however at what price in effort and time?

When our focus is consistently on writing code, we neglect that a couple of months — even a couple of weeks — after writing stated code, quite a lot of the logic has left our reminiscence. Why did we make sure selections? Why did we use sure conventions. With out feedback, we should undergo the costly train of determining what we have been considering.

Feedback are extremely helpful, and good builders ought to use them. Nevertheless, all feedback will not be created equal. Right here’s a have a look at what makes feedback good, ineffective and even counterproductive.

Good Feedback

Good feedback are easy and simple to learn. They make clear or point out a practice of thought versus how the code works.

They take many types, akin to annotations, hyperlinks and citations to sources, licenses, flags, duties, instructions, documentation, and so forth.

Ineffective Feedback

Feedback are good, however you don’t want to make use of them in every single place. A typical pitfall is utilizing feedback to explain what code is doing, when that’s already clear.

For instance, you probably have code that’s iterating by way of an array and incrementing every worth, there’s no want to elucidate that — it ought to be apparent to the programmer who’s reviewing the code. What isn’t apparent, although, is why you’re doing that. And that’s what remark will clarify.

Describing the plain is a typical pitfall… and feedback that do that are simply taking over area and probably inflicting confusion.

Unhealthy Feedback

Unhealthy feedback are extra harmful than ineffective. They trigger confusion, or worse, attempt to excuse convoluted or badly written code. Don’t attempt to use feedback as an alternative choice to good code. For instance:


var n = 0 // Line quantity

As an alternative, do:


var lineNumber = 0

Abusing feedback, akin to cluttering code with TODO, BUG and FIXME feedback, is unhealthy apply. The perfect resolution is to resolve these previous to committing code when engaged on a group — or just create a difficulty in a ticketing system.

Since feedback are free-form, it’s useful to have some conventions or templates to find out what a remark ought to appear like, however mixing conventions falls into the class of unhealthy feedback.

Did you touch upon code throughout growth? Don’t commit it — resolve the issue and take out the remark earlier than you confuse others within the group.

Past Annotations

Up so far, you’ve realized about utilizing feedback as annotations. Nevertheless, since feedback don’t have any predefined format, you possibly can prolong their use by reworking your humble remark annotation into a knowledge file or specialised doc. Listed below are some good examples.

LICENSE Feedback

LICENSE is a sort of remark that signifies phrases and situations for the code. You’ll see these particularly typically in open-source code. Right here’s an instance from the MIT LICENSE:


/*
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

Since feedback are free-form, the best way the remark is typed can take many shapes. Right here’s an instance from Apple:


//===---------------------------------------------------------------===//
//
// This supply file is a part of the Swift open supply challenge
//
// Copyright (c) 2015-2016 Apple Inc. and the Swift challenge authors
// Licensed below Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license data
// See http://swift.org/CONTRIBUTORS.txt for the listing of Swift challenge authors
//
//===---------------------------------------------------------------===//

TEMPORARY CODE-OUT Feedback

Programmers use the TEMPORARY CODE-OUT remark as a device for debugging. By taking a block or line of code out of the compile course of, you possibly can alter which code executes and which doesn’t. This technique is usually used when doing a process-of-elimination debug. For instance (solely constructing for iOS):


let package deal = Package deal(
  title: "CommentOut",
  platforms: [
    .iOS(.v14), /* .tvOS(.v14), .watchOS(.v7), .macOS(.v11) */
  ],
  merchandise: [
    .library(name: "CommentOut", targets: ["CommentOut"])
  ],
  targets: [
    .target(name: "CommentOut")
  ]
)

DECORATIVE Feedback

A DECORATIVE or SEPARATOR remark can separate a file or blocks of code by some class or perform. This helps customers discover code extra simply. Right here’s an instance:


/**************************************************
 * Huffman Implementation Helpers                 *
 **************************************************/

LOGIC Feedback

LOGIC feedback doc the rationale you selected when creating the code. This goes past what the code exhibits, like “What was that worth assigned?”

For instance (from swift-package-manager/Sources/Instructions/SwiftRunTool.swift, strains 287-288):


personal func execute(path: String, args: [String]) throws -> By no means {
  #if !os(Home windows)
  // On platforms apart from Home windows, sign(SIGINT, SIG_IGN) is used for dealing with SIGINT by DispatchSourceSignal,
  // however this course of is about to get replaced by exec, so SIG_IGN have to be returned to default.
  sign(SIGINT, SIG_DFL)
  #endif

  strive TSCBasic.exec(path: path, args: args)
}

On this case, the execute perform comprises compile conditional directions that may both embody or skip the sign name. The remark comprises the reason as to why it does this.

Superior Types of Feedback

Feedback can maintain specialised content material, sometimes formatted identical to a knowledge file could be: a file inside the code. They can be easy flags, which supply code parser instruments can reply to in numerous methods.

Flag Feedback

Flag feedback are sometimes utilized by linters; they allow or disable options. Right here’s how SwiftLint disables options utilizing flag feedback:


struct GitHubUserInfo: Content material {
  let title: String
  // swiftlint:disable identifier_name
  let avatar_url: String?
  // swiftlint:allow identifier_name
}

Compilers themselves additionally use flag feedback as a type of setup. Within the instance under, you see a Python script run as a CLI script and in UTF-8 format:


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

Be aware: The primary remark line in scripts has a proper title: the shebang. Its function is to point which interpreter the working system ought to use when it executes the script. It at all times begins with a #!.

TASK Feedback

Built-in growth environments (IDEs), textual content editors and a few CLI instruments are in a position to learn TASK feedback left by programmers in a format that signifies an motion to be carried out by the programmer sooner or later, akin to TODO:


// TODO: Swap Mannequin permissions

// FIXME: Convert strings to Enum

DOCUMENT GENERATION Feedback

DOCUMENT GENERATION feedback enable a device to parse the supply code and output a formatted doc — sometimes HTML — that finish customers can use to browse courses, strategies, and so forth. Right here’s an instance from JavaDoc:


/**
 * @param string  the string to be transformed
 * @param sort    the sort to transform the string to
 * @param <T>     the kind of the ingredient
 * @param <V>     the worth of the ingredient
 */
<T, V extends T> V convert(String string, Class<T> sort) {
}

Different instruments can generate documentation that’s seen by IDEs and proven to the consumer inside the code. One such device is Documentation Markup (DocC). That is notably helpful for APIs Apple makes use of with its personal libraries. Right here’s an instance from the open-source SwiftGD challenge:


/// Exports the picture as `Knowledge` object in specified raster format.
///
/// - Parameter format: The raster format of the returning picture information (e.g. as jpg, png, ...). Defaults to `.png`
/// - Returns: The picture information
/// - Throws: `Error` if the export of `self` in specified raster format failed.
public func export(as format: ExportableFormat = .png) throws -> Knowledge {
  return strive format.information(of: internalImage)
}

CDATA Feedback

CDATA feedback embed formatted information inside XML and XHTML information. You should utilize a number of differing kinds with these feedback, akin to photographs, code, XML inside XML, and so forth.:


<![CDATA[<sender>John Smith</sender>]]>

From Wikipedia’s article on Pc Programming Feedback, you could have the RESOURCE inclusion sort of remark: “Logos, diagrams, and flowcharts consisting of ASCII artwork constructions may be inserted into supply code formatted as a remark”. For instance:


<useful resource id="ProcessDiagram000">
<![CDATA[
 HostApp (Main_process)
    |
    V
script.wsf (app_cmd) --> ClientApp (async_run, batch_process)
                |
                |
                V
         mru.ini (mru_history)  
]]>
</useful resource>

Having Enjoyable With Feedback

Simply because feedback aren’t included with an app doesn’t imply you possibly can’t have enjoyable with them. Life classes, jokes, poetry, tic-tac-toe video games and a few coworker banter have all made it into code feedback. Right here’s an instance from py_easter_egg_zen.py:


import this

# The Zen of Python, by Tim Peters

# Lovely is healthier than ugly.
# Specific is healthier than implicit.
# Easy is healthier than complicated.
# Complicated is healthier than sophisticated.
# Flat is healthier than nested.
# Sparse is healthier than dense.
# Readability counts.
# Particular circumstances aren't particular sufficient to interrupt the principles.
# Though practicality beats purity.
# Errors ought to by no means go silently.
# Except explicitly silenced.
# Within the face of ambiguity, refuse the temptation to guess.
# There ought to be one-- and ideally just one --obvious strategy to do it.
# Though that manner will not be apparent at first except you are Dutch.
# Now's higher than by no means.
# Though by no means is commonly higher than *proper* now.
# If the implementation is difficult to elucidate, it is a unhealthy concept.
# If the implementation is simple to elucidate, it might be a good suggestion.

Necessary: Easter egg feedback aren’t welcome in all supply codes. Please seek advice from the challenge or repository coverage or your worker handbook earlier than doing any of those.

Key Takeaways

Right this moment, you realized that there’s extra to feedback than it appears. As soon as thought-about an afterthought, they’re now acknowledged a useful communication device for programming.

  • They assist doc and protect data for future code upkeep.
  • There are good feedback and unhealthy feedback.
  • Feedback may help create automated documentation.

Now, it’s time to apply! The one strategy to get good at feedback is by leaping in and including them.

By making feedback a part of your programming thought course of, they not change into an additional step to carry out. Listed below are some methods to apply:

  • Doc your present initiatives and be aware of any requirements set for the challenge or repository.
  • Use a linter on all of your initiatives to maintain your formatting and conventions in test.
  • Discover a doc generator and publish your work.

You’ll be able to apply and contribute whereas supporting an open-source challenge that wants assist with feedback and documentation.

The place to Go From Right here?

When you’d prefer to study extra about commenting, take a look at these articles and assets. A lot of them have been consulted within the writing of this text.

We hope you’ve loved this have a look at commenting! Do you could have questions, options or tricks to share? Be part of us within the discussion board for this text. You’ll be able to all study from one another.

In regards to the Writer

Roberto Machorro has been programming professionally for over 25 years, and commenting code simply as lengthy. He has championed documenting in-house, third-party and open supply code out of frustration for having to take care of badly written code or wrestle with unavailable documentation. He acquired began with library paperwork utilizing HeaderDoc, JavaDoc and now having fun with DocC.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments