0

I am trying to understand if it is useful to use String during programming, there is general notion in our group that using String is bad practice and enum is way to go but I am not able to find enough reasoning to give in my vote against String and would appreciate any thoughts and example on the issue?

Update:

I should re-phrase my question to word like under what situation usage of String is evil and what alternative dataType you should be using for the same.

Rachel
  • 100,387
  • 116
  • 269
  • 365
  • 3
    Perhaps some more context would be useful... ? Is this really *in general* or specifically with respect to constants or input or... ? – Richard JP Le Guen Apr 18 '12 at 17:43
  • This is in general while defining variables for your bean. – Rachel Apr 18 '12 at 17:44
  • 2
    Not enough context. A simple question of `String` vs `enum` makes no sense. How do you represent a name with an enum for example? – Tudor Apr 18 '12 at 17:46
  • enum is usually better for defining the state of an object as it constrains the types allowed. – Hovercraft Full Of Eels Apr 18 '12 at 17:46
  • What are some of the arguments for using String is a bad practice? – Hunter McMillen Apr 18 '12 at 17:46
  • 1
    @hunter: imagine a method that takes as a parameter an object's state. If a String is allowed, then nonsense Strings can be passed in. With an enum there is much tighter constraints on what can be passed in. – Hovercraft Full Of Eels Apr 18 '12 at 17:47
  • I still think we might be missing context, despite your claim that the question is meant in the very general sense, because obviously we cannot do without Strings for most useful programming tasks, even if that just means putting labels on GUI components, creating URLs, etc. – Kevin Welker Apr 18 '12 at 17:47
  • See also [primitive obsession](http://books.google.ca/books?id=6jyOUrJBJHAC&pg=PT113&dq=primitive+obsession&hl=en&sa=X&ei=h_6OT5THIMTdggfKq7XqDQ&ved=0CFEQ6AEwBQ#v=onepage&q=primitive%20obsession&f=false) – Richard JP Le Guen Apr 18 '12 at 17:50
  • It is dogma that is evil in computer programming, not language features. – user207421 Apr 18 '12 at 22:05

6 Answers6

9

String is useful and the best way to represent textual data. Strings should not be used to represent:

  • enumerable, related constants (use enum). E.g. no "cm", "mm", "km" as units. Use a Unit enum with these elements. Unit.cm, etc.
  • numbers (use int, double, etc.)
  • dates (use Date, Calendar or joda-time DateTime)
  • passwords - use char[] instead, as strings are handled differently by the JVM and the sensitive information may become accessible to an attacker.
  • binary content. If you have a byte[], you should not use a new String(bytes) to transfer it - you can loose information that way. Strings can represent binary content, if it is encoded - in Base64, Hex, etc.
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 3
    And they **pretty much never** be used to represent *any/all of the above at once*. "Stringly typed" code is evil++. – cHao Apr 18 '12 at 17:47
  • Saying you should use "enumerations" when "enumerations" are appropriate, is answering the question with the question. The OP seems to be asking where enum might be more appropriate than a string. – Spencer Kormos Apr 18 '12 at 17:48
  • 2
    @Spencer Kormos I fixed the wording a few seconds after the initial answer. Now it should be clearer (I will improve a bit more) – Bozho Apr 18 '12 at 17:48
  • 1
    @cHao '"Stringly typed" code is evil' - yeah, like javascript! – Martin James Apr 18 '12 at 17:53
  • @MartinJames: Psh. Don't even go there. :) We're talking about Java, where variables have types. Using `String` to bypass the type system is just asking for trouble. (Even in JS, though, it's better IMO not to have 'numbers' like `"3.0"`.) – cHao Apr 18 '12 at 17:55
2

If you are asking if

...
public enum Settings {
    FAST,SLOW,PRECISE
}
...
if(setting == Settings.FAST) {
...
}

is better than

...
if("FAST".equals(setting)) {
...
}
...

Then the answer is yes, enum is better, because you can compare with == instead of .equals() which probably makes the executable faster and is easier to write, plus you can use switch where with string values you cannot, and with enum you can leverage a good IDE like NetBeans or Eclipse to help you avoid typos that would get past the IDE and the compiler if you are checking for String values instead of your enum Flags.

Robert Louis Murphy
  • 1,558
  • 1
  • 16
  • 29
  • You can `switch` on strings as of 1.7. (Granted, the compiler probably just turns it into an `if`/`else`...but still.) – cHao Apr 18 '12 at 17:59
  • Yes, you can use switch with strings in 1.7. Question, can you build Android Apps with Java 1.7 code yet? (Just wondering) – Robert Louis Murphy Apr 18 '12 at 19:01
  • I imagine so. Apparently Android doesn't really run Java -- the dev tools translate the Java classes to Dalvik bytecode -- so as long as the class format hasn't significantly changed, you ought to be able to use any version of Java you want. – cHao Apr 18 '12 at 19:13
1

java.lang.String is not evil. In fact, it's probably the most commonly used class in java (Disclaimer: I have no data to back that up). However, there are some considerations:

  • Crypto. There is one instance when dealing with crypto passwords where char arrays should be preferred over Strings:

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

-- http://docs.oracle.com/javase/1.4.2/docs/guide/security/jce/JCERefGuide.html#PBEEx

  • When concatenating Strings, you should probably use StringBuilder since java.lang.String is immutable and new copies are made for each concatenation.

  • When a more specialized class exists, e.g. enums, numbers, dates, etc., prefer it over String.

Asaph
  • 159,146
  • 25
  • 197
  • 199
0

One unfortunate aspect of using String is that prior to JDK 7 it doesn't work in a switch...case statement; you must (if using Strings for this purpose) use if...else if...else instead. And you must test with .equals() instead of ==, and under some situations you may want to use .equalsIgnoreCase() instead. All of these incline me to prefer enum to String for such situations.

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
0

It depends. Out of mind and assuming this list is not exhaustive.

Pros:
Java SE 7: String - The String class is immutable so Strings can be shared (this also implies thread safety).
String pool in Java - Strings are pooled so it is efficient when re-using them.

Cons: Concat operations are not efficient when using + for multiple Strings. It is better to use a StringBuilder or a StringBuffer (thread-safe) or Ropes. See this: IBM: Ropes

Community
  • 1
  • 1
Kounavi
  • 1,090
  • 1
  • 12
  • 24
0

String is not evil in and of itself.

I think the harm comes when you use it as your primary abstraction. You see it in code where there are lots of primitives (e.g. Strings, ints, arrays, data structures) that are obviously related, but are scattered throughout code.

A better solution in those cases is to encapsulate data items that belong together into a sensible object.

duffymo
  • 305,152
  • 44
  • 369
  • 561