Conditions | 13 |
Total Lines | 51 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like describe_cache() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | # pylint: disable=missing-docstring,unused-variable,unused-argument,expression-not-assigned,singleton-comparison |
||
11 | def describe_cache(): |
||
12 | |||
13 | @pytest.fixture |
||
14 | def cache(): |
||
15 | return Cache() |
||
16 | |||
17 | @pytest.fixture |
||
18 | def cache_empty(cache): |
||
19 | # pylint: disable=protected-access |
||
20 | cache._data.clear() |
||
21 | return cache |
||
22 | |||
23 | @pytest.fixture |
||
24 | def cache_missing(cache_empty): |
||
25 | try: |
||
26 | os.remove(Cache.PATH) |
||
27 | except OSError: |
||
28 | pass |
||
29 | return cache_empty |
||
30 | |||
31 | @pytest.fixture |
||
32 | def cache_corrupt(cache): |
||
33 | # pylint: disable=protected-access |
||
34 | cache._data = "corrupt" |
||
35 | cache._store() |
||
36 | return cache |
||
37 | |||
38 | def describe_init(): |
||
39 | |||
40 | def it_loads_previous_results(cache_empty): |
||
41 | cache_empty.set("url", {}, "previous") |
||
42 | |||
43 | cache = Cache() |
||
44 | expect(cache.get("url", {})) == "previous" |
||
45 | |||
46 | def it_handles_missing_cache_files(cache_missing): |
||
47 | expect(Cache().get("url", {})) == None |
||
48 | |||
49 | def it_handles_corrupt_cache_files(cache_corrupt): |
||
50 | expect(Cache().get("url", {})) == None |
||
51 | |||
52 | def describe_get(): |
||
53 | |||
54 | def it_hits_with_existing_data(cache_empty): |
||
55 | cache = cache_empty |
||
56 | cache.set("url", {}, "existing") |
||
57 | |||
58 | expect(cache.get("url", {})) == "existing" |
||
59 | |||
60 | def it_misses_with_no_data(cache_empty): |
||
61 | expect(cache_empty.get("url", {})) == None |
||
62 |