Archie Mistry

Archie Mistry

1573019133

Understand the Hazards of Using Imperative Code

JavaScript has been getting a lot of new, sugary features ever since we got over Harmony. While more features can allow us to write readable, high-quality code, it’s also easy to go overboard with what’s new and shiny and run into some of the potential pitfalls.

Let’s go over some of the gotchas I see come up quite frequently as sources of confusion, both new and old.

Arrow Functions and Object Literals

Arrow functions provide a terser and shorter syntax, one of the features available being that you can write your function as a lambda expression with an implicit return value. This comes in handy for functional-style code, like when you have to use mapping arrays using a function. That would be quite a few empty lines with regular functions.

For example:

const numbers = [1, 2, 3, 4];
numbers.map(function(n) {
  return n * n;
});

This becomes a sleek, easy-to-read one-liner with the lambda style arrow functions:

const numbers = [1, 2, 3, 4];
numbers.map(n => n * n);

This use case of an arrow function will work as one would expect: It multiplies the values by itself and returns to a new array containing [1, 4, 9, 16].

However, if you try mapping into objects, the syntax isn’t what one might intuitively expect it to be. For example, let’s say we’re trying to map our numbers into an array of objects containing the value like this:

const numbers = [1, 2, 3, 4];
numbers.map(n => { value: n });

The result here will actually be an array containing undefined values. While it might look like we are returning an object here, the interpreter sees something completely different. The curly braces are being interpreted as the block scope of the arrow function, and the value statement actually ends up being a label. If we were to extrapolate the above arrow function into what the interpreter actually ends up executing, it would look something like this:

const numbers = [1, 2, 3, 4];
numbers.map(function(n) {
  value:
  n
  return;
});

The workaround is quite subtle. We just need to wrap the object in parentheses, which turns it into an expression instead of a block statement, like this:

const numbers = [1, 2, 3, 4];
numbers.map(n => ({ value: n }));

This will evaluate to an array containing an array of objects with the values that one would expect.

Arrow Functions and Bindings

Another caveat with arrow functions is that they don’t have their own this binding, meaning their this value will be the same as the this value of the enclosing lexical scope.

So despite the syntax being arguably sleeker, arrow functions are not a replacement for good old functions. You can quickly run into situations where your this binding is not what you thought it was.

For example:

let calculator = {
  value: 0,
  add: (values) => {
    this.value = values.reduce((a, v) => a + v, this.value);
  },
};
calculator.add([1, 2, 3]);
console.log(calculator.value);

While one might expect the this binding here to be the calculator object there, it will actually result in this being either undefined or the global object depending on whether the code is running in strict mode or not. This is because the closest lexical scope here is the global scope. In strict mode, that is undefined; otherwise, it’s the window object in browsers (or the process object in a Node.js compatible environment).

Regular functions do have a this binding. When called on an object, this will point at the object, so using a regular function is still the way to go for member functions.

let calculator = {
  value: 0,
  add(values) {
    this.value = values.reduce((a, v) => a + v, this.value);
  },
};
calculator.add([10, 10]);
console.log(calculator.value);

Also, since an arrow function has no this binding, [Function.prototype.call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), and [Function.prototype.apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) won’t work with them either. The this binding is set in stone when the arrow function was declared, and can’t change.

So in the following example, we’ll run into the same issue as we had earlier: The this binding is the global object when the adder’s add function is called, despite our attempt to override it with Function.prototype.call:

const adder = {
  add: (values) => {
    this.value = values.reduce((a, v) => a + v, this.value);
  },
};
let calculator = {
  value: 0
};
adder.add.call(calculator, [1, 2, 3]);

Arrow functions are neat, but they can’t replace regular member functions where a this binding is needed.

Automatic Semicolon Insertion

While it’s not a new feature, automatic semicolon insertion (ASI) is one of the weirder features in JavaScript, so it’s worth a mention. In theory, you can omit semicolons most of the time (which many projects do). If the project has a precedent, you should follow that, but you do, however, need to be aware that ASI is a feature, or you’ll end up having code that can be deceiving.

Take the following example:

return
{
  value: 42
}

One might think it would return the object literal, but it will actually return undefined because semicolon insertion takes place, making it an empty return statement followed by a block statement and a label statement.

In other words, the final code that is actually being interpreted looks more like the following:

return;
{
  value: 42
};

As a rule of thumb, never start a line with an opening brace, bracket, or template string literal, even when using semicolons because ASI always takes place.

Shallow Sets

Sets are shallow, meaning duplicate arrays and objects with the same values, which will lead to multiple entries in the set.

For example:

let set = new Set();
set.add([1, 2, 3]);
set.add([1, 2, 3]);
console.log(set.length);

The size of that set will be two, which makes sense if you think of it in terms of references as they are different objects.

Strings are immutable, however. Take the example of multiple strings in a set like this:

let set = new Set();
set.add([1, 2, 3].join(','));
set.add([1, 2, 3].join(','));
console.log(set.size);

