fabiochiu/medium-articles huggingface dataset:
Best Practices For Designing REST APIs (Part 1)
By: Osama Riaz
Tags: Best Practices, Design, Backend Development, API, Rest Api

Resource Representation

Firstly, let’s explain what is “Representation” stands for. It could be defined as:

Data that is returned when a client retrieved some resource from the server or sent from client to server.

User can view the representation of the resource in different formats. We call these formats Media Types. All the available media types should encode the same data but just in different format. Out of all the available type, the most widely used one is JSON ( JavaScript Object Notation ). JSON is simple, it’s that simple. This is the reason for it being used widely.

JSON IS THE DEFACTO STANDARD FOR WEB API.

Apart from this, it also has some limitations like a limited data type. It does not support commonly used types like Date and Time and URL. But we can still represent these type using string.

JSON Should Be Simple

Didn’t I just say the JSON is simple? Well, one can make it harder to understand if standards do not meet. JSON is a collection of name/value pairs. The name itself is a string and it corresponds toa property of the resource. It should be kept in mind that a JSON should be self-explanatory. The picture below tells everything.

Simple and Complex JSON

Notice that in the complex example, ‘user-12348-as13s0-dsdf’ appears on the left of the colon in the position wherein a simple example of JSON I have shown a property name. The JSON name data also does not correspond to a property name

How To Deal With Relations

In almost every project, a resource has some kind of relationships and using simply named properties won’t be that helpful. Therefore, in your response representation, you should consider adding LINKS. Let’s assume that JOHN owns a Dog. Now, there exists a relationship between the owner and its Dog.

Response using links

Now both representations are valid. In the left, dogID is clearly describing some sort of relationship. But the representation in the right is more expressive and convenient. Why? Let’s assume that you just retrieved the response for John and now you want to get the dog which he owns. If you follow without-links example, you would have to look into the documentation (wish that the docs are up-to-date) to find a suitable endpoint and then construct that in your code to get his Dog(s). But with ‘with links’ example, you already know where to get the response. An increasing number of APIs from major companies on the web are including links in their data like Google and GitHub.

Now it’s maybe tempting to remove the dogID property from the response. Well, it all depends. Links tell us where we are and to where we should go. But there may be some cases when you need dogID other than retrieving dog’s response.

Companies Using Links

Here’s the Google Drive API example:

Note: The above response is the truncated version.

More Reads:

Part 2 (How to design URLs).
pTron Pride Lite HBE in-Ear Wired Headphones with in-line Mic, 10mm Powerful Driver for Stereo Audio, Noise Cancelling Headset
By: Vasu Rajvi
Tags: Best Practices, Details, Trending, Review, P Tron

pTron Pride Lite HBE in-Ear Wired Headphones with in-line Mic, 10mm Powerful Driver for Stereo Audio, Noise Cancelling Headset Vasu Rajvi Apr 1·2 min read

Stylish, metallic look, in-ear stereo audio quality wired headphones with an in-line mic for hands-free phone calls.

Ergonomic in-ear design allows passive noise cancelation and outstanding sound performance.

Lightweight metal earphones come with 10mm dynamic drivers and neodymium magnets for full-range sound.

Features an HD mic with an in-line remote control to manage music and phone calls at ease — call answer/hang-up, volume control, prev./next track and play/pause music.

Wired earphones with a stylish design, 1.2meter long durable tangle-free cable and universal compatibility. It’s 3.5mm aux jack is compatible with any 3.5mm audio jack devices.

These wired earphones have a wide range of compatibility with the 3.5mm jack. Use it with your smartphones, tablets, MP3 Players, Computers and Laptops. Simple and easy to use without the worry of running out of batteries, just plug and play!

Multi-functions are gathered in one smart button control. Only need simple operations via your fingertips to experience hands-free calling (answer/end/reject), control music (play/pause) and a convenient slider to control music volume

The earphones cord is made soft and flexible so it’s not easy to knot and entangle, and the capability of strong tensile makes you no longer worry about wear-and-tear.
Best practices for .js based UI Automation
By: Shehzada Fahad
Tags: Best Practices, Vscode, JavaScript, Formatting Code, Jsdoc

What is meant by best practices?

Best practices can be considered as a set of guidelines, ethics or ideas that represent the most efficient course of action that may be established by authorities or they may be internally followed by a company’s management team.

During framework development, we need to consider practices that enhance our automation code and show visibility of testing to the development team and client.

Framework hierarchy and structure must have following parameters.

.gitignore file must include /download folder and all the reporting files. We need to follow its practices.

2. Documentation is very important when we handover projects to client or development team. It requires zero learning curve, if readability is clearly visible. Below screenshot follows JSdoc representation on all functions/methods.

@class — represent a class

@Param — represent a function/method with {*} represent it accepts argument with details

