I have done some search on this website to avoid duplication, however most of the questions were about an abstract comparison between interface and abstract class.
My question is more to my specific situation especially my colleague and I we don't agree about the same approach.
I have 3 classes
We use the composite pattern to get all folders and their permissions per user/group
The class Node
, should it be interface or Abstract class?
Folder
and File
inherit from Node.
In my opinion i think Node
should be an abstract because File
should not have all methods that Folder
has for example AddFolder(Node node)
My colleague said that it's better to use interface for better coding.
Edit: I rewrote my Node as follow:
public abstract class Node
{
public string Name { get; set; }
public string FullName { get; set; }
public Node Parent { get; set; }
public List<PermissionEntry> Permissions { get; set; }
protected Node(string fullName)
{
FullName = fullName;
Permissions = new List<PermissionEntry>();
}
public void AssignPermission()
{
// some Codes
}
}
There is no right answer here. It really boils down to this question
"Does Node
have any implementation that is common to File
and Folder
?"
If the answer is yes, then need an Abstract class, optionally with an Interface which describes its behaviour
If the Answer is no, then you could make it an Interface, optionally with an Abstract base implementation.
So you see - its basically the same either way.
Besides, there is nothing stopping Folder
adding additional methods not defined on Node
which File
would not share.
eg,
public interface INode
{
void SomethingCommon();
}
public File: INode
{
public void SomethingCommon(){...} // I must implement this
}
public Folder : INode
{
public void SomethingCommon(){...} // I must implement this
public void AddFolder(string name)
{
// File doesnt need this method, its not on the interface!
}
}
Your reasoning for rejecting the interface seems off. Why would File
have a method AddFolder
if Node
were an abstract class but not if it were an interface?
You normally choose to create an abstract class if you have common functionality that all children share. In this case, this common functionality will be implemented by the abstract base class so it doesn't have to be implemented in all children.
In many cases, you even have both:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With