我正在写一个小型图书馆。
public class MyClass {
public static String doSomethingWithString(final String s) {
new MyClass().doSomething(s);
}
public String doSomething(final String s) {
return null;
}
}
或者我可以这样做。
public class MyClass {
public static String doSomethingWithString(final String s) {
return null;
}
public String doSomething(final String s) {
return doSomethingWithString(s);
}
}
哪种风格更受欢迎?它们相同吗?
更新
感谢您的评论和回答。
这里有两个类。
public class IdEncoder {
private static String block(final long decoded) {
final StringBuilder builder = new StringBuilder(Long.toString(decoded));
builder.append(Integer.toString(
ThreadLocalRandom.current().nextInt(9) + 1)); // 1-9
builder.append(Integer.toString(
ThreadLocalRandom.current().nextInt(9) + 1)); // 1-9
builder.reverse();
return Long.toString(
Long.parseLong(builder.toString()), Character.MAX_RADIX);
}
public static String encodeLong(final long decoded) {
return block(decoded >>> 0x20) + "-" + block(decoded & 0xFFFFFFFFL);
}
public String encode(final long decoded) {
return encodeLong(decoded);
}
}
还有另一种风格。
public class IdDecoder {
public static long decodeLong(final String encoded) {
return new IdDecoder().decode(encoded);
}
public long decode(final String encoded) {
final int index = encoded.indexOf('-');
if (index == -1) {
throw new IllegalArgumentException("wrong encoded: " + encoded);
}
return (block(encoded.substring(0, index)) << 32)
| (block(encoded.substring(index + 1)));
}
private long block(final String encoded) {
final StringBuilder builder = new StringBuilder(
Long.toString(Long.parseLong(encoded, Character.MAX_RADIX)));
builder.reverse();
builder.deleteCharAt(builder.length() - 1);
builder.deleteCharAt(builder.length() - 1);
return Long.parseLong(builder.toString());
}
}
最佳答案
如果您只是在这两个选项之间进行选择,请选择第二个。
原因是第一个要求你在堆上分配一个新的虚拟对象只是为了调用一个方法。如果确实没有其他区别,就不要浪费时间和空间,直接从类中调用静态方法即可。
第二种更类似于静态效用函数,这是一种很好的编码习惯。
关于java - 静态方法或实例方法中的实际代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16848496/