3. Naming convention — for locators, we usually follow naming convention in all caps with const. We do not use let/var for these type of files.

For test methods and functions. We can either use camel casing but it is preferable to use kebab-case for JavaScript.

4. Code formatting — it is very important to beautify your code. VS Code provides different linting and prettify extensions that can be used. But its proper usage and configuration should be used.

npm install -D prettier

.prettierrc file with configuration as per need

you can create above configuration file using shortcuts ctrl+shift+p and select prettier: create configuration file

Hence, prettier can be configured through this and we can format document using ctrl + shift + i (for whole document). But it would be hectic to format manually.

VS code provides a feature to format document on save. We just need to enable this feature.

In VS code, go to File -> Preferences -> Settings . Under this select Text editor -> Formatting and select the checkbox saying Format on save.

This way, VS code will automatically format your document on save. Hence, if we accidentally add extra spacing, it will automatically be fixed on save.

There are plenty of other options in settings that can be explored for better coding. Also, VS code provides various extensions to ease programming/automation (coding).

5. Shortcuts — though its not any feature, but if we consider best practices, we should know the shortcuts for the IDE we are using for development. For VS code, its community provide the shortcuts which are very useful for fast development.

6. Report viewer — we use different html reporting in our automation code. We can also use extensions to view report within IDE

No extra configuration required. Just install above extension in VS code. Open html file in VS code and type ctrl+shift+v . It will open report view within editor.

And its preview would be (After pressing ctrl_shift+v )

To sum up, there would be plenty of more options available to explore for best practices. Above mentioned are some of them.
Presenting for Impact
By: Shivakumar Narayanan
Tags: Storytelling For Business, Presentation, Best Practices

There is a lot of advice out there about presentation and communication skills, best practices and what not. What I share here are some thoughts on what I have learnt over the last two decades of working in startups and big companies.

Presentation is not about slides, words etc. It is about the story you want to convey. Be it a technical presentation, a Product Demo or Product Vision or Strategy. Feel free to add other use cases of presentation.

For the sake of simplicity, let us assume you are doing a powerpoint presentation to give an update on product development and possibly a demo — either individually or in a single meeting. My basic approach has been — Be a storyteller or a paint a picture of what they will experience/learn from the presentation.

I would start by what you intend to cover in the presentation, how it can be used, then walk through the key points/information and converge to what you want the take-aways to be.

For a demo only presentation, this can be translated into

Tell the audience what you are going to demo(define scope and expectations) Show the Demo Summarise again what you just demo’ed.

In short, Tell-Show-Tell Again

The key to presentation is what remains when the audience leaves the meeting. Whether they were attentive or not during your entire presentation, you, as a presenter or storyteller have the onus to make sure they have a summary to take away — as in 4–5 key points.

If there are external facing people(people who interface with external entities — customers, investors or Exec Management), then calling out slides of importance would be good. These people are not going to remember all your slides. Asking them to digest only a subset of slides, will be great help for their subsequent action. These slides could be use cases, key differentiators, what is available now or how to sell this to customers.

Even after this, people will only remember what they want to remember. But by having the above approach, you have done your best.

In subsequent posts, I will try to talk about different presentations(focus themes) and how you could approach it. Also will talk about Body Language, How do deal with questions or Devil’s Advocates etc.

Note:

If this applies to you — Good! Incorporate/adopt as much as possible!

If this doesn’t apply to you — Good! You are awesome!

If you did not learn anything new — Good! There will be other things you might learn, keep coming back!
Make More Money In Affiliate Marketing
By: Make Money Online
Tags: Work From Home, Best Practices, Affiliate Marketing, Make Money Online, Passive Income

Affiliate marketing benefits both the online business and the affiliate. With affiliate marketing, an online business will have an increase in traffic on the website, and, consequently, generate more sales. With affiliate marketing, an affiliate can earn money just by referring visitors to the website of the online business. Each client visit is converted to an agreed amount for the affiliate. But, does this happen often?

Some affiliates who have been involved in affiliate marketing may answer that the conversion of visits to money does not happen often enough. Are there too many affiliates already? Of course not. The cyberspace has a limitless supply of clients and their numberss are growing every second. There could never be too many affiliates. But there are methods in which one affiliate can earn more money than his counterparts.

These methods have been proven time and again by affiliate marketing experts. Thus, an affiliate must plan to carry out these suggestions so that his income will greatly increase.

1. Study Search Engine Optimization

The target clients of affiliates are those that get inside cyberspace and surf the Internet to find information and products. These target clients can easily do the surfing and the searching by using Search Engines. Therefore, the affiliate’s website should find its way in the first results page of a Search Engine.

The job now of the affiliate is to find out how to have his website listed and ranked high by Search Engines and Directories. This is why the affiliate should study search engine optimization.

2. Have Good Content

Affiliate marketing is not just about selling products or services. It is also providing useful information to the target clients. Thus, the affiliate must make sure that the articles found in his website should be information-laden.

If the target clients finds the website useful, they will return to the affiliate’s website again and again, until they are convinced enough to proceed to the website of the online business. But if the client finds the affiliate’s website is all flash and no substance, they will immediately find another and better website.

3. Promote More Than One Product

A client likes to be given choices. Thus, the affiliate should respond to this need of clients. The website of the affiliate should be offering options to the client. Each option will be described in terms of advantages and disadvantages. When options are given, convincing the client to patronize a certain product or service becomes easier.

4. Give Away Free Products

The wise affiliate should build loyalty from clients by offering freebies. Such freebies may only be information that can be downloaded by the clients.

With all the above suggestions being kept in the mind by the affiliate, his business of marketing will give him greater returns.
Memento Design Pattern in Java
By: Omid Haghighatgoo
Tags: Java, Best Practices, Memento Pattern, Java Interview Questions, Design Patterns

Implementing memento design pattern using java 11

Memento Design Pattern Implementation in Java 11

1- Brief Introduction

The memento pattern is a software design pattern that is used to store and restore an object to its previous state. Memento pattern is categorized as behavioral pattern same as observer pattern.

2- Memento Design Pattern

Problem: It’s very easy. Have you ever seen undo button in any application?

A little more technical means storing state of an object step by step so we can restore it to any step any time we want.

Solution: Memento Design Pattern!!!

memento design pattern class diagram

3- Implementing Memento Design Pattern in Java

Now we know that we should have three classes.

1- Memento: is an object which is the same as originator state.

Memento class

2- Originator: is an object which would have some states which we want to store and restore them.

Originator class

3- CareTaker: is responsible to keep track of the originator states history by saving them as a stack. Also it is used to retrieved states.

CareTaker class

Now we can use them in out Main class.

Main class
Introduction to dependency Injection-Dagger 2 [Part1]
By: Ebin Joy
Tags: Dependency Management, Best Practices, Dagger 2, Dependency Injection, Android App Development

What is A dependency? In simple words, dependency means relying on something for support, for example, your phone dependent on the sim, battery, display, etc. According to Wikipedia, the definition of dependency injection is

In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A “dependency” is an object that can be used, for example as a service.

Then there will be a famous Question, Why we need dependency Injection?

The DI mechanism separates object production from object consumption

Tightly coupled Vs Loosely coupled

In the above examples class, A depends on class B. In Type1 B is tightly dependent on A, since class A needs to know how to instantiate the object of B. So the class A&B are tightly coupled. Sometimes the object creation of class B may complex because it need/know another ingredient like a, b, c, d, e(some other parameter objects consume in class B).

In Type2, Inorder to create an object of class A we need to pass the object of class B. So class A doesn’t need to worry about the instantiation of class B and it is loosely coupled.

In the above example, we found constructor injection, that’s we passed object ‘b’ to A through the constructor of class A.

Types of dependency injection

Injecting dependencies via constructor

Injection via getter/setter

Interface Injection

Injecting dependencies via constructor

In the above example, class Phone has a dependency on Sim. But these dependency class Sim is not created by Phone, instead of it injected/passed through constructor params ‘Phone(Sim sim)’.

Injection via getter/setter methods

In the above example, class Phone has a dependency on Sim. But these dependency class Sim is not created by Phone, instead of it injected/passed through ‘getSim()’ and ‘setSim()’ methods.

Interface Injection

In the above example, class Phone has a dependency on Sim. But this Sim dependency injected/passed through interface method ‘sendSim(Sim sim)’. The sendsim() method is called by the external part with Sim object.

Again another question, Do we need DI frameworks?

Not at all. You could simply pass all instances to other objects manually by your own logic by the above three ways. If you have a small application there is no need for frameworks like Dagger2.

But frameworks will give you the following advantages

You can remove tons of boilerplate codes.

Help to write and maintain complex relationships between objects.

Maintain the scope of your object nicely( is it needed in entire screen or single window/screen)

Help to share object between multiple screens/class

What’s next? Part2 available here
Best practices for logging in nodejs using winston
By: Manish Kumar
Tags: Logger, Best Practices, Nodejs, Logging, Winston

Winston logging framework in nodejs

In node.js we have a very popular library for logging called “winston”

We’ll go through how to implement winston in our project.

1. Install Winston

npm install winston

npm install winston-daily-rotate-file

2. Create a file quick-logger.js

I have created the file inside services/_helper

3. Configure winston in quick-logger.js

Let's go through what we are doing here.

After importing createrLogger from Winston , we need to pass our config to it.

Log Levels :

There are various Log levels present

Info: Various info for code flow and execution

Error: Logs to find where code execution fails

Warn : Code that is probable to fail

Debug: Can be used to debug code

Formatting

Winston provides formatting to logs , there are various built-in formats (link) that help us in easily analyzing the logs. Here we are combining various formats to build a custom logger.

Transport :

Winston transport helps us in the storage of the logs. It can be a local file or a database. Winston by default provides Console, File, Http, and stream. Apart from these, there are various community-driven transports created that help in logging to AWS, ElasticSearch, etc. You can find all compatible transporters here (Winston-Transports)

Here in transport key (line no 25–34) we are writing error level logs to a file name ‘app-error.log’ and all the combined logs to a file named app-combined.log.

Rotating logs

We have used a custom transport ‘winston-daily-rotate-file’ which is useful in rotating the logs on time basis(hourly/daily/weekly..) or size basis (1 MB, 1 GB..). Here datePattern: ‘YYYY-MM-DD’ identifies that the logs would be rotated in daily basis.

Logs created on daily basis

You can also explore more on writing logs to DB/ElasticSearch using custom transports available.

If we are not in a production environment we are also writing the logs to console for easy development and debugging using the Console transport provided by Winston(line no 42–49 )

Note : create a folder path as /var/log/your-project
Always pass one argument to your JavaScript function
By: Richard D Jones
Tags: Function, Best Practices, Programming, JavaScript, Documentation

Before I try to convince you this is a good idea, let’s take a look at how argument handling works in JavaScript.

A function may specify an arbitrary number of arguments in its declaration:

function callMe(a, b, c) {}

When you invoke this function with the right number of positional arguments then everything makes sense:

function callMe(a, b, c) {

return a + b + c

}

callMe(1, 2, 3) >>> 6

In many other languages, doing anything different would be cause for an exception. Don’t provide enough arguments? Exception. Provide too many arguments? Exception. Not so in JavaScript.

Try calling our function above with too few arguments:

callMe(1,2) >>> NaN

Or with too many:

callMe(1,2,3,4) >>> 6

What’s happening is that JavaScript doesn’t really have the same concept of a method “signature” that you would find in, say, an OO language. When you declare an argument name in a function declaration, all you’re doing is attaching a label to that positional argument for when it is used inside the function. If that argument doesn’t get passed in, the label is undefined . If you pass in an argument for which there is no positional label, then it is still there in the function scope, you just don’t have a name for it.

That explains the outputs of our function calls above. When we omitted a value for c then c was undefined and a + b + c resulted in NaN . When we passed in a fourth argument, the function simply carried on as if it weren’t there.

So what’s the point of being able to pass in values for which no label exists, and therefore can’t be accessed inside the function? Well, the second half of that statement isn’t really true. We can access the value, if you know where to look, and that is in the special arguments local variable that exists inside all declared functions. It’s a special beast, with its own type, and we can convert it to an array if we like:

function callMe() {

return Array.prototype.slice.call(arguments)

}

(note I’m using ES5 here, which will definitely work in your browser of choice. There is a slightly quicker way to do this in ES6 with Array.from(arguments) ).

We’ve declared this function with no positional arguments, just to make the point super clear. We can now call this with an arbitrary number of arguments and it will reflect them back at us:

callMe(1, 2, 3, 4) >>> [1, 2, 3, 4]

The other thing you need to know about arguments, from ES6 onward, is that you can set default values on them like this:

function callMe(a, b=2, c=4) { return a + b + c } callMe(1)

>>> 7 callMe(2, 3)

>>> 9

But you cannot pass the arguments as keywords. What I mean is, the following does not work as you would expect; try it and see:
What Makes a Good Developer?
By: Jonathan Bluks
Tags: Best Practices, Tech, Web Development, Software Development, Careers

3. In The Time Allocated

Productivity and efficiency is big in the world of computers. In fact, it could be argued that the whole “raison d’être” of computers is productivity and efficiency.

That means that as developers, we are entering into that world of productivity and efficiency. On the one hand we are responsible for writing code that makes peoples lives more productive and efficient, and on the other hand, we leverage computers to help bring these advancements to users.

A side-effect of this world is the social expectation of having everything done now. That pressure comes from bosses, clients, users, and the business climate of getting to market first.

That can create a lot of pressure, and we are only human ourselves. We are not generally efficient or productive — at least not in the way that computers are.

There are always unforeseen problems…

Time estimation can be very tricky, and there can be a lot of unknown, unexpected problems that come up when building complex software. With the mentioned social pressure — and the inclination of our minds to skip over details, it is always tempting and easy to underestimate the time required.

Underestimating time to delivery is really dangerous — you will feel under immense stress, feel pressured to cut corners, risk burnout, and negative feelings from your boss/team/clients. Timelines matter and other people are dependent on you meeting agreed upon timelines.

It is better to reasonably overestimate, building in a buffer for when (not if) things go wrong. Have you done this kind work before and how long did it take you in the past? What parts are unknown or new to you?

