frontpage.
newsnewestaskshowjobs

Open Source @Github

fp.

Open in hackernews

Ask HN: Java why put string in a constant?

1•ramsicandra•1y ago
I'm relatively new to Java. I often notice a pattern where there is a list of constant which value are equal to the name.

  class Constant {
    public static final String ALBUM = "album";
    public static final String NAME = "_name";
    public static final String DISPLAY_NAME = "display-name";
    public static final String SERVICE_NAME_METRIC_NAME_PREFIX = "service_name.metric_name";
  }

Here is a public example of this practice I could find: https://developer.android.com/reference/android/provider/MediaStore.MediaColumns

I could understand that this might help in 2 ways refactoring and typo. This reduces chance of typo because you'll get compile error instead of run-time error if you typo a constant. This might also help in refactoring if you ever wants to change the value. but if may use this android public API example, I don't think it's wise to change a field name ever. If it's decommissioned, it's good to keep it so we don't re-use the field. If it's a new better field available, I think it should have a different name. I maybe making a straw man argument here. Let me know. If it's an internal API where such refactoring might make sense -- I still kind of think internal API should also be backward compatible, replacing a string are not a complicated operation in my opinion.

I see that this practice has a cost. One being that in every class that use this API. You need to add an import. It's also often the const is only used once from my experience.

  import static com.example.MediaFields.NAME;
  import static com.example.MediaFields.DISPLAY_NAME;

  String value = json.getString(NAME);
  String value2 = json.getString(DISPLAY_NAME);
vs

  String value = json.getString("name");
  String value2 = json.getString("display_name");
You write 1 line for declaration plus 2 lines for each class using this API. This is not a big deal in terms of LoC and I'm not an LoC police. However, my sense is the cost outweigh the benefit.

What do you think?

Comments

lanna•1y ago
You just made TWO typos: "display-name" vs "display_name" and "_name" vs "name", automatically counter-argumenting your point.

It is also for documentation. With the declared constants, we know all possible values. With plain strings, how am I supposed to know which values to use?

The benefits far outweigh the marginal cost.

ramsicandra•1y ago
The -, _, and leading _ are just variations of white space / separator I have encountered. I think it's possible to document all the allowable values in the Javadoc section of the function that takes in string as their argument.

In the specific android example, I would put it here. Under projection params where it takes in all the Images.Media.* string consts.

https://developer.android.com/reference/android/content/Cont...

Though, if it's a practice of Java Engineer to document allowable enum like string as a constant, then I can say that's a valid argument.

A new Intel Itanium (IA-64) emulator that boots Windows

https://raymii.org/s/blog/Intel_Itanium_IA-64-Emulator_that_boots_Windows.html
2•jandeboevrie•8m ago•1 comments

Americans are angry about data centers. Politicians are feeling the pressure

https://www.reuters.com/world/us/americans-are-angry-about-data-centers-politicians-are-feeling-p...
1•baranul•9m ago•0 comments

From Enlightenment to Alignment

https://smolnero.com/posts/from-enlightenment-to-alignment
1•andsoitis•9m ago•0 comments

Why It's So Hard to Add a Column in the Middle of a PostgreSQL Table

https://www.bytebase.com/blog/why-its-hard-to-add-a-column-in-the-middle-of-postgres-table/
1•thunderbong•12m ago•0 comments

Moore's Law for Everything

https://moores.samaltman.com/
1•dtj1123•16m ago•0 comments

I built an AI operating system after getting tired of repetitive work

https://lynx.apex7ai.com
1•levymartins•18m ago•0 comments

Data Science Weekly – Issue 660

https://datascienceweekly.substack.com/p/data-science-weekly-issue-660
1•sebg•21m ago•0 comments

Is the determinant of this "Fibonacci sum" indicator matrix always -1, 0 or 1?

https://mathoverflow.net/questions/513340/is-the-determinant-of-this-fibonacci-sum-indicator-matr...
1•philipfweiss•22m ago•0 comments

Russian drones spotted using screwed-on magnetic compasses as navigation aids

https://www.tomshardware.com/tech-industry/drones/russian-drones-spotted-using-screwed-on-magneti...
2•rmason•23m ago•1 comments

Mefo Bill

https://en.wikipedia.org/wiki/Mefo_bill
3•handfuloflight•31m ago•0 comments

How to soothe thumb pain when texting and scrolling

https://apnews.com/article/trigger-thumb-de-quervains-tenosynovitis-carpal-tunnel-35728b0142d310c...
3•devonnull•32m ago•0 comments

Tine: A new editor for Jai, Zig and C++

https://travisdp.itch.io/tine
1•travismd•32m ago•0 comments

Heavy TV watching associated with smaller brain structures, study finds

https://dornsife.usc.edu/news/stories/heavy-tv-watching-associated-with-smaller-brain-structures/
37•mashally•33m ago•6 comments

Wall of Optimism – I have reasons to believe the future is beautiful, and you?

https://wallofoptimism.com
2•nikitafaesch•36m ago•0 comments

Can LLMs write Base64 as well as they read it?

https://arvidsu.github.io/encode_bench/index.html
2•ArvidSu•39m ago•0 comments

HMD Fusion easy to repair smartphone

https://www.hmd.com/en_int/hmd-fusion
2•savolai•40m ago•1 comments

Show HN: A schema you change by talking to it, without the model writing SQL

https://github.com/leandrobon/mutable-crm
2•leandrobon•40m ago•0 comments

Prime Flow Field Background Animation

https://www.brt.fyi/posts/prime-flow-field/
4•maxbrt•43m ago•0 comments

Is someone Into process mining? Let's talk in this thread

1•FrancescoMassa•46m ago•0 comments

The Windows laptop market is so bad I'm considering a MacBook

https://old.reddit.com/r/laptops/comments/1uy4hj0/ive_officially_hit_rock_bottom_the_windows_laptop/
3•ksec•48m ago•0 comments

Eric Schmidt tried to convert Google to Java

https://www.youtube.com/watch?v=ceCy2_FRxxo
5•mashally•49m ago•1 comments

Barbarians at the Gateways (2013)

https://spawn-queue.acm.org/doi/10.1145/2523426.2536492
2•tosh•57m ago•0 comments

Pyinfra Is Underrated

https://pyinfra.com
5•zxspectrumk48•1h ago•0 comments

Why Argentina Has Almost No Black People [video]

https://www.youtube.com/watch?v=FiPSZ_eaRPo
6•baranul•1h ago•0 comments

Trend Has Russian Men Smashing Their iPhones for a Manlier Look

https://www.odditycentral.com/videos/bizarre-trend-has-russian-men-smashing-their-iphones-for-a-m...
11•jethronethro•1h ago•1 comments

On Claude's Clotted Writing Style

https://blog.kierangill.xyz/clotted-claude
3•kierangill•1h ago•0 comments

The Newest Vegas Loop Stations Will Blow Your Mind [video]

https://www.youtube.com/watch?v=e7vFCP3PtuA
2•Topfi•1h ago•0 comments

Nvidia DGX Spark as a daily driver

https://daniel.lawrence.lu/blog/2026-07-15-dgx-spark-as-daily-driver/
5•plun9•1h ago•1 comments

Photo going viral of Lionel Messi with baby Lamine Yamal(2024)

https://www.euronews.com/culture/2024/07/16/two-legends-the-story-behind-the-2007-photo-going-vir...
2•rawgabbit•1h ago•1 comments

Wigolo: Local first web search agent

https://knockoutez.github.io/wigolo/
2•handfuloflight•1h ago•0 comments