C
C#2y ago
tornixdev

❔ abstract class vs interface

public interface IFoo
{
protected static string GetFormattedTime() => DateTime.Now.ToString("HH:mm");

public void Foo();
public void Bar();
}

public class Baz : IFoo
{
public void Foo() { ... }
public void Bar() => Console.Writeline(IFoo.GetFormattedTime())
}
public interface IFoo
{
protected static string GetFormattedTime() => DateTime.Now.ToString("HH:mm");

public void Foo();
public void Bar();
}

public class Baz : IFoo
{
public void Foo() { ... }
public void Bar() => Console.Writeline(IFoo.GetFormattedTime())
}
would an abstract class be appropriate here? or would this be just fine?
9 Replies
Thinker
Thinker2y ago
You have a protected static member in the interface so you clearly don't want an interface. You should ideally remove GetFormattedTime from the interface (and for instance move in into a static class), but you can keep the rest.
tornixdev
tornixdevOP2y ago
why a static class though?
Thinker
Thinker2y ago
Because you have a static method which doesn't depend on the interface
tornixdev
tornixdevOP2y ago
what if, hypothetically, I don't want to expose the methods to other classes?
Thinker
Thinker2y ago
Why is that a concern? The method above doesn't do anything very special, it could just be an extension method/utility
tornixdev
tornixdevOP2y ago
not really a concern, but let's say what if that method returned "important" information that should be kept within' that entire interface-class relationship or what if the method is something that no other external class would ever use?
Thinker
Thinker2y ago
Then use an abstract base class An interface should not contain any kind of implementation details, all they should do is specify what a type has to implement.
Djinn
Djinn2y ago
i agree with Thinker, interface even if you can write default methods, statics and so on they should just have contract to some implementation instead of implementing them this protected static could be in Baz class as protected/private or as Thinker said, abstract class
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server