Knowing yourself based on past performance is critical. You also need to include time for research, testing, and debugging, not just writing your code. Never assume that your code is going to work correctly the first time through and have honest conversations with your team leads, managers, and clients about your concerns and negotiate timelines that work for everyone.

As a developer it is also your responsibility to find all the ways you can be as productive as possible. Are you working to your full capacity? Are you leveraging all the tools available to make your life easier? Work smarter, not harder is an adage that applies here. While you can certainly learn to type and think faster, you will want to rely on your computer to automate large portions of your tasks so you can work on more creative, critical tasks.

Setting reasonable expectations, maintaining the trust of your team, and being seen as a professional, reliable developer is critical to the health of your career. Therefore,
Email Best Practices
By: Rishabh Bohra
Tags: Email Productivity, Email, Best Practices, Gmail, Email Marketing Tips

Opening Lines

Hi/Hello for semi-formal or informal emails(To our friends)

Dear/Mr/Mrs for formal emails( To our colleague and acquaintances)

Post Opening Lines

I write this with reference to the code no 192

Agenda for mail …..

Further to our discussion, I am sending you……

With reference to the email trail

I am writing to enquire about the opening

Thank You for your letter dated 8 Aug…..

Pre Ending Lines

If you require any further information please contact me

Requesting you to look into this and suggest changes

Please advise as necessary

I look forward to your reply

Ending

Thank you! / Thanking you! / Thanks! / Many Thanks!

With Regards/ Best Regards,

%Signature% (Follow company policy for signature)(This can be predefined in our Gmail account and used wherever required)

Do’s To Email Etiquette

Use a strong subject line

Type the correct email id

Use bold to highlight a point

Timely check your Inbox and reply within a reasonable time (If you don’t have instant answer write back to apologize or providing alternative resource or asking time for it)

Be polite and courteous in tone (use words like kindly, do excuse me, looking forward to)

Use “out of office” assistant when on a leave to inform your client/colleague and also to tell them whom they can contact if necessary

Use correct spelling and grammar (use Gmail spell check option)

Write about only one topic in one email

Keep mail formal and avoid jokes.

Keep your email short (if too many points need to be discussed prefer a voice chat)

Proofread all your emails before sending them

Don’ts of Email Etiquette

Don’t write long emails keep your mail short

Don’t use one-word response like ( Yes, No, Confirm) as they don’t convey the proper information ( use line like ‘yes you can do this’, ‘yes I confirm the same’ etc)

Don’t use all UPPERcase or all lowercase in the mail use combination of both

Don’t use unnecessary humor

Don’t send large attachment file with email

Sms language don't be used ( short form and other words of SMS)

If so many people a mail is sent then don't reply back to all of them only reply to the person to whom your reply is relevant

Don't write an email when angry

Don’t reply with an attachment which is attached to your mail to which you want to reply (it unnecessarily increase the size of your mail)

The tone of voice while typing ana Email

Some Questions:-

Some question to find what’s wrong in those email:-

Some Examples of Perfectly written Emails:-

Let’s Practice:-

Summary:-
Performance, Security and target=”_blank”
By: Garima Kamboj
Tags: Performance, Best Practices, Security, HTML

It’s quite surprising and interesting to notice that a lot of developers are not aware of the consequences of using target="_blank" in anchor tags, which motivated me to write about it giving an overview of it’s performance and security impact.

Performance Impact

Whenever you add a hyperlink using anchor tags in your page and use target="_blank" there which is basically to open the linked page in a new tab or window, the browser runs the linked page on the same thread your current page is running on because of synchronous cross window access.

Thus, the size of the linked page affects the performance of your current page based on how heavy the linked page is, it’s scripts, assets, etc. It can even block the further execution of your page for considerable amount of time as your thread now is busy running javascript of the linked page. Your page speed is affected by this at a greater extent.

Browsers like chrome have been looking to use separate threads for the execution of the linked pages. Some browsers optimise this behaviour to run the linked pages on a separate thread thus avoiding the risk of affecting performance of your page.

Security Compromise

Adding the same exposes your website to cyber attacks as window ’s opener api allows access to the window from where the linked page is opened. This means anyone can get reference to your window object through window.opener api and they can do anything they want like redirect your page to a phishing site, reverse tabnabbing, etc.

Photo: Shocked face on Clipart Library

So doing this, you end up giving full control over your page increasing the attack surface of your website without even realising which makes it the worst.

eBay and Heroku are some of those popular names whose web pages were vulnerable at some point because of this.

Solution

Adding the attribute rel="noreferrer noopener" solves this problem. It avoids exploitation of the window.opener api and makes the linked page run in a separate thread or process. Doing this, your web pages are now secure and faster. So, make it a practice to add it to every anchor tag where you use target="_blank" . And yes, the solution is as simple as that.

