Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail From: Cholo Lennon Newsgroups: comp.lang.java.programmer Subject: Re: Call by Result Date: Thu, 16 Jun 2011 11:30:22 -0300 Organization: Aioe.org NNTP Server Lines: 77 Message-ID: References: NNTP-Posting-Host: FX2JlnghQKkO0dWgQsflYQ.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110414 Lightning/1.0b2 Thunderbird/3.1.10 X-Notice: Filtered by postfilter v. 0.8.2 Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:5334 On 10/06/2011 03:03, Gene Wirchenko wrote: > Dear Java'ers: > > I wish to call by result with a method. Is it possible? If not, > can it be easily simulated in an unnasty way? > > 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. > > Sincerely, > > Gene Wirchenko IMHO using exceptions is not always the best answer to this problem (as other suggested). How about using a simple generic class? (of course, it could be corrected or improved. A similar idea could be found in other languages (such as C++ (boost)): class Optional { private T value; private boolean valid; public Optional(T value) { setValue(value); } public Optional() { this.valid = false; } public boolean isValid() { return this.valid; } public T getValue() { return this.value; } public void setValue(T value) { this.value = value; // TODO Shall I set to true when value is null? this.valid = true; } public void invalidate() { this.value = null; this.valid = false; } } // Test Optional result = GetString(); if (!result.isValid()) { // too bad ... } else { System.out.print(result.getValue()); ... } Regards -- Cholo Lennon Bs.As. ARG