I've just noticed this somewhere:
public string MakeRequest(string hostname, string message)
{
Socket socket = null;
IPAddress serverAddress = null;
IPEndPoint serverEndPoint = null;
byte[] sendBytes = null, bytesReceived = null;
int bytesReceivedSize = -1, readSize = 4096;
serverAddress = Dns.Resolve(hostname).AddressList[0];
serverEndPoint = new IPEndPoint(serverAddress, 80);
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
bytesReceived = new byte[readSize];
sendBytes = Encoding.ASCII.GetBytes(message);
socket.Connect(serverEndPoint);
socket.Send(sendBytes);
bytesReceivedSize = socket.Receive(bytesReceived, readSize, 0);
socket.Close();
if(-1 != bytesReceivedSize)
{
return Encoding.ASCII.GetString(bytesReceived, 0, bytesReceivedSize);
}
return "";
}
Why do programmers still write code like this in C#? Do they like verbosity? Why not write this instead:
public string MakeRequest(string hostname, string message)
{
IPAddress serverAddress = Dns.Resolve(hostname).AddressList[0];
IPEndPoint serverEndPoint = new IPEndPoint(serverAddress, 80);
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
int readSize = 4096;
byte[] bytesReceived = new byte[readSize];
byte[] sendBytes = Encoding.ASCII.GetBytes(message);
...
}
It seems to me there are loads of these statement level refactorings that would prove really useful. Do any tools support "small" refactoring like this? Do any books talk about them?
Here's another: Instead of writing:
if (expression)
return true;
else
return false;
why not just write:
return expression;