Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!feeder.erje.net!newsfeed.utanet.at!newscore.univie.ac.at!aconews-feed.univie.ac.at!aconews.univie.ac.at!not-for-mail Newsgroups: comp.lang.java.programmer From: Andreas Leitgeb Subject: Re: Call by Result References: Reply-To: avl@logic.at User-Agent: slrn/pre0.9.9-111 (Linux) Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: Date: 10 Jun 2011 07:33:12 GMT Lines: 50 NNTP-Posting-Host: gamma.logic.tuwien.ac.at X-Trace: 1307691192 tunews.univie.ac.at 73248 128.130.175.3 X-Complaints-To: abuse@tuwien.ac.at Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:5169 Gene Wirchenko wrote: > I am writing a simple preprocessor. I have a few spots where a > string needs to be parsed. I want to call something like this: > String ReturnString=""; > boolean DidItWork=GetString(ReturnString); > if (!DidItWork) > // too bad > It is not acceptable to have a special String value mean failure. I > want the method to be able to return any potential string. There's three basic ways to do it: 1) Return null to indicate failure. (Unless you consider null to also be a valid String-value - That typically depends on the context and I didn't read your wording as being explicit on that.) String retVal = getString(); if (retVal == null) { /* too bad */ } This won't work, though, if you need to return a String both on failure and success. 2) instead of the string, pass a mutable container of a string: String[] stringContainer = new String[1]; boolean didItWork = getString(stringContainer); if (didItWork) { /* stringContainer[0] has the string */ } and within GetString: public boolean getString(String[] strCont) { strCont[0] = "blah"; return true; } 3) encode the String: e.g.: prepend a particular text to "success"- strings, and a different text to "failure"-strings: public String getString(String[] strCont) { if (ok()) { return "+" + okMessage; } else { return "-" + errMessage; } } use: String retVal = getString(); if (retVal == null || retVal.length() == 0) { /* internal error */ } else if ( retVal[0] == '+' ) { // All's well that ends well: retVal.subString(1) } else if ( retVal[0] == '-' ) { // Uh-Oh!: retVal.subString(1) } else { /* internal error */ } PS: Surely, someone will soon point out coding-conventions about upper-/lower-casing different kinds of identifiers. I dare to agree in advance. (Btw., I changed to conformant casing in my examples.)