Categories
IntelliJ

Avoiding Wildcard imports in Java/Kotlin with IntelliJ

What is a wildcard import or a star import?

When you want to import multiple classes from the same package like this:

import com.example.exception.CustomerNotFoundExcetpion
import com.example.exception.ProductNotFoundExcetpion
import com.example.exception.ProductOutOfStockException
import com.example.exception.AdressNotFoundException

Java has an option to combine them into a single line using wildcard imports:

import com.example.exception.*

Is it bad?

Performance-wise, no. Using a wildcard import doesn’t actually import all the classes in the package. When your code is compiled, only the classes used from this package are added to the bytecode. So there is zero performance difference between wildcard import and explicit imports.

Then why should we avoid it?

  • Explicit imports clearly states what external classes the current class is directly using, provided that you don’t leave redundant imports in your code.
  • If there are two classes with the same name from different packages, it can introduce collision when using wildcard imports.
  • When multiple people are working in a project, wildcard imports can create confusion as to which classes are actually imported

Many large Java projects that I have worked with, have a checkstyle rule to disallow wildcard imports for the above reason.

Now that we have understood why explicit imports are better than implicit imports, let’s see how we can make IntelliJ always use explicit imports.

By default, IntelliJ will convert implicit imports into wildcard imports when it sees 5 import statements from the same package.

This setting can however by set to a large value like 99 to prevent the automatic wild card imports.

Goto Preferences -> Editor -> Code Style -> Java (or Kotlin) -> Update the following two values to 99:

  • Class count to use import with ‘*’
  • Names count to use static import

Click ‘Apply’ and close the dialog. Now do ‘Optimize Imports’ again to remove the wildcard imports automatically now and in the future.

More ‘Import’ options can be customized with IntelliJ. Follow this link for more customizations: https://www.jetbrains.com/help/idea/creating-and-optimizing-imports.html

The default Sun & Google’s Checkstyle rules also recommend avoiding star import by throwing this exception:

(imports) AvoidStarImport: Using the '.*' form of import should be avoided

To add this rule to your checkstyle configuration, add this line:

<module name="AvoidStarImport"/>
Categories
HTML

First look at HTML

HTML is used to feed the content on the web page or web application.

HTML = content.

HTML is not used for styling the page if you want to style then you need to use CSS.

HTML ≠ style. CSS = style.

HTML Document Structure

All HTML document must start with <html> and end with </html>.

<body> … </body> body tag is where the content is entered and visible in the browser.

<!DOCTYPE HTML>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

If you don’t know how to run this code you can use this link and follow the steps.

HTML Headings :

  • <h1> </h1> tags are used to define the headings.
  • heading tags vary from <h1> to <h6>.
  • <h1> with the larger size and the size reduce when the number increases till <h6>.
<html>
<body>

<h1> This is h1 element </h1>
<h2> This is h2 element </h2>
<h3> This is h3 element </h3>
<h4> This is h4 element </h4>
<h5> This is h5 element </h5>
<h6> This is h6 element </h6>

</body>
</html>

you can copy paste this code and run it using editor.

HTML Paragraph:

<p> tags are used to define the HTML paragraph.

<html>
<body>

<p> This is an paragraph </p>
<p> this is an second paragraph </p>

</body>
</html>

you can copy paste this code and run it using editor.

Categories
HTML Web Development

How to run an HTML file?

Many modern editors are available to create and modify web pages. But we recommend using simple editors like Notepad (windows) and Textedit (Mac).

How to open Notepad in windows?

Open start and type notepad at search.

(OR)

Open Start > Programs > Accessories > Notepad.

How to open Textedit in Mac?

press command + space enter Spotlight search will appear and type Textedit in that search.

(OR)

Open Finder > Applications > TextEdit

For mac, we recommend installing sublime text https://www.sublimetext.com/3

Let’s get started!

<html>
<header><title> This is title </title> 
</header>
<body>
Hello world
</body>
</html>

Copy the above code and past it the Notepad (or) Textedit.

Select File > Save as

Name the file as index.html. all HTML files should be in <filename>.html format.

Double click on the file, or right-click – and choose “Open with” and select your preferred browser.

the output may look like this.

Categories
React

React: How to use Apollo with ‘Union Types’ in GraphQL

Apollo is one of the most popular React library to work with GraphQL APIs. However they don’t have native support when your APIs contain union types.

Let’s look at an example API that contains union types and how we can work with them using Apollo. Assuming you have an API like this:

{
  search(text: "an") {
    __typename
    ... on Human {
      name
      height
    }
    ... on Droid {
      name
      primaryFunction
    }
    ... on Starship {
      name
      length
    }
  }
}

that returns this response….

{
  "data": {
    "search": [
      {
        "__typename": "Human",
        "name": "Han Solo",
        "height": 1.8
      },
      {
        "__typename": "Human",
        "name": "Leia Organa",
        "height": 1.5
      },
      {
        "__typename": "Starship",
        "name": "TIE Advanced x1",
        "length": 9.2
      }
    ]
  }
}

If you use the above query via Apollo, you will see this warning messages in the browser console:

You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the `IntrospectionFragmentMatcher` as described in the docs: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher

This is because Apollo by default uses a simple heuristics matching to match the response string into the Response object. We need to do some extra work to tell Apollo how to parse the response with union types.

Apollo has a separate section on their docs about this.

Step 1: Save the information about the fragment types in a separate file:

const fetch = require('node-fetch');
const fs = require('fs');

fetch(`${YOUR_API_HOST}/graphql`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    variables: {},
    query: `
      {
        __schema {
          types {
            kind
            name
            possibleTypes {
              name
            }
          }
        }
      }
    `,
  }),
})
  .then(result => result.json())
  .then(result => {
    // here we're filtering out any type information unrelated to unions or interfaces
    const filteredData = result.data.__schema.types.filter(
      type => type.possibleTypes !== null,
    );
    result.data.__schema.types = filteredData;
    fs.writeFile('./fragmentTypes.json', JSON.stringify(result.data), err => {
      if (err) {
        console.error('Error writing fragmentTypes file', err);
      } else {
        console.log('Fragment types successfully extracted!');
      }
    });
  });

The JSON file should look something like this:

{
  "__schema": {
    "types": [
      {
        "kind": "UNION",
        "name": "UnionSearchDetails",
        "possibleTypes": [
          {
            "name": "Human"
          },
          {
            "name": "Droid"
          },
          {
            "name": "Starship"
          }
        ]
      }
    ]
  }
}

Step 2: Create fragmentMatcher using the JSON file from the previous step:

import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import introspectionQueryResultData from './fragmentTypes.json';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData
});

Step 3: Now include this fragmentMatcher in cache object and pass it to the Apollo client:

import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';

// add fragmentMatcher code from step 2 here

const cache = new InMemoryCache({ fragmentMatcher });

const client = new ApolloClient({
  cache,
  link: new HttpLink(),
});

Now all done. The warnings and errors that you noticed previously should have gone away and the Response object from Apollo should contain the correct data.

How to use ‘Union types’ in tests and storybooks?

Now that you have fixed the problem for production code, how can we fix it for your tests or storybooks?

Apollo provides MockedProvider for this purpose. Here is a sample:

<MockedProvider mocks={mocks} addTypename cache={cache}>
     <MyComponenent />
</MockedProvider>

The important change here from the sample code is that addTypename has to be true, to allow Apollo to use the __typename in the response to map the object to the correct type.