I would recommend you to avoid linking your pages to external links at all or if it can’t be avoided at least be careful about it as it can increase the attack surface for your page in ways you won’t even realise.

Lastly, please don’t forget how rel="noreferrer noopener" saves the day.

References:

https://jakearchibald.com/2016/performance-benefits-of-rel-noopener/

https://developers.google.com/web/tools/lighthouse/audits/noopener
Dependency Injection and Inversion of Control on .Net Core
By: Alex Alves
Tags: C Sharp Programming, Best Practices, Net Core, Inversion Of Control, Dependency Injection

Do you know about the terms Dependency Inject and/or Inversion of Control? No? Let’s go to talk about it! I’ll explain to you how and why do you need to use these patterns. And finally, we’ll develop a .Net Core simple application that uses these concepts.

Firstly, what do you think to learn the theory? Let’s start learning a little bit about Dependency Injection!

Dependency Injection

Dependency Injection, also known as DI, is a Design Pattern used to avoid coupling inside your code. According to the best practices in software development and part of one of S.O.L.I.D. principles, a class should depend on abstractions and not from concrete classes.

A dependency is an object that your class needs to do the work, in other words, this object isn’t created inside your class. The dependency is injected into a class that uses it, so the dependency is required to be external. The object instantiation (that is the dependency) must not be inside the class, but outside it. Look below a simple example:

In this case, when I instantiate the LeaderboardServiceManager class, I need to pass an IMapper type instantiate. Look, the constructor receives a parameter (mapper) and its value is set to a variable (_mapper) which will be used in the other functions of this class.

Benefits of using it:

Low coupling

Simplicity

Ease of maintenance

Ease to learn about the code/project

Ease to test your code

Exists three most common types of Dependency Injection:

1) Constructor

It is the most common type of DI. When the class’ constructor receives a class or an abstraction of another class as a parameter it is a DI. Look at another example below:

In this case, I receive an ISmtpClient type instantiate by the constructor to use it in some function of my class.

2) Getter and Setter

Injection by properties (get and set). It occurs when exists a class or an abstraction exposed as property. Look the example below:

We have a property SmtpClient of ISmtpClient type, so to this property must be attributed a valid value.

3) Interface Implementation

When the class has a method who receives an abstraction by parameter. In the following example, the method setSmtpClient receives the smtpClient variable of the ISmtpClient interface type (an abstract type).

4) Service locator

It is often called a container. It happens when you have a container that provides many instances and you can just request a specific instance to it. Like this:

First, we should have a class to register and provides the instances

Second, in another part of your code, we can register all the instances

And finally, we can use it like this

And next, let’s go to talk about the Inversion of Control!
🍬 Syntactic sugar, diabetes alert 🚨
By: Maya Shavin
Tags: Best Practices, Front End Development, Programming, JavaScript, ES6

This function, theoretically — without considering inner loop combinations.map() — takes O(n). Linear time - should be good, right? But that’s just in theory.

Why? Because:

map loops through the original array, creates new array based on it and returns the new array — new resource is allocated. Same goes to filter , reverse , etc... reduce also requires to loop through the new array again, and returns a reduced value based on that array with a calculation formula passed. Each of these calls are known to be much slower than the original for loop, regardless how optimised the JS profiler is built. JavaScript is single-thread. This means while it is in a loop, the browser is technically pausing and waiting for the iteration to complete before moving on the next piece of code. Hence the bigger the array is, the more logic to execute, the waiting time will be longer — user will start seeing browser “frozen” more obvious. Linear time doesn’t really apply in this case. In addition, chaining calls like map and reduce here will only make the matter worse, not better (browser needs to “freeze” for the first map to complete, and then again for reduce to complete, and so on). for loop is not in a need of syntactic sugar that badly. We can rewrite the above code using for and stills maintain KISS rule with efficiency (both in resource allocation and performance)

Apparently the syntactic version is way slower than the classic for as in a performance test, despite of the same time efficiency (O(n²)).

In short, it’s O(n) but NOT always O(n), so be careful. Sometimes it’s better to use the classic for loop. Period.

Browser.support(syntactic sugar)?

Exactly, not all syntactic sugar is supported in every browser. That’s why we need Babel — for instance — to make it works.

Yup. Remember our little friend IE (or even Safari 9+?). Some of ES6 syntactic sugar like ... and for..of will not be supported, and suddenly your following sweet and clean code which originally looked like this

const sumUp = (...numbers) => {

let sum = 0;

for(const number of numbers) {

sum += number;

}

return sum;

}

After going through Babel’s compiler, will become (sort of):

