[英]Splitting long text into multiple lines of code, best way to do it?
假設您想向游戲顯示歡迎消息,但是要求將源代碼中的行的最大長度保持為80個字符的寬度。 在游戲中,線條的長度並不重要。 歡迎消息的示例為:
private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me how to create a long messages like this in a read-able fashion. Imagine there is a limit of 80 characters per line for a programmer to see. How to fix this efficiently? This is one large line in my IDEA. ");
}
這行太長了,以致於每行代碼不能超過80個字符,如滾動條所示。 我以前學會了簡單地做這樣的事情:
private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me" +
" how to create a long messages like this in a read-able " +
"fashion. Imagine there is a limit of 80 characters per line for" +
" a programmer to see. How to fix this efficiently? This is one " +
"large line in my IDEA. ");
}
但是我發現這個解決方案很難看,這創建了一個令人討厭的依賴項。 如果我添加"Welcome to the game. This message should learn me"
,我只需要更改一個單詞即可更改所有其他行,因此一行之后的所有行都取決於它。
我也可以想象會有一些懲罰,僅僅是因為它以這種方式可讀。 這讓我想知道:
想象這是一個真實的游戲,您是否會制作一個txt文本文件並使用StringBuffer等將其導入以在屏幕上顯示呢? 否則您將如何顯示更長的短信?
編譯器是否直接附加所有行,因為它們本身不依賴其他變量,還是在運行時發生? (恐怕它將調用連接運算符函數('+')4次)
編譯器將連接字符串。 沒有運行時開銷。
在此示例中,具有.append()的StringBuffer會更有效嗎,因為它不會創建5個字符串,而是將其追加到StringBuilder對象?
沒有。
演示:
class Test {
public static String test = "a" + "b" + "c";
}
命令
javac Test.java && javap -c -v Test
產生以下輸出
[...]
Constant pool:
#1 = Methodref #5.#15 // java/lang/Object."<init>":()V
#2 = String #16 // abc
#3 = Fieldref #4.#17 // Test.test:Ljava/lang/String;
[...]
Code:
stack=1, locals=0, args_size=0
0: ldc #2 // String abc
2: putstatic #3 // Field test:Ljava/lang/String;
5: return
[...]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.