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