Say I have the following classes:
abstract class AbstractFileReader {
// ???
}
class SyncFileReader extends AbstractFileReader {
public readFileDecorated(filePath: string): string {
console.log('Filepath: ');
console.log(filePath);
const contents = this.readFileInternal(filePath);
console.log('Length of file: ');
console.log(contents.length);
return contents;
}
private readFileInternal(filePath: string): string {
return fs.readFileSync(filePath, {'encoding': 'utf8'});
}
}
class AsyncFileReader extends AbstractFileReader {
// highly redundant code...
public async readFileDecorated(filePath: string): Promise<string> {
console.log('Filepath: ');
console.log(filePath);
const contents = await this.readFileInternal(filePath);
console.log('Length of file: ');
console.log(contents.length);
return contents;
}
private async readFileInternal(filePath: string): Promise<string> {
return await fs.promises.readFile(filePath, {'encoding': 'utf8'});
}
}
const syncFileReader = new SyncFileReader();
const asyncFileReader = new AsyncFileReader();
asyncFileReader.readFileDecorated('./test.txt').then((contents) => {
console.log(contents);
}).catch((reason) => console.log('abc'));
// The following call should still work without change after the changes in AbstractFileReader.
console.log(syncFileReader.readFileDecorated('./test.txt'));
The code in readFileDecorated (just a silly example of course) is highly redundant, so I want to put it in a method in AbstractFileReader instead. However, the problem is that readFileDecorated is sync in SyncFileReader but async in AsyncFileReader.
The straightforward solution I came up with was to make everything async in AbstractFileReader. This would work, but then, the call in the last line had to be changed, which I do not want to do because a SyncFileReader should expose only sync syntax.
Another solution was to use readFileDecoratedPre(filePath) and readFileDecoratedPost(contents) methods that are called before or after (resp.) the call to readFileInternal, but this would not be a feasible solution when a method contains several sync/async calls.