Conditions | 11 |
Paths | 30 |
Total Lines | 48 |
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:
1 | <?php |
||
26 | function update($new_status) |
||
27 | { |
||
28 | if (strlen($new_status) > 140) { |
||
29 | $this->error = "Status too long: {$new_status}."; |
||
30 | return false; |
||
31 | } |
||
32 | $fp = @fsockopen('twitter.com', 80, $errno, $errstr); |
||
33 | if (!$fp) { |
||
34 | $this->error = "Socket error #{$errno}: {$errstr}"; |
||
35 | return false; |
||
36 | } |
||
37 | $post_data = 'status=' . urlencode($new_status); |
||
38 | $to_send = "POST /statuses/update.xml HTTP/1.1\r\n"; |
||
39 | $to_send .= "Host: twitter.com\r\n"; |
||
40 | $to_send .= 'Content-Length: ' . strlen($post_data) . "\r\n"; |
||
41 | $to_send .= "Authorization: Basic {$this->auth}\r\n\r\n"; |
||
42 | $to_send .= $post_data . "\r\n\r\n"; |
||
43 | $bytes = fwrite($fp, $to_send); |
||
44 | if ($bytes === false) { |
||
45 | $this->error = 'Socket error: Error sending data.'; |
||
46 | return false; |
||
47 | } elseif ($bytes < strlen($to_send)) { |
||
48 | $this->error = 'Socket error: Could not send all data.'; |
||
49 | return false; |
||
50 | } |
||
51 | if ($this->debug) echo "Sent:\n{$to_send}\n\n"; |
||
52 | $response = ''; |
||
53 | while (!feof($fp)) { |
||
54 | $buf = fread($fp, 1024); |
||
55 | if ($buf === false) { |
||
56 | $this->error = 'Socket error: Error reading data.'; |
||
57 | return false; |
||
58 | } |
||
59 | $response .= $buf; |
||
60 | } |
||
61 | if ($this->debug) echo "Received:\n{$response}"; |
||
62 | $was_error = preg_match('#' . preg_quote('<error>') . '(.+)' . preg_quote('</error>') . '#i', $response, $matches); |
||
63 | if ($was_error) { |
||
64 | $this->error = "Twitter error: {$matches[1]}"; |
||
65 | return false; |
||
66 | } |
||
67 | list($first_line) = explode("\r\n", $response); |
||
68 | if ($first_line !== 'HTTP/1.1 200 OK') { |
||
69 | $this->error = "Request error: {$first_line}"; |
||
70 | return false; |
||
71 | } |
||
72 | return true; |
||
73 | } |
||
74 | |||
76 |
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.