Why do Java programmers like to name a variable "clazz"? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I've seen lots of code with declarations like Class clazz. Where does this originate from? Is this some kind of convention? I think ‘clazz’ is not even an English word, has no meaning at all, how can so many programmers name a wrong name coincidentally?

clazz has been used in Java in place of the reserved word "class" since JDK 1.0. "class" is what you want, but abbreviating or inserting junk ("a", "the", "_", etc) reduces clarity. clazz just says class. "International" English speakers (those reading both British and American English) are used to transposing 's' and 'z'.
Since Java has had disclosed source and a suitable culture right from the start, worthwhile Java code and tutorials pick up the same conventions. That's one of the great things about the Java ecosystem, which I think has been an important part of its success.

Because they cannot use the word they want to use which is class. It is reserved.

It's simply because 'class' is a reserved keyword, hence Class class isn't allowed. Therefore you'll see Class clazz or Class cls.

It comes down to the actual compiler and its ability to distinguish what a token means within its context. However, in this particular case, it is the compiler's inability to distinguish what the token class means in a different context. It is a hard and fast rule that class, regardless of its context, is used to denote the declaration of a class, and as such it is a reserved word. That is as simple and as low-level as it gets.
If you feel compelled, you could write your own Java compiler to include a contextual rule that will allow you to use class as a variable name. Though I think it would be far better use of your time to just use clazz or klass -- it would probably be good for your health as well.

Declaration Class clazz is popular in Java world, but it may be awkward for newcomers and spellcheckers. I've heard some people saying that it should be avoided according to principle of least astonishment.
As it is possible to say that a Class object represents a type, I personally prefer to declare such variables as Class type.

where does this originate from ?
I saw it first at Josh Bloch's puzzlers. But I'm pretty sure it was used much earlier by other developers. Josh Bloch just made it more famous.

Java does not have a feature that allows you to use a keyword as an identifier, unlike C# with its # prefix (e.g. #class is a valid identifier.)

It is just a English word replaced(Equavalent) by Keyword Class Keyword, to make people understand that it is a Class. and it is almost to increase the readability of the Code
Nothing big Logic involved in this

