Consider a scenario where having a structured approach is necessary. For instance, imagine you have your own library or app structured like this.
- src
- views
ListView.ts
PinnedListView.ts
- test
App.ts
Here is an example of how your files might look before and after implementing the structure.
Before
// ListView.ts
class ListView<A extends Adapter> {
protected adapter?: A;
...
setAdapter(adapter: A) {
...
}
}
export abstract class Adapter {
abstract id(pos: number): number;
}
export default ListView;
// PinnedListView.ts
import ListView, {Adapter} from "./ListView";
class PinnedListView<A extends PinnedListViewAdapter> extends ListView<A> {
...
}
export abstract class PinnedListViewAdapter extends Adapter {
abstract shouldPin(pos: number): boolean;
}
export default PinnedListView;
// App.ts
// let's say you use path alias
import PinnedListView, {PinnedListViewAdapter} from "views/PinnedListView";
class MyAdapter extends PinnedListViewAdapter {
// your implementation
}
const pinnedListView = new PinnedListView();
const myAdapter = new MyAdapter();
pinnedListView.setAdapter(myAdapter);
After
// ListView.ts
class ListView<A extends ListView.Adapter> {
protected adapter?: A;
...
setAdapter(adapter: A) {
...
}
}
namespace ListView {
export abstract class Adapter {
abstract id(pos: number): number;
}
}
export default ListView;
// PinnedListView.ts
import ListView from "./ListView";
class PinnedListView<A extends PinnedListView.Adapter> extends ListView<A> {
...
}
namespace PinnedListView {
export abstract class Adapter extends ListView.Adapter {
abstract shouldPin(pos: number): boolean;
}
}
export default PinnedListView;
// App.ts
// let's say you use path alias
import PinnedListView from "views/PinnedListView";
class MyAdapter extends PinnedListView.Adapter {
// your implementation
}
const pinnedListView = new PinnedListView();
const myAdapter = new MyAdapter();
pinnedListView.setAdapter(myAdapter);
Visualize a situation where there are multiple classes that need to be named Adapter
, regardless of their function. This structured approach helps in keeping
- your app organized by avoiding naming conflicts and having to prefix consuming class names before
Adapter
- readers understand clearly the purpose of each
Adapter
class without confusion