C
C#2y ago
barcode

❔ Question about abstraction

public interface ILocatable
{
public double Longitude { get; set; }
public double Latitude { get; set; }

public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

double dLat = (latitude - Latitude) * Math.PI / 180;
double dLon = (longitude - Longitude) * Math.PI / 180;
double lat1 = Latitude * Math.PI / 180;
double lat2 = latitude * Math.PI / 180;

double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
}
public interface ILocatable
{
public double Longitude { get; set; }
public double Latitude { get; set; }

public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

double dLat = (latitude - Latitude) * Math.PI / 180;
double dLon = (longitude - Longitude) * Math.PI / 180;
double lat1 = Latitude * Math.PI / 180;
double lat2 = latitude * Math.PI / 180;

double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
}
Is this a correct usage of interfaces? then having
public class Center : BaseEntity, ILocatable
public class Center : BaseEntity, ILocatable
implement an abstract class an and interface
10 Replies
barcode
barcodeOP2y ago
or should the method not be implemented and then implement in class extending it?
Mideks
Mideks2y ago
Interface with method implementations? 🤯
cap5lut
cap5lut2y ago
interfaces describe contracts -> behavior of something, so it fits. base classes and alike are implementation details, which seems to fit here as well. with this little piece of code w/o further context it seems fine iirc default interface method implementations were added in c# 8.0
Mideks
Mideks2y ago
I think this is an anti-pattern for most use cases.
cap5lut
cap5lut2y ago
i think its a totally fitting use case here
barcode
barcodeOP2y ago
the other option is copying the code in 5 places
cap5lut
cap5lut2y ago
as long as the actual ILocatable type isnt volumetric that method is accurate
Sossenbinder
Sossenbinder2y ago
I usually view default interface implementations as "mixins", I don't use them a lot, but there are good use cases since the alternative is either duplication or often using an abstract class which in turn causes issues if your class already inherits from another one
cap5lut
cap5lut2y ago
tbh i think this is a really good example for the usage of default interface implementations 😂
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