We use clazz because class is a type header. For example, you use class here:
public class HelloWorld {
and here:
Object.class.getName();
So unfortunately, we have to use alternate names such as clazz.

Related

Is it good to Sharing constant strings in Java across many classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'd like to have Java constant strings at one place and use them across whole project?I am confusing Is it a good practice for better readability or not?
Simple: when multiple classes need the same information, then that information should have a single "root".
So yes: it is absolutely good practice to avoid re-declaring the same value in different places. Having a "global" constant simply helps with avoiding code duplication - thus preventing errors later on, when you might have to change such values.
One single class with (unrelated) constants has problems. It is a bottleneck:
if in a team a constant is added at the bottom, someone else adding a constant will receive a VCS conflict. Enforce the declarations to be sorted alphabetically. It also ties this package together in other forms. Still many unneeded recompilations would be needed (see also the remark at the end).
In java 9 with modules, you would in every using module need to require the constants classes module, probably causing an unnecessary module graph.
Then there are constants which need not be named and still are not "magic".
In annotations as arguments. An annotation scanning can gather those values if you need uniqueness or such.
And finally there are shared constants. Near the used constructs is still my favourite.
Also the constants class pattern tends to be used often with String constants. That reeks of code smell, as it is a kind of burocracy where one
should use automatic mechanisms, OO, fixed conventions, declarative data.
For database tables and columns there exist better mechanisms.
Classes with constants (still) have the technical compilation problem that in java the constant is incorporated in the .class file itself, and the import disappears. Hence changing the original constant will not notify the compiler to recompile the "using" class. One needs a full clean build after recompiling a constants class.
If you think that your Strings are going to be referenced in many flows, then it is good to use. Moreover, it is a widely accepted practice as well.
It is good to create Interface & declare your all constant in it.
E.G
public interface ICommonConstants {
public static final String ENCODING_TYPE_UTF8="UTF-8";
}
Implement this interface in your all class where you like to use constants.You can use by calling
ICommonConstants.ENCODING_TYPE_UTF8
Code duplication is a code smell and if you wouldn't use readily available constants you need to re-declare the String over and over again for each class using it, which is bad.
This leads to less maintainable code, because when the duplicated String needs to change and you forget to update it in one of the classes, the code breaks.
It's common practice to set up a class holding reusable constants:
public final class MyDefs {
public static final String A = "a";
public static final String B = "b";
private MyDefs() {
// Utility class, don't initialize.
}
}
I would recommend an Enum, or you could just have sort of like a utility class with just static final strings. All depends on what you want do i guess, i don't see anything bad. if the class is going to be shared by many classes, that's fine.

Why are Java naming conventions not enforced? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Java has strong naming conventions for class, method, field and variable names.
For instance:
Class names should start with an upper case character
Methods, fields, and variable names should start with a lower case character
The JDK has only few exceptions to these two rules.
But a convention is not a syntax rule, and therefore classes like the following compile without errors (C# programmers would be happy anyway):
public class string {
private char[] C;
public int Length() { return C.length; }
}
But the gap between a convention and a syntax rule inevitable leads to violations of the convention by beginners which then leads to lengthy explanations about naming conventions.
If the most fundamental naming conventions (like the one cited above) would be part of the syntax then the Java compiler would enforce them and automatically educate those beginners.
So here is the question:
From the Java language designers point of view: Is there any good reason to leave a gap between syntax and naming conventions which should never be violated? Are there any meaningful use cases for namings (of classes, methods, fields, variables) which violate the convention but make sense beyond the convention?
The conventions were written long after the language was defined so they could be retrofitted without breaking compatibility. The problem with conventions are they involve taste. e.g. spaces or tabs, using $ as a variable name, starting field names with m_ or _ etc. even wither to add get and set to getters and setters (which I prefer not to)
Java actually allows you to do things which would make C programmer feel queasy. Why they allowed this I don't know, but I assume they didn't want to limit adoption by imposing more rules than really needed.
Note this is a piece of Java code is valid due to the use of a character which probably shouldn't be allowed but is.
for (char c‮h = 0; c‮h < Character.MAX_VALUE; c‮h++)
if (Character.isJavaIdentifierPart(c‮h) && !Character.isJavaIdentifierStart(c‮h))
System.out.printf("%04x <%s>%n", (int) c‮h, "" + c‮h);
Most IDEs will help beginners write code which follows conventions. The only problem with this is most developers don't know how to make full use of their IDEs. ;)
Well, personally I think the reason for not enforcing conventions is simply because of the fact because it's technically not really necessary. Counterexample: E.g. in Java you have to name the class file exactly like the class because the Java Class Loader could not load it otherwise. Building these checks into the compiler would bloat the source code and as the name tells it, a compiler converts source code into machine code / byte code / whatever by parsing the source files and checking the syntax. Checking whether a class starts with an uppercase or lowercase letter is simply not the compiler's job.
And of course a programming language gives you a certain degree of freedom by not enforcing such things as conventions to style your code how you like it if it matches the syntax rules of the language.
Well, if I use some Chinese characters in identifiers, there are no upper/lower cases for them:) So the convention cannot be always enforced.
Of course, it's pretty safe to bet that 99.9% Java code are in English. And you may also argue that the enforcement can be limited on some charsets only.
I agree that this naming convention has become critical, and it should be strictly followed. A java source code that does not follow the convention is practically incomprehensible.
From the Java language designers point of view: Is there any good reason to leave a gap between syntax and naming conventions which should never be violated?
Yes. "Never" is a strong word.
The language has requirements and recommendations. The language specification for identifiers is a requirement. But those strong naming conventions are recommendations.
Having some definition of identifiers is necessary for the compiler to recognize them as tokens. Leaving that definition looser than the norm gives us a little freedom for cases outside the norm.
Are there any meaningful use cases for namings (of classes, methods, fields, variables) which violate the convention but make sense beyond the convention?
Yes. Java programs can interact with other languages, which have different conventions.
Code conversion
Sometimes when hand-converting code from another language, leaving the original case is easier and more understandable.
Code generation
Sometimes we generate code from a specification that was not written for Java. For example, we might generate code from a WSDL file, or generate wrappers using SWIG.
Code wrappers
Some Java methods can wrap external functions. For example, JNA allows defining interfaces with a native function's name and signature.
JVM languages
Multiple languages can run atop the Java virtual machine. These other languages have their own conventions. It's possible to mix languages in a single program. Stepping outside the convention can be necessary to interact.
I guess this is why it's only conventions and not rules... I don't see why should it be enforced, there are many other conventions which are not enforced (e.g. putting constructors before alother methods, putting public methods before private methods and many more), it would be too strict (in my mind at least) to enforce it all.
I can think of one case you don't want this convention to be enforced - it's also common to write consts variable in uppercase- again, just a convention.
In any case, I think that in most IDE's you can configure it to give a warning when such conventions are violated. this can help you I guess

When is length used as a method and when as property in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've seen some legacy code that uses lengthproperty on some objects and others that uses length() method. Currently I'm working with a NodeList from the org.w3c.dom package and I found that it have the getLength() method to get the numbers of elements.
My Question is how as Java developer I can know how to determine when to use length, length(), size(), getLength()? obviously it depends of the object type and the API is there for read... but the point is how the Java Development select which of that implements in their classes.
Note: In the Question When to use .length vs .length() Makoto answer's indicates that .length is a property on arrays. That isn't a method call, and length() is a method call on String. But, why is the reason? why not use ever a method or ever a property for maintain the consistency around all the API.
how would Java developers select which of [the methods] to implement in their classes?
When you implement classes that contain other objects, it's almost always going to be size(), the method provided by theCollection interface.
As far as other choices go, you should avoid exposing member variables, even final ones, because they cannot be accessed through an interface. Java gets away with it for arrays because of some JVM trickery, but you cannot do the same. Hence, length should be out: it remains in Java because it's not possible to change something that fundamental that has been in the language from day one, but it's definitely not something one should consider when designing new classes.
When you implement your own type that has length (say, a rectangle or a line segment) you should prefer getLength() to length() because of Java Beans naming conventions.
obviously it depends of the object type and the API is there for read...
You already have answered your question yourself: look in the API documentation of whatever class you are using.
but the point is how the Java Development select which of that implements in their classes.
The classes in Java's standard library have been developed over a long period of time by different people, which do not always make the same choice for the name of methods, so there are inconsistencies and unfortunately you'll just have to live with that.
There is no clear rule, otherwise we wouldn't see such a mixup in the jdk itself. But here are some things to consider when making such a design decision.
Don't worry to much. It is a minor thing and won't make to much of a difference. So when you think longer then 5 minutes about this, you are probably wasting money already.
Use getters when a frameworks need them. Many frameworks depend on the getter style. If you need or want such frameworks to work nicely with your class it might be beneficial to use that style.
Shorter is better. the 'get' part doesn't increase clarity. It just generates to characters of noise to the source code, so if you don't need it for some reason, don't use it.
Methods are easier to evolve. Length is often a quantity that is not set directly but somehow computed. If you hide that behind a method it gives you the flexibility to change that implementation later on, without changing the API.
Direct field accesses should be a tiny bit faster, but if you aren't working on high volume online trading or something, the difference isn't even worth thinking about. And if you do you should do your own measurements before making a decision. The hotspot compiler will almost for sure inline the method call anyways.
So if there aren't any external forces driving you in a different direction I would go with 'length()'
According to OOPS principles, length should be attribute and getLength() should be method. Also length attribute should be encapsulated should be exposed through methods, so getLength() sounds more appropriate.
Unfortunately not all Java library classes follow standards. There are some exceptions and this is one among them.
In a pure OO language it should be probably always a method like length(). So in a class hierarchy you can override the attribute length.
But Java is not pure OO. And the main reason for fields (.length) vs method (length()) is/was performance issues.
And even Sun/Oracle programmers did some bad class design.

Why Object.hashCode() does not follow Java code convention [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is there any specific reason, why hashCode is the only public method of Object class which does not follow Java Code Conventions recommended by Sun and later on by Oracle? I mean they could name it toHashCode() or getHashCode() or createHashCode() right?
EDIT:
I talk about Code Conventions for the Java Programming Language ( oracle.com/technetwork/java/codeconvtoc-136057.html ). These conventions are referenced in Oracle's book 'OCA Java SE 7 Programmer I Study Guide (Exam 1Z0-803) (Oracle Press) - Liguori, Robert'
In the document we can read as follows:
"Methods should be verbs, in mixed case with
the first letter lowercase, with the first letter of
each internal word capitalized.".
AFAIK hashcode is not a verb.
I think it does follow conventions. It all depends on which convention you're talking about.
The OP is specifically interested in the Code Conventions for the Java Programming Language, and the conventions for method names are covered in chapter 9. First, it should be noted that this document is no longer maintained, and contains a large caveat:
... the information itself may no longer be valid. The last revision to this document was made on April 20, 1999
Of course, the hashCode() method predates 1999 so we can refer to the document to see if the method in question violated the conventions at the time. The document states:
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
With regard to hashCode(), there is no disputing that it is mixed case with the first letter lowercase. However, the OP seems to be of the opinion that it violates the convention that methods should be verbs; the implied assumption is that "hash code" or "hashcode" is a noun.
Before passing judgment, let's look at the third part of the convention: the first letter of each internal word [is] capitalized. If you briefly assume that the original authors followed these conventions, then the capitalization of hashCode() indicates that its authors considered "hash" and "code" to be separate words. If you treat them separately, the word "hash" is a verb in English. With that interpretation, all parts of the convention are met.
Admittedly, the term "hash code" has become common jargon among (at least) Java developers and is often treated as a noun -- probably in no small part due to the name of this method in the first place. (Chicken v. egg?) But only the original authors can speak to their intent.
In my original answer, I used the JavaBeans conventions as an example:
A bean is a Java class with method names that follow the JavaBeans guidelines. A bean builder tool uses introspection to examine the bean class. Based on this inspection, the bean builder tool can figure out the bean's properties, methods, and events.
In JavaBeans, properties are accessed via a "getter" method, i.e. the "foo" property is read by calling getFoo(). However, the hashCode() method is a technical requirement imposed by the Java language on all subclasses of Object but is not generally a property of the "business logic" that the object represents. If you write a class to represent fruits, it would have properties like getColor(), isSkinEdible(), etc. If not for Java's technical requirement, you would probably not consider writing a method like getHashCode() because... have you ever found a real, live banana with a hash code?
If hashCode() were named getHashCode() then, for this convention, JavaBeans would have to special-case it in order to ignore it. Or it would always inspect that "property" for what commonly has little use in the main logic of your program.
I can't cover all possible conventions in this answer, but I have these thoughts on the other examples given in the question:
createHashCode() - I would not use this, even by convention, because hashCode() returns an int (a primitive) and they're not created like reference types (Objects) are. I think this would be the wrong verb.
toHashCode() - To me, this represents a conversion. But that's not what hashCode() does. If foo.hashCode() returns 42 I should have no expectation that 42 is in any way a representation foo. It was computed from information about the foo instance, but there's no other real correlation. Plenty of other instances (of many classes) could return 42 so it's not a stand-in or analogue for any of them.
The hashCode() method was specified before there were conventions.
Also, the convention is for naming Java Bean "properties," to facilitate wiring together beans in a design tool and assist in other forms of automation. It's unlikely that you'd need the hash code to be exposed as a property in these situations. In fact, because getClass() does follow Java Bean naming conventions, it requires a special case in many such tools to exclude it from the list of object properties.

what are the major differences and similarity in java and ruby? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am java professional now I like to go for ruby.Are there any similarity in both the languages? and what are the major differences? As both are object oriented.
What about these:
Similarities
As with Java, in Ruby,...
Memory is managed for you via a garbage collector.
Objects are strongly typed.
There are public, private, and protected methods.
There are embedded doc tools (Ruby’s is called RDoc). The docs generated by rdoc look very similar to those generated by javadoc.
Differences
Unlike Java, in Ruby,...
You don’t need to compile your code. You just run it directly.
All member variables are private. From the outside, you access everything via methods.
Everything is an object, including numbers like 2 and 3.14159.
There’s no static type checking.
Variable names are just labels. They don’t have a type associated with them.
There are no type declarations. You just assign to new variable names as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a = {1,2,3};).
There’s no casting. Just call the methods.
The constructor is always named “initialize” instead of the name of the class.
You have “mixin’s” instead of interfaces.
== and equals() are handled differently in Ruby. Use == when you want to test equivalence in Ruby (equals() is Java). Use equal?() when you want to know if two objects are the same (== in Java).
Taken from: To Ruby From Java
Besides being object oriented there are very few similarities between the two languages. Java is a statically typed compiled language while ruby is a dynamically typed interpreted language. The syntax is also very different. Java uses the c convention of terminating lines with a semi-colon while ruby uses the return character.
While Java does have some built in support for iterators ruby's uses of iterators is pervasive throughout the language.
This obviously only touches upon a comparison of the two. This is a decent write-up on the comparisons
You're asking a very broad question. I like to compare scripting languages similarly to how I'd compare spoken languages, so in this case; what are the major differences and similarities between Spanish and Italian?
If you ask that question, you're going to either get very varied or very long answers. Explaining differences between languages are difficult at best, as it's hard to pinpoint key factors.
This is proved by the responses here so far, as well as the links other people have linked to. They're either varied or very long.
Going back to the Spanish vs. Italian analogy, I could say that the languages are similar but still very different. If you (only) know one of them, you might be able to understand what's going on in the other, though you would probably not be able to use it very well. Knowing one definitely makes it easier for you to learn the other. One is used by a larger number of people, so you might benefit more from learning it.
All of the previous paragraph can be applied to Java vs. Ruby as well. Saying that both are object oriented is like saying Spanish and Italian both are members of the Romanic language family.
Of course, all of this is irrelevant. Most probably, your underlying question is whether it's "worth" learning Ruby instead of or in addition to Java. Unfortunately, there's no easy answer to that either. You have to weigh advantages and disadvantages with each language, such as popularity, demand and career opportunities. And then there's naturally the question of which language you prefer. You might like one language more than the other simply because it has a nicer syntax. (Similarly, you may prefer Italian because you think it's more "beautiful" than Spanish, even though the latter is more widespread and you'd have more "use" for it.)
Personally, I prefer Ruby. For many different reasons. Just like I prefer Italian.
The Object Oriented feature in Ruby is actually very different compared to Java.
In Ruby, everything is an object, including a primitive type (in Java) like integer.
In Ruby, new is like a property instead of a keyword. So to instantiate an object you would do this in Ruby:
animal = Animal.new
Ruby is strong typing but also dynamic. Because of its dynamicsm, Ruby enables you to do duck typing.
Ruby's answer to multiple inheritance is mixin (which is a language feature), where in Java you would implement many interfaces.
Ruby has got block, where you would use anonymous class to achieve the same thing in Java. But IMHO Ruby block is more powerful.
So I can say there's not too much similarities in Java and Ruby. Until today I can't find any similarities between the two as Ruby has gone its own path unlike many other language that derives from C language.

Categories