开发者

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

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