by pmontra · 8y ago · 0 comments
fn box(status=checked)
do domething
fn box(status=*)
do something else
My Elixir projects have 0 to 10 ifs and they do solve real problems. I use plenty of ifs in other languages but I follow some of the advices of the post.Most pattern matching in languages is basically souped-up switch statements much of the time. Note that pattern matching is not one of the solutions mentioned by the author.
A Swift-enum allows you to have methods inside enums:
enum ConnectionStatus {
case connected
case connecting
case disconnecting
case disconnected
func `for`(isConnected: Bool, isConnecting: Bool, isDisconnecting: Bool) -> ConnectionStatus {
switch (isConnected, isConnecting, isDisconnecting) {
case (true, _, false): return .connected
case (false, true, _): return .connecting
case (true, _, false): return .disconnecting
case (false, false, _): return .disconnected
}
}
Then somewhere inside your code: public func connect() {
switch ConnectionStatus.for(isConnected: self.isConnected, isConnecting: self.isConnecting, isDisconnecting: self.isDisconnecting {
case .connected, .connecting: return // We're already good
case .disconnecting: reconnectWhenDisconnected()
case .disconnected: startConnection()
}
The amount of if's that have to be juggled to do the same and the resulting code that is hard to parse when you're maintaining it definitely is more problematic.Same goes for `Optional<T>` in an argument position, though https://github.com/quchen/articles/blob/master/algebraic-bli...