How do we enhance your code so that it's meaningful to others?

Tip of the week

Created on: October 24, 2017

Updated on: October 24, 2017

Tip of the week

How do we enhance your code so that it's meaningful to others?

If you are new to coding or providing web development services, you may have noticed that there are some developers who write comments within their code.

And there are also developers that do not put comments in their code.

I will use an analogy here and it’s like driving a car and using indicators to inform others where you are going to turn.

In the UK there are lots of people who don’t indicate to inform others where they will turn.

However it is best practice to inform other road users where you are going to turn your car. It’s the same thing with programming, and just as in driving it’s important to set context in your comments.

Good Example of a Laravel comment


/**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws MethodNotFoundException
     */

    public function index(Request $request)
    {

        try {

            $query = $request->input('q');

            if ($query) {
                $blogs = Blog::search($query)->get();

                return view('pages.search', compact('blogs'));

            } else {

                $blogs = Blog::latest('published_at')->get()->all();

                $title = 'Blog Listings';

            }

        } catch (\Exception $e) {

            throw new MethodNotFoundException($e->getMessage());
        }

        return view('blogs.index', compact('blogs', 'title'));
    }

The above mentioned snippet was taken from a controller and it demonstrates a comment that has been written in context. The index method is used to display a listing of the resource within a set of blog posts for example.

This was taken from our very own web development services web page at www.ormrepo.co.uk/blogs

Bad Example

    /**
     * 
     *
     * Orders is part of a charge.
     *
     * 
     */
    public function charge()
    {
        return $this->belongsTo('App\Charge');
    }

As you can see an order is not part of a charge; this is a relationship and the comment doesn’t explain the relationship between the order and the charge.

Code comments need to be in context and they need to explain the purpose of the code. The reason being is that if someone else tries to read your code, they will misunderstand bits of it. This will lead to serious consequences because they will make assumptions and this can crash your code and in turn, a web development services project that it may be related to.

Think about others and how they will experience your code and you will become a responsible and empathetic coder.