Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: add new no-throw and/or no-try-catch rules (functional style rules) #86

Closed
RebeccaStevens opened this issue Jun 17, 2018 · 1 comment

Comments

@RebeccaStevens
Copy link
Collaborator

RebeccaStevens commented Jun 17, 2018

Exceptions, try-catch[-finally] and try-finally patterns are not functional.
I would like to propose adding 1 or 2 new rules to prevent the use of these.

Below are some examples on how to switch out use of throw and try-catch.

Original code for examples:

const numbers = [[4, 2], [6, 0], [3, 4]];

try {
  doDivide(numbers).forEach((result) => {
    console.log(result);
  });
} catch(error) {
  console.error(error.message);
}

function doDivide(numbers: number[][]): number[] {
  return numbers.map(([x, y]) => divide(x, y));
}

function divide(x: number, y: number): number {
  if (y === 0) {
    throw new Error('Cannot divide by zero.')
  }
  return x / y;
}

Example - Returning an error:

const numbers = [[4, 2], [6, 0], [3, 4]];

const results = doDivide(numbers);
const error = results.find(result => result instanceof Error) as Error | undefined;

error === undefined
? results.forEach((result) => {
    console.log(result);
  })
: console.error(error.message);

function doDivide(numbers: number[][]): (number | Error)[] {
  return numbers.map(([x, y]) => divide(x, y));
}

function divide(x: number, y: number): number | Error {
  return (
    y === 0
    ? Error('Cannot divide by zero.')
    : x / y
  );
}

Example - Returning a rejected promise:
(Should only be used with async code)

const numbers = [[4, 2], [6, 0], [3, 4]];

doDivide(numbers)
  .then((results) => {
    results.forEach((result) => {
      console.log(result);
    });
  })
  .catch((error) => {
    console.error(error.message);
  });

async function doDivide(numbers: number[][]): Promise<number[]> {
  return Promise.all(
    numbers.map(async ([x, y]) => divide(x, y))
  );
}

async function divide(x: number, y: number): Promise<number> {
  return (
    y === 0
    ? Promise.reject(Error('Cannot divide by zero.'))
    : x / y
  );
}
@jonaskello
Copy link
Owner

Yes, I think this makes sense, something like no-try and no-throw maybe?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants