Separate and unchanging code

Source: Internet
Author: User
Tags file handling

When working with files, the code we want to write is robust. If a long-running file handler does not perform a robust operation on the file, there are some problems.

such as an HTTP server, it is mainly to open the file and read the content, sent to the requestor. If there is a problem with the network connection, which causes the file being transferred to not be closed, we can only restart the HTTP server if we want to modify the contents of the file.

In order to write robust file handling code, we usually use the try-catch-finally statement block:

1FileStream file = null;
2try
3{
4 file = new FileStream (path, mode, access);
5//do something
6}
7catch (IOException e)
8{
9 throw e;
11finally
12{
if (file!= null)
{
file. Close ();
17}

Wouldn't it be annoying if your code is full of code that's in this pattern? If you read the contents of a file, the code that might really be useful is just a few lines of code. For robustness, we have to write 10 lines of code to handle exceptions and close files.

Do you think of the encapsulation of these patterns of code? Not bad! In order to write less code, encapsulation is a good thing, and we can focus on this pattern of code. As far as thinking is concerned, we use the changed content as the parameter of the method. We use proxies for code that handles changes while encapsulating this operation.

It is not difficult to encapsulate this mode of operation.

First we need a proxy that contains a FileStream type of argument:

delegate void Processfilestreamcallback (FileStream file);

Although the name of this agent is very long, we can use the anonymous function to reduce the number of words.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.