Best Practices: Coding

Writing code is like cooking. No matter what you do, someone’s going to come up to you and tell you to add more salt, sugar, spices, and so on.

The same goes for writing code. The way you write your code is your business, and someone is eventually going to look at your code and tell you how you could have written that function better. Sure, there are a lot of right ways to write code, so how do you know which one to choose?

I started coding professionally about 3.5 years back. I’m still new to a lot of concepts and some concepts just go right over my head. Whenever I start to code a feature, I spend a lot of time worrying whether I’m writing optimized code or how my much-experienced colleague would write it. That’s where code reviews help, and you must understand that they’re an important part of your professional journey as a Software Programmer.

There are some simple guidelines that you can follow that ensures code reviews remain true to their purpose, finding potential errors & ensuring good quality code is sent forward.

Image for post

Photo by Safar Safarov on Unsplash

Don’t write code you don’t need

Mo code, mo problems.

The more code you write, the more it’s going to need maintenance. Write less code, remove code you don’t need. Version Control will always help to go back in time and revert if needed.

Same with commented out code, if a commented block is going into a release, remove it. This helps to keep your code space clean and easy to understand.

Use consistent code styles

There’s no right or wrong way to indent your code. However, whichever style you choose, stay consistent with it.

Let’s face it, this is annoying:

if (hour < 18) {
greeting = "Good day";
}else 
{
greeting = "Good evening";
}

As w3.org, rightly mentions:

Browsers are very forgiving when it comes to JavaScript syntax. This should not, however, be a reason for you to write sloppy code that relies on browsers to make it work.

I usually use the ESLint which is available on all major IDEs as a plugin whenever I write JavaScript code. Having a consistent style makes your code look beautiful and other developers can quickly read through your code.

For Python, the PEP8 style guide is probably the most comforting and it offers a handy command-line tool so that you can test your python files.

File & Folder Structure

If you’re a beginner starting their first project, it would seem to make sense to write all your code in a couple of files. However, as your project gets more complex and bugs start to pile up, you will realize that this isn’t a good idea.

Keeping your code in one or two files makes it hard to debug, and even the sharpest developers forget where every function is located.

Before you begin writing code, make sure you divide your code into features and modules and keep them logically separate. This will help you in maintaining your code in the long run.

DRY — Don’t Repeat Yourself

If you’re writing a piece of code again for the third time, its time to extract that piece of valuable logic and put it in a helper class that you can import everywhere. There are a lot of use cases that can be used as helper classes such as date or string format functions or logging functions.

Imagine a scenario where you’re formatting a date to MM-DD-YYYY in various files throughout your codebase, and suddenly your client decides to switch to DD-MM-YYYY format, imagine the horror! You will need to go through all the files and if you miss any one of them, you’ll be getting a juicy bug report.

If you had used a helper class all you would need to do is edit that one function only!

Like I said earlier, Mo code, Mo problems.

Modularise Your Code

If a function or method goes past 30 lines of code, consider breaking it up. The good maximum module size is about 500 lines.

Little pieces of code are easier to understand and debug.

Write defensively.

Always think about what can go wrong, what will happen on invalid input, and what might fail, which will help you catch many bugs before they happen.

This is probably one of the most overlooked concepts. Developers need to understand that a user does not understand the flow of the product and is bound to launch a nuclear missile while trying to figuring out your app.

So, you need to think about scenarios with invalid input & failure cases and make sure your code returns an appropriate error response rather than just a vague error like ‘Error’.

#software-development #technology #coding #best-practices #programming

What is GEEK

Buddha Community

Best Practices: Coding
Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Code Trashing Symptom

There are a set of skills and qualities which make the ideal software

developer we are all searching to be or searching for to employ. However, right now I am going to emphasize the importance of a quality that is mostly found in senior developers.

As a beginner, I remember the enthusiasm when I implemented my first app. It was in VisualBasic v6.0 with very basic UI and logic. From there on,

it was very hard to leave the keyboard without writing code daily. At

first, it was VB, then some HTML, JavaScript (when it was very buggy),

Java, and sometime later I became a true working developer/team-leader

