I was working on this problem, where I am constructing a Object Oriented structure of file system where you can have Directories and Files. The Directories could have sub Directories and files.
I have the following layout and I am looking for feedback on improvements or if my approach is wrong.
My OOP design has three different classes Root, Directory and Files
class Root {
constructor(name, size, writable, parent){
this.name = name;
this.size = size;
this.writable = writable;
this.parent = parent;
}
getName(){
return this.name;
};
setName(val){
this.name = val;
}
}
class Directory extends Root{
constructor(name, size, writable, parent){
super(name, size, writable, parent);
this.children = [];
}
addContent(obj){
this.children.push(obj);
}
getContent(){
return this.children;
}
}
class File extends Root{
constructor(name, size, writable, parent){
super(name, size, writable, parent);
}
getSize(){
return this.size;
}
}
let root = new Root('head', 100, true);
let directory1 = new Directory('sample', 40, true, root);
let file1 = new File('test', 12, true, directory1);
let file2 = new File('test2', 14, true, directory1);
let subDirectory = new Directory('sample2', 40, true, directory1);
directory1.addContent(file1);
directory1.addContent(file2);
directory1.addContent(subDirectory);
console.log(directory1.getContent());
-
\$\begingroup\$ What kind of data will be most commonly stored with this? \$\endgroup\$Adam– Adam2018年08月28日 12:28:16 +00:00Commented Aug 28, 2018 at 12:28
1 Answer 1
I'd say Root
is a misnomer here, since at first glance I imagined it to represent the filesystem root (i.e. the /
directory), not the root of your class tree. Moreover, instead of deriving File
and Directory
from a common (abstract) ancestor, I'd derive Directory
from File
instead, since that's what most real filesystems do anyway, i.e. they treat directories as special files.
size
should not be a writable property; the File
object should always calculate it based on its content. This can ensure there's no discrepancy between the stored size and the actual size of the file's content. Also, why doesn't Directory
have a getSize()
method? It could just call getSize()
on all its children and add up the results.
You have a writable
attribute on your objects, but you don't seem to be using it, e.g. in setName()
you just replace the name of the object without checking if it's writable. Similarly, you have a parent
argument in the constructor, but you don't use it; I'd expect the File
to call addContent()
on its parent automatically if the parent is specified in the constructor.
As for further features, I'd recommend making your Directory
class iterable (so it can be used in for
loops), as well as implementing the most common collection methods, such as forEach
, has
, length
(i.e. the number of files in the directory), etc., instead of just exposing the array of children.