This will end up with the set having a size of one because strings are immutable and interned in JavaScript, which can be used as a workaround if you find yourself needing to store a set of objects. One could serialize and de-serialize them instead.

Classes and the Temporal Dead Zone

In JavaScript, regular functions get hoisted to the top of the lexical scope, meaning the example below will work as one might expect:

let segment = new Segment();
function Segment() {
  this.x = 0;
  this.y = 0;
}

But the same is not true for classes. Classes are actually not hoisted and need to be fully defined in the lexical scope before you attempt to use them.

For example:

let segment = new Segment();
class Segment {
  constructor() {
    this.x = 0;
    this.y = 0;
  }
}

This will result in a ReferenceError when trying to construct a new instance of the class because they aren’t hoisted like functions are.

Finally

Finally is a bit of a special case. Take a look at the following snippet:

try {
  return true;
} finally {
  return false;
}

What value would you think it returns? The answer is both intuitive and at the same time can become unintuitive. One could think the first return statement makes the function actually return and pop the call stack. But this is the exception to that rule because Finally statements are always run so the return statement inside the Finally block returns instead.

In Conclusion

JavaScript is easy to learn but hard to master. In other words, it’s error-prone unless a developer is careful about what and why they’re doing something.

This is especially true with ECMAScript 6 and its sugary features. Arrow functions, in particular, come up all of the time. If I was to make a guess, I’d say it’s because developers see them as being prettier than regular functions. But they’re not regular functions and they can’t replace them.

Skimming the specification from time to time doesn’t hurt. It’s not the most exciting document in the world, but as far as specifications go, it’s not that bad.

Tools like the AST Explorer also help in shedding some light on what is going on in some of these corner cases. Humans and computers tend to parse things differently.

With that said, I’ll leave you with this final example as an exercise.

#javascript #code #programming

What is GEEK

Buddha Community

Understand the Hazards of Using Imperative Code
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

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

Houston  Sipes

Houston Sipes

1604088000

How to Find the Stinky Parts of Your Code (Part II)

There are more code smells. Let’s keep changing the aromas. We see several symptoms and situations that make us doubt the quality of our development. Let’s look at some possible solutions.

Most of these smells are just hints of something that might be wrong. They are not rigid rules.

This is part II. Part I can be found here.

Code Smell 06 - Too Clever Programmer

The code is difficult to read, there are tricky with names without semantics. Sometimes using language’s accidental complexity.

_Image Source: NeONBRAND on _Unsplash

Problems

  • Readability
  • Maintainability
  • Code Quality
  • Premature Optimization

Solutions

  1. Refactor the code
  2. Use better names

Examples

  • Optimized loops

Exceptions

  • Optimized code for low-level operations.

Sample Code

Wrong

function primeFactors(n){
	  var f = [],  i = 0, d = 2;  

	  for (i = 0; n >= 2; ) {
	     if(n % d == 0){
	       f[i++]=(d); 
	       n /= d;
	    }
	    else{
	      d++;
	    }     
	  }
	  return f;
	}

Right

function primeFactors(numberToFactor){
	  var factors = [], 
	      divisor = 2,
	      remainder = numberToFactor;

	  while(remainder>=2){
	    if(remainder % divisor === 0){
	       factors.push(divisor); 
	       remainder = remainder/ divisor;
	    }
	    else{
	      divisor++;
	    }     
	  }
	  return factors;
	}

Detection

Automatic detection is possible in some languages. Watch some warnings related to complexity, bad names, post increment variables, etc.

#pixel-face #code-smells #clean-code #stinky-code-parts #refactor-legacy-code #refactoring #stinky-code #common-code-smells

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

Fannie  Zemlak

Fannie Zemlak

1604048400

Softagram - Making Code Reviews Humane

The story of Softagram is a long one and has many twists. Everything started in a small company long time ago, from the area of static analysis tools development. After many phases, Softagram is focusing on helping developers to get visual feedback on the code change: how is the software design evolving in the pull request under review.

Benefits of code change visualization and dependency checks

While it is trivial to write 20 KLOC apps without help of tooling, usually things start getting complicated when the system grows over 100 KLOC.

The risk of god class anti-pattern, and the risk of mixing up with the responsibilities are increasing exponentially while the software grows larger.

To help with that, software evolution can be tracked safely with explicit dependency change reports provided automatically to each pull request. Blocking bad PR becomes easy, and having visual reports also has a democratizing effect on code review.

Example visualization

Basic building blocks of Softagram

  • Architectural analysis of the code, identifying how delta is impacting to the code base. Language specific analyzers are able to extract the essential internal/external dependency structures from each of the mainstream programming languages.

  • Checking for rule violations or anomalies in the delta, e.g. finding out cyclical dependencies. Graph theory comes to big help when finding out unwanted or weird dependencies.

  • Building visualization for humans. Complex structures such as software is not easy to represent without help of graph visualization. Here comes the vital role of change graph visualization technology developed within the last few years.

#automated-code-review #code-review-automation #code-reviews #devsecops #software-development #code-review #coding #good-company