for many years.

Reliving those days when I was an enthusiast developer, I remember the powerful feeling that kept me on my path. I was (and still) addicted to code. But it is not code I was after. It is the vast feeling of creating something your own. Creating something from within. This strong feeling of a new creation is addictive.

The problem with addiction is that you don’t recognize the limits of

yourself and your creations. Consequently, you are not guided by your

consciousness.

As a leader of development teams in different projects, I came across a

variety of situations with different developers. But this same question I kept hearing from time to time, “This is a great piece of code, do you really want me to remove it?”, and it is really a great piece of code with the ultimate design.

But what you shouldn’t forget that you and your team are here to accomplish something meaningful for your clients and users! Thus writing a greatly designed code with low correlation to requirements isn’t going to change anything.

When I moved to my current team and project, I found out that the project’s code was written beautifully and well designed. But it was insignificant to our client’s future requirements.

One of the best decisions I made was to gradually re-implement (remove old code and write a new one without reference nor copy-pasting any parts). The reason being the already written code was a big hurdle to bend to any new requirements we received

Sometimes it’ll be hard to ask for, especially when you’re asking the original author of the code. But always remind him of these facts: your main focus is your clients; if you miss your code, Github will always remember it for you.

Acknowledging your addiction to code is your first step to overcoming your unconscious desire to create worthless stuff that no one will use (and believe me, it hurts more to find out that your code is useless than

removing a code you’ve written).

Final Thoughts

From my personal experience, when you implement something hard to solve the first time, most of your energy and thoughts are invested in solving the problem and not in the most relevant design for the given requirements.

Rewriting the same code a second time gives you a second chance to spend your time (almost solely) in design (since the problem is already

solved).

The best design is a design made for the current (known) requirements and not future mystic stuff that we just came up with.

**Remember: **Refactor! Don’t predict!

#clean-code #best-practices #programming #development #refactoring #coding #coding-skills #coding-life

Seamus  Quitzon

Seamus Quitzon

1600061880

How to write clean code ? follow these best practices for writing clean code

Hey programmers , this article is not about some java related feature or concept but more than that . Basically I’m going to explain what all mistakes a java developer does while writing the code and hence how you can minimize it and you don’t have to refactor your code .So this article is about BEST PRACTICES a developer should always follow .

1. What’s there in the name :

A developer should always try to give a meaningful name to the variables, methods and classes . It becomes too easy to understand what the method or class or variable is about when some one reads your code while reviewing it or debugging it. Giving name like a ,b,c to variable do not intent any meaning and becomes less relevant while debugging the code .

  1. Always start the name of a class with upper case .Eg.
public class Employee {

}

here **Employee **is class name and other developers can easily understand that this class deals with employee related stuff.

2. Always start a variable name with lower case .Eg.

private int salary;

here **salary **tells about salary of employee .

3.Always start method name with lower case and do not include And and Or words in method name .Eg.

public int calculateSalary(int noOfDaysWorked , int baseSalary)

4. Write constants in upper case and separate them with under score .Eg.

public final int RETIREMENT_AGE = 58;

Note : do not use special symbols while writing variables ,methods , constants or classes names .

#programming #best-practices #code-review #java #coding

Osiki  Douglas

Osiki Douglas

1624789560

Best Practices to Write Clean Python Code

Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used extensively across various domains like web development through popular frameworks like Django and Flask, web scraping, automation, system administration, DevOps, testing, network programming, data analysis, data science, machine learning, and artificial intelligence. In fact, the first language which comes to someone’s mind when talking about data-related technologies is Python!

Along with being a heavily used language by beginners due to its ease of learning, it has huge community support and extensive documentation. But a lot of people when switching from other languages like Java, C, C++, JavaScript etcetera, find it a little difficult to follow along with the best practices that should be adopted to write clean code in Python. Clean code is easier to read and understand, debug, and elegant. So today we will be discussing all of them in detail, therefore you will get a better idea of them. So let’s get started!

#gblog #python #best practices to write clean python code #clean python code #best

Samanta  Moore

Samanta Moore

1621137960

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review