aboutcode-org / aboutcode-org/vulnerablecode

Limit 'try' block to a single piece of logic

Aberta
#876 0 comentários 0 reações 1 responsável Reivindicada por @johnmhoran Ver no GitHub
ui
Linguagem predominante
Python
Estrelas
702
Forks
328
Merge médio
3d 8h
PRs com merge (30d)
3

Descrição

From @tdruez 's comments in https://github.com/nexB/vulnerablecode/issues/875 .

Excerpts:

![image](https://user-images.githubusercontent.com/11096678/186770892-9e364ba3-5576-487b-ac54-986b95069040.png)

The QS should live outside the try block.

> what's the reason to move the Qs outside the try block

In general, you want to keep only one piece of logic that could fail within a `try` block.
An exception raised by converting a PURL has nothing to do with an exception filtering a QuerySet.

Also, using generic `except:` is bad practice. You should always try to be explicit about the exception you want to catch. Since you want to "Check whether the input value is a syntactically-correct purl", let's catch that specific Exception:
```
>>> PackageURL.from_string('wrong syntax')
Traceback (most recent call last):
File "", line 1, in
File "/Volumes/nexB/repos/scancode.io/lib/python3.9/site-packages/packageurl/__init__.py", line 354, in from_string
raise ValueError(
ValueError: purl is missing the required "pkg" scheme component: {repr(purl)}.
```

The packageurl raise a `ValueError` in that case, that's the exception we want to catch.
You code could become:

```
try:
purl = PackageURL.from_string(package_name)
except ValueError:
purl = None

if purl:
packages = ...
else:
packages = ...

return list(packages)
```

This way, this are properly grouped, the code is more readable:
1. we deal with the purl
2. we prepare a queryset based on the available data
3. we return the fetched objects

> keeping the try focused on its sole purpose: the purl test?

Yes, bottom line is to always try to keep you `try` block as focused as possible.

Guia de contribuição

Nenhum guia de contribuição indexado para este repositório

Avaliação

Esta issue ainda não foi avaliada.

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.