aboutcode-org / aboutcode-org/vulnerablecode

Limit 'try' block to a single piece of logic

Offen
#876 0 Kommentare 0 Reaktionen 1 zugewiesene Person Beansprucht von @johnmhoran Auf GitHub ansehen
ui
Vorherrschende Sprache
Python
Sterne
702
Forks
328
Ø Merge
3 T. 8 Std.
Gemergte PRs (30 T.)
3

Beschreibung

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.

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.