Conditions | 14 |
Total Lines | 51 |
Lines | 0 |
Ratio | 0 % |
Changes | 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 ListMessages() 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 | from core.helpers import pad_title, timestamp |
||
19 | @route(PLUGIN_PREFIX + '/messages/list') |
||
20 | def ListMessages(viewed=None): |
||
21 | # Cast `viewed` to boolean |
||
22 | if type(viewed) is str: |
||
23 | if viewed == 'None': |
||
24 | viewed = None |
||
25 | else: |
||
26 | viewed = viewed == 'True' |
||
27 | |||
28 | # Retrieve messages |
||
29 | messages = list(List( |
||
30 | viewed=viewed |
||
31 | ).order_by( |
||
32 | Message.last_logged_at.desc() |
||
33 | ).limit(50)) |
||
34 | |||
35 | total_messages = List().count() |
||
36 | |||
37 | # Construct container |
||
38 | oc = ObjectContainer( |
||
39 | title2="Messages" |
||
40 | ) |
||
41 | |||
42 | for m in messages: |
||
43 | if m.type is None or\ |
||
44 | m.summary is None: |
||
45 | continue |
||
46 | |||
47 | thumb = None |
||
48 | |||
49 | if m.type == Message.Type.Exception: |
||
50 | thumb = R("icon-exception-viewed.png") if m.viewed else R("icon-exception.png") |
||
51 | elif m.type == Message.Type.Info: |
||
52 | thumb = R("icon-notification-viewed.png") if m.viewed else R("icon-notification.png") |
||
53 | elif m.type in ERROR_TYPES: |
||
54 | thumb = R("icon-error-viewed.png") if m.viewed else R("icon-error.png") |
||
55 | |||
56 | oc.add(DirectoryObject( |
||
57 | key=Callback(ViewMessage, error_id=m.id), |
||
58 | title=pad_title('[%s] %s' % (Message.Type.title(m.type), m.summary)), |
||
59 | thumb=thumb |
||
60 | )) |
||
61 | |||
62 | # Append "View More" button |
||
63 | if len(messages) != 50 and len(messages) < total_messages: |
||
64 | oc.add(DirectoryObject( |
||
65 | key=Callback(ListMessages), |
||
66 | title=pad_title("View All") |
||
67 | )) |
||
68 | |||
69 | return oc |
||
70 | |||
200 |