✅ Abstract Class vs Interface
I am building a WPF financial application from some VBA code I'm rewriting in C#, someone else wrote the VBA and so far I've managed to translate 40% of the functionality.
I have the following structure:
public class I03 -> reads + filters out invalid financial transactions from a text file
interface ILineItem -> defines properties for the following classes:
public class HeaderData
public class LineItem
HeaderData and LineItem will be used in a factory design pattern, as each valid transactional data should be an instance of either of the two classes.
My question is, should I have used an abstract class to derive HeaderData and LineItem from?
I initially wrote the classes like this to make unit tests for each property but now I've gotten to the part where I have to think deeper about how the code will be implemented.
When should we use Interfaces and when should we use an abstract class? In the latest .net sdk it seems like interfaces became more like an abstract class and I don't see the big difference, what am I missing?
6 Replies
Abstract Classes are used to share behaviours and states. Methods in abstract classes always have a default implement.
Interfaces are just include declarations without implementation. Classes who inherit interface should implement all members by themselves.
And also interface can do multiple inheritance, but abstract class cannot.
default implementations in interfaces dont work like abstract classes
theyre only invoked from the interface directly
general rule of thumb is if you can use an interface then do that
i rarely use abstract classes
theyre especially rare in modern software architectures
where we much prefer composition over inheritance
Abstract classes don’t have always an default implementation
well no but if all youre using them for is as a contract then you should be using an interface
Well interfaces are compiled as abstract classes in IL :kekw:
jokes aside, i would preferer less inheritance possible and use Interfaces as much as possible
Hi, just properties and one method which is dependent on the class it belongs to. 90% of the properties are the same.
Ended up creating an abstract class and I’ll have a factory class to decide which class should be instantiated at runtime
The fun part will be figuring out how to make the GUI interact with the implementation once the backend is complete