var sumUp = function sumUp() {

for (var _len = arguments.length,

numbers = Array(_len), _key = 0;

_key < _len; _key++) {

numbers[_key] = arguments[_key];

} var sum = 0;

for (var _iterator = numbers,

_isArray = Array.isArray(_iterator),

_i = 0,

_iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {

var _ref; if (_isArray) {

if (_i >= _iterator.length) break;

_ref = _iterator[_i++];

} else {

_i = _iterator.next();

if (_i.done) break;

_ref = _i.value;

} var number = _ref; sum += number;

}

return sum;

};

And it suddenly becomes not that efficient anymore 😅

Therefore, as long as your users still use certain browsers, your code needs to work well on them. Thus before putting a new syntactic sugar in your code, don’t forget to double check or read the instructions (aka the documentation).

Being extra careful with new syntax is always a good habit 😉.
How we learned to stop worrying and love pull request templates. And why you should too.
By: Andrei Iordache
Tags: Bitbucket, Best Practices, Pull Request, Template, Github

How we learned to stop worrying and love pull request templates. And why you should too. Andrei Iordache Jun 10, 2019·6 min read

Setting up source control. Maintaining legacy code. Dailies. What do all have in common? They can be tedious, but all of it needs doing. Just like settling on a pull request workflow and sticking with it.

If you`re like us, you probably love coding, but hate the grunt work. That`s one of the reasons we picked up pull request templates (PR templates for short) as a simple tool to improve our workflow. We get to keep things neat and tidy without the tediousness.

And they`re also a great way to make sure you`re not missing anything important when submitting a pull request. When you add a PR template to your repository, the PR description will be automatically populated with the template`s contents and all project contributors will have access to it.

In this article, we`re going to walk you through the steps of creating PR templates on two of the most popular platforms: GitHub and Bitbucket. We also included two PR templates we use in our daily work, which you can customize for your own projects. Finally, we`re going to talk about the benefits of using PR templates and what we`ve gained out of the whole thing.

Adding a PR template to your repository

GitHub

You can create PR templates as files in your repository, either as simple text files or markdown (.md or .markdown). To make sure collaborators can also use the template, store the file on the repository`s default branch.

To create a pull request template, click the Create new file button on the main page of the repository and name your file PULL_REQUEST_TEMPLATE. Make sure to add the .md file extension if you`re going for markdown.
eBook | Strategies for Successful Surveys
Tags: Research, Strategy, Best Practices, Ebooks Online, Surveys

David Lansanah, EVP, Global Head, Strategic Solutions, GLG

Neil Armstrong, an aeronautics engineer, astronaut, and — oh, yeah — the first man to walk on the moon once said, “research is creating new knowledge.” Most research begins with an idea, theory, or hypothesis. But these things are not knowledge, they are suppositions. Suppositions are gateways into knowledge but not knowledge themselves. Without solid research, you’re left guessing.

Quantitative research quantifies a problem by generating numerical data — usually through surveys — that can be used to quantify the behaviors, attitudes, and opinions of specific groups of people. It’s a powerful way to uncover insights that can be applied in business situations. How do engineers regard a specific software product? What is the market potential for a new medical device? How do potential customers feel about the last iteration of your mobile device? Surveys can give you the quantitative insight that helps answer these questions.

But conducting a survey that produces valid, relevant, and actionable data isn’t as easy as drafting a list of questions and sending it out to an email list. How do you craft a survey that gets the information you want? How do you ensure your questions do not create bias or confusion? How do you ensure that your target audience is responding to your survey? It can get complicated quickly.

In GLG’s ebook, Strategies for Successful Surveys, we’ll discuss three aspects of quantitative research. Starting with the basics, you’ll learn how to select the survey that best meets your research needs, how to design your survey, and how you can best reach the right respondents. We’ll cover both questionnaire design (how to create the questionnaire to get great data) and research design (how to reduce bias and weight results).

A well-run survey can provide you with the insight you need to stop a product development roadmap before it makes a wrong turn. It can give you the insight you need to make a smarter investment by understanding how the audience may receive a product or service. It can help you advise clients of your own, by giving you insight that they may not even know they need.

DOWNLOAD THE eBOOK
Is the Longest Password Always the Best for security?
Tags: Best Practices, Passwords

People usually say size matters when it comes to password strength. The longer a password is, the harder it is to crack using brute force algorithms. However, password length is only one factor contributing to password security.

How to harden your password?

One way to create a strong password is by using several characters. The more characters used, the harder a password is to crack.

The four character sets are:

Numerical characters such as 12345

Lowercase characters such as abcdefg

Uppercase characters such as ABCDE

Special characters such as !$%&?

A password consisting exclusively of numerical characters has only ten possible options for each character (0–9). If a password is six numerical characters in length, a hacker can attempt one million possible combinations (10 x 10 x 10 x 10 x 10 x 10).

However, a six-character password consisting of numbers and lowercase letters has thirty-six options for each character (0–9 plus a — z). Now, rather than one million possible combinations, 2,176,782,336 possible combinations exist for a six-character password.

Adding Randomness increases security

A password’s overall randomness also contributes to better password security, and passphrases are an easy way to achieve that. Using a passphrase helps as it combines memorable words or phrases known to the user but less recognizable by hackers.

Another way to strengthen passwords is to avoid commonly used dictionary words or repeated or sequential characters, such as “qwerty”. Likewise, some very long passwords appear in password dumps with remarkable frequency.

One such password is d1k20,q.26n12$$4001nf105j13@$$02@, which, despite being thirty-four characters in length, would be among the first couple of thousand attempts by a brute force hacker.

How password managers help

A password manager helps generate and store unique and complex passwords for each account. The benefit of storing passwords in a password manager is that they are encrypted, hashed, and salted to prevent authorized access — which is a far safer option than storing passwords in plain text format in Word documents or Excel spreadsheets!
Top 5 Kotlin features for better readability
By: Code Fusion
Tags: Best Practices, Clean Code, Readable Code, Kotlin, Readability

Named arguments

In terms of readability, this is by far my favorite Kotlin feature.

Let’s take a look at how we can make an instance of a class without using named arguments:

With named arguments:

By looking at the code you can tell what each of the arguments is used for, also the order of the declaration is up to you! Even better we don’t have to change anything if the order of the constructor’s arguments changes! It also makes your pull requests look cleaner and easier to understand.

Trailing commas

In Kotlin we can add a comma after the last argument

Adding a comma after the last argument

Now let’s say that our Car needs to have heated seats as well:

Adding a comma after the last argument

Now it’s time to make our pull request. Let’s compare the differences with and without trailing commas:

Making a pull request without a trailing comma

Making a pull request with a trailing comma

With the usage of trailing commas, we have just 1 change whereas without a trailing comma we have 3 changes!

Safer class casting

In Java, if we want to cast a class in a safe way we probably would come up with the following code:

Casting an Animal to Cat in Java

As you can see we can’t escape the try-catch block. If we do so we would get “java.lang.ClassCastException”

Thankfully in Kotlin we can skip the try-catch block and use the “as?” operator

Casting an Animal to Cat in Kotlin

If the casting fails the expression returns null but since we are using the safe call operator the meow function would never get executed. If we would like to do more things with our casted object we could use the scoped function called let:

Using the let scoped function in Kotlin

Take If

Any object in Kotlin has the takeIf function predefined. TakeIf is a function that accepts a predicate as an argument and returns the object if the predicate returns true, otherwise it returns null.

Using the takeIf function

Also

Also or also(block: (T) -> Unit): T is another scoped function in Kotlin. We receive as an argument the context object and the return value of .also is the context object itself.

Using the .also scoped function

Here we have a class that reads a string value from a local database. When we read from the local database we are returning the read value and also cache it in the cachedValue variable for later usage.
Microservices application boundary types
By: Milan Brankovic
Tags: Microservices, Best Practices, Microservice Architecture, Software Architecture, Software Development

A microservices architecture is an approach of building a server application as a set of small services. This type of architecture is mainly oriented to the back-end, although it can also be used on front-end.

While building a microservice we need to carefully design boundaries of microservices. A boundary layer provides a façade over the complex interactions inside the microservice.

Let's explore three different patterns.

# API gateways

An API gateway provides an extra layer, a single client-entry point over a service-oriented back-end. An API gateway takes all API calls from clients, then routes them to the appropriate microservice with request routing, composition, and protocol translation. Typically it handles a request by invoking one or more microservices and combining the results into a unified, seamless experience for the user.

Sitting in front of APIs, the gateway acts as protector, enforcing security and ensuring scalability and high availability. An API gateway can restrict the microservices which external consumers can access within the protected architecture as well as control the bandwidth which flows into the system.

Rather than provide a one-size-fits-all style API, the API gateway can expose a different API for each client.

# Backends for frontends (BFF)

In the Backend for Frontend pattern, a service (“the backend”) serves as a termination point for a requesting interface (“the frontend”). BFF is a variation on the API gateway approach.

A BFF can be used to elegantly expose complex backend systems to multiple client-facing platforms, such as iOS and the web, without building a monolothic API that attempts to serve all clients equally.

As BFF is tightly coupled to a specific user experience, it will typically be maintained by the same team as the user interface. Having this in mind it will be easier to define and adapt the API as the UI requires. As a result, each backend will be smaller, less complex and likely faster (and more decoupled) than a generic backend that tries to satisfy the requirements for all interfaces, because each backend is specific to one user interface.

# Consumer driven gateways

In both previous approaches, the API gateway determines the structure of the data returned to the consumer. In order to serve different clients, you might choose to build unique backends. But, you can also flip things around — build a gateway that allows consumers to express exactly what data they need from the service.

Think of it as a variation of BFF approach, building a single "super-set" API that allows consumers to define the shape of response they require. Most popular libraries using this approach are GraphQL an Apollo.