3 ms·
I don't consider this style of pattern matching to be semantically different than ifs or switch cases. There's literally no "if" but they are fundamentally simi
by hellofunk 8y ago
I don't consider this style of pattern matching to be semantically different than ifs or switch cases. There's literally no "if" but they are fundamentally similar to having a single function with a switch/if inside for the "doing something".
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.
- dep_b 8y ago`switch boolValue` insists you do something with the false part, `if boolValue` does not. This is just looking at it from the most atomic level possible. If you have a group of booleans you get pretty complex lines of code. Switching on a tuple of three boolean where you can have cases like "if the first two are true ignore the third one" is super powerful. It becomes even better if you return an enum that indicates what it really means. Like CONNECTED, CONNECTING, DISCONNECTING, DISCONNECTED. Now every possible meaningful value of those three booleans has a word attached to it. 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.
- hellofunk 8y agoWhose comment are you responding to? It seems you agree with my comment about pattern matching and switch cases.
- dep_b 8y agoI must've misunderstood your comment. I thought you were saying these pattern matching rules were basically souped up if's. Elixir has pattern matching on function level but it's also heavily ingrained in the whole philosophy. It's quite the antithesis to Java.
- your-nanny 8y agoThe don't care _ is doing a lot of work keeping that code less verbose.