Created
September 21, 2011 14:05
-
-
Save zah/1232112 to your computer and use it in GitHub Desktop.
Forwarding references
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type Connection = object | |
| userName: string | |
| messageHistory: list[string] | |
| type ConnectionManager = object | |
| networkConnections: map[string, Connection] | |
| const | |
| NULL_CONNECTION : Connection = ... | |
| # The Connection values could not be really copied. Maybe, I should use just var here? | |
| proc getConnection(m: var ConnectionManager, host: string): Connection = | |
| return m.networkConnections[host] | |
| # If I use the NullObject pattern, returning var type becomes harder? | |
| proc getUserConnection(m: var ConnectionManager, user: string): Connection = | |
| for host, con in items(networkConnections) | |
| if con.userName == user | |
| return con | |
| return NULL_CONNECTION | |
| var gConnectionManager : ConnectionManager | |
| # Let's assume that the list of messages is expensive to copy and we don't want to do it | |
| proc getUserMessages(user: string) : list[string] = | |
| gConnectionManager.getUserConnection(user).messageHistory | |
| # Multiple bodies of the function are compiled for the two usage patterns? | |
| let messages1 = getUserMessages("Araq") | |
| # just passes the reference | |
| var messages2 = getUserMessages("Araq") | |
| # creates/initializes a copy | |
| # or a copy is created by the returned reference? | |
| proc getUserName(host: string) : string = | |
| gConnectionManager.getConnection(host).nameName | |
| proc getMostActiveUser(): string = | |
| var mostActiveHost = "foo" & "bar" & baz # this a temporary created local string | |
| return getUserName(mostActiveHost) | |
| # This can not be safely optimized with the crude rules | |
| # mostActiveHost in the body of getMostActiveUser is a temporary varialbe | |
| # passed to a function that could return it (so, reference could not be forwarded) | |
| let user = getMostActiveUser() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment