by algorithmsRcool · 7y ago · 0 comments
Safer threading with immutability
Safer programming with null-safety
Safer logic with precise domain modeling
The precise domain modeling is the real paradigm shift.
The whole point of static typing is to inform the compiler about your intent so that it can provide guarantees about correctness. F# makes it easy to define lots of small types that precisely model state so that you can give more responsibility to the compiler to verify your program.
I cannot overstate how important this is to maintaining correct software overtime. If you guard your touches with non F# code, you need far fewer unit tests and probably even less runtime checks because you already know if the types are right, so is the logic. And when you need to write unit tests, the functional style makes your tests very easy to write.
I have personally struggled with domain complexity in C# that i was able to model precisely in F# and have it work perfectly on the first try.
There's nothing superior about these type systems, they're simply two of the most static and rigid systems in circulation right now.
Try writing C, Lisp and Forth until it clicks. Then we can sit down and have an informed discussion about missing features.
With Haskell, you need to put in a lot more up front thought. Then stuff doesn't compile and you spend ages working out why.. You can go for hours without having anything running. The cause of the errors can be quite abstract and obtuse and may seem like it is nothing to do with the actual problem you are trying to solve.
Different people just suit different styles.
The way I write php isn't that different from how I write haskell, especially with phan running on save. Php actually requires a bit more thinking in advance because I can't refactor it quite as easily.
What could also be taken into account is that I used to be up there preaching the static typing gospel. And then I gradually got fed up with the ceremonies, since they didn't pull their own weight and couldn't keep up.
It's all compromises. The claim is that in return for following rigid rules, they guarantee this and that. Sort of the same deal the state has pushed down our throats since forever. And for a while it seems reasonable, until you pull hard enough to notice the chains around your ankles.
I really do think that an ML-style type system is the better way to do domain modeling. The compiler support you get in F#, such as ensuring that your match expressions are complete, are nice. But what really makes me enjoy working that way is that (the non-OO bits of) F#'s type system makes it very easy to create domain models whose intent and inner workings are just obvious.
You're right, it's not correct to cast the differences as "missing features" - it's just different ways of doing things. And each has its own advantages and disadvantages. F#'s set of tradeoffs is just the one that most suits my tastes when I'm building LOB applications.
This might sound like an unwanted restriction, but 9 times out of 10, having mutually recursive types is signs of a code smell. You can almost always model your problem better with a slight indirection through an interface or function, it helps avoid the need for mutation, and makes testing simpler.
I've even found that apart from enforcing better design, it can also trigger it. As an illustration, I've had a function 'f' in module 'C' that I decided made more sense in module 'A'. When I moved the function however, module 'A' would no longer compile because 'f' was dependent on a module 'B'. No problem I thought, I'll just move module 'A' below module 'B'. Whoops, now module 'B' won't compile; I didn't realize it was dependent on module 'A'. If I resist the urge to just revert everything and return the function 'f' to module 'C', and I investigate "why does 'f' feel like it belongs in module 'A' and yet placing it there introduces circularity...", often I'll discover a beneficial refactoring that I probably would not have thought of otherwise.
It might be my least favorite thing about F# (Except that Option<T> is a class not a struct)
There is ValueOption<T> now.
It's a mouthful and you'll still have to deal with all the standard library, or other third-party libraries, which produces and consumes Option<T>, but you can address that with some aliases and conversion operators if you want to go all-in:
type 't voption = ValueOption<'t>
type VOption<'t> = ValueOption<'t>
let inline (!) opt =
if System.Object.ReferenceEquals(opt, null) then ValueNone else
match opt with None -> ValueNone | Some x -> ValueSome x
let inline (?) vopt =
match vopt with ValueNone -> None | ValueSome x -> Some x;;
// usage
let x = !(List.tryFind (fun x -> x = 0) [1]);;
// [<Struct>] val x : int voption = ValueNoneIf you're willing to provide a (simplified) example I would be very interested.
Although personally I'd rather have the different states encapsulated in separate classes than a single type that encapsulates all possible states and enforces them through the constructor.
Yes! That is exactly right, F# give you the tools to express your actual model with little/no ambiguity.
public class Order {
final Optional<DeliveryDetails> delivery;
public Order(Optional<DeliveryDetails> delivery) {
this.delivery = delivery;
}
}
public class DeliveryDetails {
final long deliveryTimeMs;
...
public DeliveryDetails (long deliveryTimeMs,...) {
this.deliveryTimeMs = deliveryTimeMs;
...
}
}
My IDE writes most of these lines for me. I believe C# will have similar or more succinct constrcuts. type OrderId = OrderId of string
type DeliveryTime = DeliveryTime of long
type DeliveryDetails = { deliveryTime: DeliveryTime...}
type Order = { id: OrderId ...}
type DeliveredOrder = { id: OrderId, deliveryDetails: DeliveryDetails...}
Probably it is even better to define delivery time using the unit of measures and specifying it as ms.
What is the difference in this way?
That an order cannot ever have DeliveryDetails, while a DeliveredOrder must have DeliveryDetails.
As a bonus you can’t just pass any string as an order id (for example a description) but you need to pass an actual order id. the same is true for the deliveryTime with the adddd advantage that you won’t be able to perform operations on it with a different unit of measure.
In java or c# you would kill yourself if you try to do something similar and moreover you won’t have all the constraints specified here and the immutability automatically enforced.I was writing a little program to help glue some things together in our build/release pipeline. This tool would be deployed to the build server and get invoked by the build agent. (This could have been a script, but the complexity got to be too much to keep organized)
The tool had two halfs:
- The frontend whose job was to gather up all the 'input' from CommandLine and Env vars, do some parsing, then spit out proper types/objects.
- The backend that would interpret this data and make decisions, make some API calls and maybe copy some files.
Because of the way our our software is built, we have 5 or 6 different 'flavors' of our app that needed special treatment during build. The complexity of branching on if it was a build step or a release step, the different flavors of our app and the need to deal with input data that may or may not be there got the best of me and I spent weeks making tweaks to deal with NREs at runtime because i hadn't handled some weird case.
So i trashed the tool and rebuild the front end in F#. I spent a little time making a very accurate type representation of the data model. Including defining a lot of stuff as optional and introducing a lot of discriminated unions to represent possible branches. Then i essentially just filled in the blanks (match cases) and fixed the compile errors until every case was covered and I was done. No bugs.
You see the big, big win of F# is the default path doesn't let your cheat yourself.
You MUST handle every switch/match case.
You MUST fully construct your records.
If your function may fail, you MUST use Option to express None/Null
And you MUST handle every option type as potentially None and write handling logic
When you define your data model, just be on honest about what data needs to be where and the compiler will keep you on the straight and narrow.
There's no setup required, just start typing some F# code into the online playground and see it run immediately.
I like this one: https://fsharpforfunandprofit.com/posts/designing-for-correc...
https://fsharpforfunandprofit.com/posts/designing-for-correc...
Just a shame that the university exam I took this summer was to implement binary trees and a parser...