## Lazy Disposable

A lot of bugs are associated with
[sequential coupling](https://en.wikipedia.org/wiki/Sequential_coupling) anti-pattern.
One particualar case is disposable objects. The objects that are required to be disposed
as soon as they are not in use anymore. These objects can't be cleaned by garbage
collector, for example, files has to be closed, callbacks/events has to be
unsubscribed etc. Different languages provides different solutions for the problem.

### C

In C language you need to call these dispose functions manually.

```c
FILE *fp;
fp = fopen("somefile.txt", "r");

// ... read file here ...

// dispose method
fclose(fp);
```

### C++

C++ and other languages with determenistic memory allocation have a destructors which
uses [RAII](https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization)
programming idiom.

```c++
{
    ofstream file;
    file.open("somefile.txt");

    // read file here.

    // no need to call file.close() method because destructor will be called at
    // this point and close the file
}
```

### Java, C# and other GC Languages

Suprisingly, a lot of GC languages don't have a good language support for
disposable objects. In most cases, developers should manually dispose objects.

```java
FileInputStream input = new FileInputStream(...);

// ... read file here ...

input.close();
```

Can you see a bug? If an exception is thrown before `input.close()` then the file will be
left open.

```java
FileInputStream input = new FileInputStream(...);
try {
    // ... read file here ...
} finally {
    input.close();
}
```

C# appears later (**2002**) and tried to address the issue by adding the `IDisposable` interface and
the `using` statement

```c#
using(FileStream file = File.Open("somefile.txt", FileMode.Open))
{
    // ... read file here ...

    // no need to call file.Close() method because `Dispose` method will be called at
    // this point and close the file.
}
```

The `using` statement adds some automation but even the recent compiler doesn't prevent
you to write code without the using statement

```c#
{
    FileStream file = File.Open("somefile.txt", FileMode.Open)

    // ... read file here ...

    // nobody closes the file.
}
```

The compiler will not give you even a warning about the problem.

Later, a similar to `using` syntax was included in Java 7 (**2011**).

```java
try(FileInputStream input = new FileInputStream(...)) {

    // ... read file here ...

    // no need to call file.close() method because `close` method will be called
    // automatically.
}
```

Well, almost 10 years to partially fix the problem. Design problems are expensive.

### A solution for GC Languages

The Wikipedia article mentions a solution for the sequential coupling anti-pattern. It's
called [Templeate Method Pattern](https://en.wikipedia.org/wiki/Template_method_pattern).
The method doesn't require redisigning the language. Here's an example how it can be
done in TypeScript without changing the language.

Here's an example of template method pattern for open file synchonously

```typescript
function openSyncUsing<T>(
    path: string,
    flags: string,
    context: (fileHandle: number) => T)
    : T {
    const fileHandle = fs.openSync(path, flags);
    try {
        return context(handle);
    } finally {
        fs.closeSync(fileHandle);
    }
}

// example
openSyncUsing("somefile", "r", fileHandle => {

    // ... read file here ...

    // no need to call fs.closeSync() here
});
```

Or asynchronous implementation

```typescript
function openUsing<T>(
    path: string, flags: string, context: (fileHandle: number) => Promise<T>)
    : Promise<T> {
    const handlePromise = fsp.open(path, flags);
    return handlePromise
        .then(context)
        .then(
            value => fsp.close(handle).then(() => value),
            err => fsp.close(handle).then(() => Promise.reject(err))));
}

// example
openUsing("somefile", "r", fileHandle => {

    // ... read file here ...

    // no need to call fs.closeSync() here
});
```

A more generic version of the asynchronous disposable template method pattern is
implemented in this package. See the `lazyDispose` function.

```typescript
function open(path: string, flags: string): LazyDisposable<number> {
    return lazyDisposable(() => fsp.open(path, flags), fsp.close);
}

// example of disposable template method pattern.
open("somefile", "r").using(fileHandle => {

    // ... read file here ...

    // no need to call fs.closeSync() here
});
```