Which to use , abstract class or interface in F#?

倖福魔咒の 提交于 2019-12-24 00:56:58

问题


Been grokking F# coming from a C# background.

In C# there is a clear difference in deciding when to use interfaces and when to use abstract classes. In F# I see the two blurring almost into one. I understand under the hood that the same is being done in F# as c# as far as the CLR is concerned, but what is the "best practise" when programming in F# to use?

Should I avoid class inheritance altogether?


回答1:


I think that interfaces tend to be used much more frequently than abstract classes (compared to object-oriented languages like C#).

In many cases, you don't need any of the two, because you can just write higher-order function (that takes a function as an argument, instead of taking an interface as an argument). However, sometimes you may have two functions that are always used together - in that case, you can group two functions into an interface:

// Instead of using higher-order function
val foo : (int -> string) -> (string -> int) -> ...

// ..we can define an interface
type TwoWayConversion = 
  abstract ToString : int -> string
  abstract FromString : string -> int

val foo : TwoWayConversion -> ...

I think that this is quite useful F# programming pattern that uses interfaces in a perfectly functional style.

On the other hand, I would use abstract classes only when writing object-oriented code that is supposed to be used from C# (e.g. C# code implementing your F# abstract class) - because that's a natural extensibility point from the C# point of view. However, I think that idiomatic F# code uses different extensibility points than C# (e.g. taking function/interface as an argument), so you don't really need abstract classes.




回答2:


Well, if you're debating between abstract classes and interfaces, I think your reasons for one or the other would be the same as in C#. Maybe you should consider using functions, functional data types and modules as units of abstraction though. If you need to write an F# library to be used in C#, then you'll probably want to use interfaces etc for your exported types.



来源:https://stackoverflow.com/questions/3109027/which-to-use-abstract-class-or-interface-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!