Constructors or Properties

One thing, I regularly struggle with is remembering all of the properties that I need to set up on an object in order to be able to perform an operation. For example, if you use the FTPWebRequest class, then most of the time you simply,

  • Create an instance of the class using WebRequest.Create(Uri)
  • Set the Username/Password using a NetworkCredentials (or another class that derives from ICredentials)
  • Call GetResponse()

When you are doing an upload you need to two additional steps

  • Tell the object that it needs to receive a known number of bytes into its request stream.
  • Write the contents of your local file into Stream returned by GetRequestStream()

i.e.

private void Put(string relativePath, FileStream fileStream)
{
    FtpWebRequest request = WebReqeust.Create(relativePath);
    request.Credentials = new NetworkCredentials(username, password);
    request.Method = WebRequestMethods.Ftp.UploadFile;     
    request.ContentLength = fileStream.Length;      
    Stream requestStream = request.GetRequestStream();        
    CopyStream(fileStream, requestStream);
}

To me this borders on un-intuitive, but then I don't really see an alternative. Consider the following

private void Put(string relativePath, FileStream fileStream)
{            
    FtpWebRequest request = WebRequest.Create(relativePath,         
        new NetworkCredentials(username, password),        
        WebRequestMethods.Ftp.UploadFile,        
        fileStream.Length);    
    Stream requestStream = request.GetRequestStream();        
    CopyStream(fileStream, requestStream);
}

private FileStream Get(string relativePath)
{            
    FtpWebRequest request = WebRequest.Create(relativePath,         
        new NetworkCredentials(username, password),        
        WebRequestMethods.Ftp.DownloadFile);    
    WebResponse response = request.GetResponse();        
    return response.GetResponseStream();
}

Now I have different constructors with a different number of arguments, and I still don't know which one to use.  We can of course get around this by the use of factory methods, and with the use of extension methods, we can even make it seem as if it was always meant to be the right way.

However I think this may once again fall back to Martin Fowler's article on attitudes.

  • Properties enable the developer who follows to choose their own way to structure their object creation and preparation
  • Constructors direct the developer who follows down a very specific route, where each parameter must come in a pre-ordained order

Add comment

  Country flag


  • Comment
  • Preview
Loading