[英]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.