开发者

Handling Large String Constants in Java

开发者 https://www.devze.com 2023-02-06 22:40 出处:网络
What is the best way to handle large string constants in Java? Imagine that I have a test fixture for SOAP and I want to send the following string:

What is the best way to handle large string constants in Java?

Imagine that I have a test fixture for SOAP and I want to send the following string:

<?xml version="1.开发者_如何学JAVA0" encoding="utf-8"?>
<soap:Envelope 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
       <QuoteRequest xmlns="https://www.bcponline.co.uk">
            <header>
                <SourceCode>BN325</SourceCode>
                <MessageSource>B2B3</MessageSource>
                <Profile>B08A</Profile>
                <Password>AP3U86V</Password>
                <OperatorID>flightline</OperatorID>
                <ShowWebOptions>0</ShowWebOptions>
            </header>
            <serviceSelection>
                <ServiceProviderCode></ServiceProviderCode>
                <ProductCode>CarParking</ProductCode>
                <IATACode>lgw</IATACode>
            </serviceSelection>
            <quoteDetails>
                <DepartureDate>21-Jun-2005</DepartureDate>
                <DepartureTime>07:00</DepartureTime>
                <ReturnDate>28-Jun-2005</ReturnDate>
                <ReturnTime>07:00</ReturnTime>
                <QuoteReference></QuoteReference>
                <NoPax>1</NoPax>
            </quoteDetails>
            <sPostCode></sPostCode>
        </QuoteRequest>
    </soap:Body>
</soap:Envelope>

I'd rather not put quotes and pluses around every line. If I put it in a file it's extra code and it would be somewhat hard to put several strings in the same file. XML has problems escaping text (I have to use CDATA ugliness). Is there an easier way?


If the strings are unrelated, you could put them in separate files even if it's a lot of files (what is the problem with that?).

If you insist on one file, you could come up with a unique delimiter, but you would be paying a price when attempting to randomly access a specific entry.

Data files should almost always be externalized (likely in a separate directory) and read when needed, rather than hardcoded into the code. It's cleaner, reduces code size, reduces need for compilation, and allows you to use the same data file for multiple test. Most test fixtures as well as build and integration tools support external files.

Or, you could write code or a builder that builds SOAP from arguments, making this all a lot more concise (if you're willing to pay the runtime cost). (Correction: I see you changed your sample, this would be nasty to auto-generate).


What about using a StringBuilder? You can always use StringBuilder.toString() to get the String...

0

精彩评论

暂无评论...
验证码 换一张
取 消