Why does Java's V Map.put(K key, V value) not comply to the Command-Query Separation?

  • 4
    Many reasons. For instance, the Time-of-check-time-of-use problem often requires doing exactly the opposite as the command-query separation principle says. – Kilian Foth Mar 18 '20 at 7:13
  • 2
    We can speculate, but only the programmers who created that method can give a definitive answer. – Rik D Mar 18 '20 at 7:16
  • How downvoted?. It's a valid question! – Suhas Srivastava Mar 18 '20 at 9:03
  • 3
    @SuhasSrivastava Because answering this involves Software Engineering, but it would require reading some designer's mind to be sure. Don't be disouraged by StackExchange, it's a bit like Albus Dumbledore: the most powerful force of explanation in the world, but a bit mad (especially right now). – Kilian Foth Mar 18 '20 at 9:10
  • Why do you ask about this method specifically? Do you see any widespread attempt at following CQS in the Java API in general? Almost all of the state-changing methods on Map also return a value. – Hulk Mar 18 '20 at 11:25

The Command-Query Separation Principle was created by Bertrand Meyer for the Eiffel Programming Language. The Java Programming Language is not the Eiffel Programming Language, so there is no reason for Java Programmers to follow rules of Eiffel Programmers.

There are hundreds of people who have written thousands of books on Object-Oriented Programming. It is highly unlikely that some random programmer working at Sun in the 1990s would have read every single one of those books, so it is to be expected that they may not know about at least one of the rules set out in those books.

  • 2
    CQS often leads to code that’s easier to reason about. That’s a reason for Java programmers to follow the principle. – Rik D Mar 18 '20 at 7:14
  • 1
    @RikD except for when its not. Not everything can be pleasantly done as either a command, or as a query. Consider updating an atomic variable, but only if it were originally zero. The decomposition essential forces the same logic to be forced down one layer. In which case how does one atomically update the guard bit/bits but only if unset? repeat till absurdity hits home. – Kain0_0 Mar 18 '20 at 7:34
  • Agreed @Kain0_0. Only apply principles when they make sense! – Rik D Mar 18 '20 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.