aboutcode-org / aboutcode-org/vulnerablecode

Limit 'try' block to a single piece of logic

Aperta
#876 0 commenti 0 reazioni 1 assegnatario Rivendicata da @johnmhoran Vedi su GitHub
ui
Lingua principale
Python
Stelle
702
Fork
328
Merge medio
3g 8h
PR unite (30g)
3

Descrizione

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.

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.