patterncsharpMinor
Marking class with no abstract methods as an abstract
Viewed 0 times
abstractmarkingwithmethodsclass
Problem
Consider an interface:
Class definitions:
-
-
-
(1) is already marked as an abstract so it cannot be instantiated. (2) and (3) are fully implemented though they should not be instantiated, rather they should be derived by other class specifying `
public interface IWindowOperations
{
// Some operation methods.
}Class definitions:
-
public abstract class BaseWindow : IWindowOperations
{
// partially implemented class.
}-
public class TraditionalWindow : BaseWindow
{
// Fully implemented class.
}-
public class ModernWindow : BaseWindow
{
// Fully implemented class.
}(1) is already marked as an abstract so it cannot be instantiated. (2) and (3) are fully implemented though they should not be instantiated, rather they should be derived by other class specifying `
so the application framework can register them.
e.g.
public class SliderWindow : ModernWindow
{
// In general case this is just an empty class
// unless special handling is needed.
}
In this case is it right to mark (2) and (3) as an abstract`? Those are just template defining some concrete functionality but also allows derived classes to override if required.Solution
It depends on your design entirely. If classes (2) and (3) can not operate on their own, should not be instanciated and are there to serve as base classes only, then you are justified to make them abstract, and i think you should.
Also, you should probably reflect your intent in class names by adding
Edit Objects with protected constructor can still be instanciated. For example, you can create them from some method in derived class. It is not a realistic use-case in most cases, but you should not leave such holes nonetheless. If you want to forbid instanciation completely, the only way to do it is to mark the class abstract.
Also, you should probably reflect your intent in class names by adding
Base suffix to (2) and (3) (or prefix, but i think it is less common).Edit Objects with protected constructor can still be instanciated. For example, you can create them from some method in derived class. It is not a realistic use-case in most cases, but you should not leave such holes nonetheless. If you want to forbid instanciation completely, the only way to do it is to mark the class abstract.
Context
StackExchange Code Review Q#33432, answer score: 5
Revisions (0)
No revisions yet.