Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(Note: This should all hopefully work, but I cannot test it at this time. Please give it your own sanity check.)</p> <p>You could write</p> <pre><code>(defn download-web-page "Downloads the webpage at the given url and returns its contents." ([^String url] (download-web-page url nil nil)) ([^String url ^String user ^String password] (with-open [client (doto (WebClient.) (-&gt; (.set_Credentials (NetworkCredential. user password "")) (-&gt;&gt; (when user))))] (.DownloadString client url)))) </code></pre> <p>That seems pretty convoluted to me, though. Another approach:</p> <pre><code>(defn download-web-page "Downloads the webpage at the given url and returns its contents." ([^String url] (download-web-page url nil nil)) ([^String url ^String user ^String password] (with-open [client (let [c (WebClient.)] (when user (.set_Credentials (NetworkCredential. user password ""))) c)] (.DownloadString client url)))) </code></pre> <p>The convoluted <code>-&gt;</code> / <code>-&gt;&gt;</code> pattern from the first version could be abstracted away with a macro:</p> <pre><code>(defmacro doto-guard [guard action] `(-&gt; ~action ~guard)) </code></pre> <p>Then you could write</p> <pre><code>(doto (WebClient.) (doto-guard (when user) (.setCredentials ...))) </code></pre> <p>This has the nice property that you could use it multiple times in a single <code>doto</code> form while mixing in regular <code>doto</code> clauses. Well, it's nice if this sort of thing comes up more often in your code, anyway. Otherwise the <code>let</code>-based version should do fine.</p> <p>(If that pattern comes up <em>really</em> often for you, the macro could be made more flexible... It's also tempting to make it slightly <em>less</em> flexible, but prettier, say by replacing <code>~guard</code> with <code>(when ~guard)</code>, so that at point of use one would write <code>(doto-guard user (.setCredentials ...))</code>. Any deep reason to choose a particular version would have to come from a broader context, however.)</p> <p>The split into two function bodies is just a matter of style -- I prefer not to write the <code>nil nil</code> when no credentials are actually provided.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload