Conditions | 8 |
Total Lines | 51 |
Lines | 0 |
Ratio | 0 % |
Changes | 3 | ||
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:
1 | from datetime import datetime |
||
79 | def poll(self): |
||
80 | |||
81 | for hostname, device_obj in self.devices.items(): |
||
82 | |||
83 | try: |
||
84 | last_bgp_peers = self.device_state[hostname]["last_bgp_peers"] |
||
85 | except KeyError: |
||
86 | |||
87 | # Get current BGP peers (instead of setting to 0 and |
||
88 | # triggering every time sensor starts initially) |
||
89 | try: |
||
90 | self.device_state[hostname] = { |
||
91 | "last_bgp_peers": self.get_number_of_peers(device_obj) |
||
92 | } |
||
93 | continue |
||
94 | # Any connection-related exception raised here is |
||
95 | # driver-specific, so we have to catch "Exception" |
||
96 | except Exception as e: |
||
97 | self._logger.debug("Caught exception on connect: %s" % e) |
||
98 | continue |
||
99 | |||
100 | try: |
||
101 | this_bgp_peers = self.get_number_of_peers(device_obj) |
||
102 | # Any connection-related exception raised here is |
||
103 | # driver-specific, so we have to catch "Exception" |
||
104 | except Exception as e: |
||
105 | self._logger.debug("Caught exception on get peers: %s" % e) |
||
106 | continue |
||
107 | |||
108 | if this_bgp_peers > last_bgp_peers: |
||
109 | self._logger.info( |
||
110 | "Peer count went UP to %s" % str(this_bgp_peers) |
||
111 | ) |
||
112 | self._bgp_peer_trigger(BGP_PEER_INCREASE, hostname, |
||
113 | last_bgp_peers, this_bgp_peers) |
||
114 | |||
115 | elif this_bgp_peers < last_bgp_peers: |
||
116 | self._logger.info( |
||
117 | "BGP neighbors went DOWN to %s" % str(this_bgp_peers) |
||
118 | ) |
||
119 | |||
120 | self._bgp_peer_trigger(BGP_PEER_DECREASE, hostname, |
||
121 | last_bgp_peers, this_bgp_peers) |
||
122 | |||
123 | elif this_bgp_peers == last_bgp_peers: |
||
124 | self._logger.info( |
||
125 | "BGP neighbors STAYED at %s" % str(this_bgp_peers) |
||
126 | ) |
||
127 | |||
128 | # Save this state for the next poll |
||
129 | self.device_state[hostname]["last_bgp_peers"] = this_bgp_peers |
||
130 | |||
183 |