Can class name and variable name be same in java? [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 8 years ago.
Improve this question
In this simple program is this good practice or what?
Can we use the same name as that of class in variable? IF yes, is there some particular term to use it? Is it a good practice?
class test {
public static void main (String args[]) {
int test;
System.out.println(test);
}
}

It is perfectly fine from a language grammer - syntax perspective. The compiler does not mix Class name with a variable name, since both will be in different scope. Both mean different things to the compiler. So it is perfectly fine to have a variable name as the same as the Class name.
The next aspect is the readability and maintainability. In this aspect, it is a very bad practice to have both the same. Because human beings mistake one for another. The very question you had asked itself is a sign that it will be difficult to maintain and manage such a piece of code.
Moreover the program which you have provided will result in a compilation error saying test is not initialized.

There are well-defined naming conventions in Java. Class names should begin with capital letters and variables should begin with lower case letters. These rules are not enforced, so as you have discovered you can define a variable with the same name as a class. In any language, if two entities have the same name, the language designers have to make a decision about how to interpret that name. In this situation, the decision was taken that whenever the variable is in scope the name refers to the variable, not the class. As a result it is impossible to refer to the class by its simple name (you can still use its fully qualified name though). As a result it's called obscuring. You should not do it because people reading your code will get very confused if you don't follow the standard naming conventions. You should also not do it because the person reading your code may not know whether the name is referring to the variable or the class. There's no reason why they should know - this is a very obscure corner of Java and there's no reason to do it anyway.
For more information, Java Puzzlers by Bloch and Gafter includes a detailed discussion (p.180 - 182) of all the different types of name reuse in Java (overriding, hiding, overloading, shadowing and obscuring).

Related

Is there a C and Python equivalent of Java's public and private? [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 2 years ago.
Improve this question
I realized that in many languages I have learned includes the keywords public and private, and I also found out that Lua's equivalent to private is local which got me thinking if there is also an equivalent in C and Python.
So is there an actual equivalent of Java's public and private in C and Python?
There is a naming convention for protected and private fields in Python:
A prefix of one underscore means protected, two underscores mean private. But this is not really enforced. More details here:
https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python
Everything not prefixed with one or two underscores is public.
In C, global variables and functions can be accessed from functions in other source files unless they are declared static. Not exactly the same as private, but C is not object-oriented so the concept of a class does not exist here.
In python you can declare private members by putting dunders(double underscore) before member name, like this :
class Sample:
def __init__(self):
self.__private_mem = "Can be accessed only by member functions"
self.public_mem = "Can be accessed as object properties outside the class"
sample = Sample()
print(sample.public_mem)
print(sample.__private_mem) # will raise an Error
But, I guess there is no such thing in C language as it is not object oriented.

Any reason not to prefix Java type parameters with a dollar sign? [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
First off, I know not to use dollar signs in class names, because inner classes get dollar signs in their .class file names. I've also seen synthetic variable names like this$0, so I tend to avoid dollar signs in identifiers like any good Java programmer.
However, I find single-letter type parameters like <T> to be repugnant. If I'm making a generic class that has parameters for requests and responses, for instance, I have a naming problem. What should I use, <TRequest, TResponse>? <R1, R2>? Gross.
I've started doing <$Request, $Response>. It's readable, it's distinct, and I can't imagine any .class file naming conflicts. Seems to me like low-hanging fruit for making Java code more readable. Any JVM gurus or insightful devs want to tell me why this is a terrible idea?
Edit: As for readability, I may be drawn towards this by my use of other languages in which variables are prefixed with dollar signs, and generic types are types with a more variable nature than class types. As for convention, yes, I'm a fan; I want to know whether this would work as a convention, or if some technical issue would prevent it.
Convention, convention, convention.
Although you're free to do as you wish, the general convention can be found in the Java Trails.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U ,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API...
Breaking these conventions should only be done when:
Following the above protocol would make the generic more confusing to use
The readability gains can be readily identified by other collaborators
Explicitly in the case of $, the JLS has a recommendation against using $ as a generic identifier.
The $ sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

Why does java use System.out.print/println instead of just print or println? [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
This post may be considered to be inappropriate for stackoverflow, although I'm not trying to insult the Java language or anything like that. I enjoy coding in Java, but there is something regarding System.out.println that I have been wondering for quite a while.
Why is it that we are always forced to type System.out.println() or System.out.print() every time we want to print? Sure, we could make a void function to save time and energy in programs that we will have several print statements (which I sometimes do) like so:
public static void print(String output) {
System.out.print(output);
}
and then just call print (and if you want to really be thorough you can overload the function with arguments involving ints, doubles, chars, etc). But why is it that the Java language itself doesn't already allow us to print to the console by just writing print? Some languages (such as Python) make printing to console that neat and simple - so why doesn't Java?
Again - I'm not saying that the Java language is poorly designed, or trying to start a thread that is intended to bash Java. I'm sure the language designers had their reasons for designing it the way they did, and it would help me to understand why it is so. It would be much easier to just need to type print instead of System.out.print, so there must be reasons for why we must type System.out.print - I just can't figure out those reasons. I've tried googling for information on this issue and can't find anything relevant to the issue.
Please refrain from opinionated responses about the Java language - I want actual facts that explain this phenomenon.
Simply, Java doesn't have global functions.
Also, according to The Java Language Environment (a '90s book co-authored by James Gosling):
Java has no functions. Object-oriented programming supersedes functional and procedural styles. Mixing the two styles just leads to confusion and dilutes the purity of an object-oriented language. Anything you can do with a function you can do just as well by defining a class and creating methods for that class.
It's not to say that functions and procedures are inherently wrong. But given classes and methods, we're now down to only one way to express a given task. By eliminating functions, your job as a programmer is immensely simplified: you work only with classes and their methods.
So there is at least one language designer's reasoning.
You may shorten the call by statically importing System.out:
import static System.out;
class Example {
public static void main(String[] args) {
out.println("hello world!");
}
}
Since System.out is an object, its instance methods cannot be statically imported.

Java/Guava convention for using 'get' prefix? [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
On a project that I am working on, we are debating when to use get (getFoo) vs a normal name (foo) in java. When I look around in java core and guava, I see that there are many examples where get is omitted. Is there any doc that covers when guava or new java APIs will use the get prefix and when not to? Is there a convention these developers use here?
Thanks for taking the time to read this.
Examples:
ByteBuffer : http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#compact()
ForwardingObject : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/ForwardingObject.html#delegate()
Stopwatch : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Stopwatch.html#elapsed(java.util.concurrent.TimeUnit)
Ticker : http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/Ticker.html#systemTicker()
EDIT:
As of http://download.oracle.com/otn-pub/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/beans.101.pdf, "A Java Bean is a reusable software component that can be manipulated visually
in a builder tool." In our code base, the issue of get vs no get comes when the code has nothing to do with value or data objects (objects that represent data). When the class represents data, we are fine doing get.
My main question is why both java and guava choose to use non get methods for non data objects and what are their conventions.
The get prefix comes from the JavaBeans Conventions, which states that if you have an accessor for a property, then the accessor method's name must start with get, unless it is a boolean (the primative type), in which case is should start with is. Note that you use the get prefix to return type Boolean.
Throughout most of Java's API this is the convention that is used, which would be my recommendation as well. Your decision is up to you, but whichever convention you pick, I would suggest to be consistent and not mix the two.
While the idea of dropping the "get" appeals to me, the problem comes when you also have a setter. You would have to do something like
public String name(); // getter
and
public void name(String newName); // setter, xor use the below **instead** but not both
public Foo name(String newName); // if you prefer fluent/builder style
Which "looks weird" to a Java programmer. And until 1 minute ago I thought it was illegal, and my original post mistakenly said so until I tested it. You learn something everyday...
Added in response to #DwB
One good reason to use get/set is that many 3rd party frameworks expect this convention, as they use reflection to reason about your class. However, a framework could be able to look for combinations like the above, or be configured to use these methods instead of the usual get/set. This was almost in my original post but I haven't used Spring, Hibernate etc. in a few years so I'm not up to speed on what some of them will on won't allow if you aren't using get/set.
For example, Jackson can use annotations and mixins to define mappings, no need to follow get/set convention. I would think that Spring, JSF etc. could do likewise, (somebody please edit this answer with details as needed) though with some extra work. Whether this extra work is worth the "conciseness" of eliminating get/set is unclear. I'd say no, but YMMV.

Java: Include "this" parameter or let it be implied [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 a Java recommendation or industry best-practice suggestion for including, or not including, the this parameter when it isn't explicitly necessary?
For instance, assuming there are no naming clashes between instance variables and local variables, is it preferential to use
this.someParam
or simply
someParam
and when calling methods that are in the same class is it preferential to use
this.someMethod()
or
someMethod()
The argument in favor of the former is that it makes the code more explicit. The argument in favor of the latter is that it makes the code cleaner.
I'm curious if there is any documentation out there that recommends one way or another (I can't find any, google searches with the word this are obviously tricky) or if it is simply a matter of preference.
On the merits of explicit versus cleaner: Excluding "this." is no doubt less text character "noise" (albeit small) in source file. The "this." explicitness would be helpful for example if using a small text viewer when looking at a method with many lines of code (should that be the case anyway?). So at best the explicitness has limited usefulness - especially as modern IDEs highlight instance variables. I am of the opinion of excluding "this." as code style.
I don't know that there is a "wrong" answer here. However, in my 15+ years writing Java, the convention that I have seen is to NOT include "this" unless it is necessary.
You can minimize confusion by naming variables in a consistent way. There are several good convention documents out there. Pick one and follow it. Some examples:
http://google-styleguide.googlecode.com/svn/trunk/javaguide.html
https://source.android.com/source/code-style.html
http://www.javaranch.com/style.jsp
There is no reason to prefer one or the other. It's a matter of opinion.
My opinion is that you should only use this if needed. There are some situations when you have to use this, such as if a local variable has the same name as an instance variable. It happens a lot in my constructors:
public MyClass(String s, int i) {
this.s = s;
this.i = i;
}
If you are working on a team, I recommend coming up with a strategy you all agree with, so you don't waste too much time reformatting each others code. Also, for me, it's pretty annoying to look at code that uses this too much (such as that generated by JD).
As for:
parameters/attributes - I always suggest using consistent approach throughout the code. In most cases all automatically generated getters and setters of Java classes need to use this to distinguish parameter name from actual object attribute. Consistency is then a good reason to use this for instance variables throughout the code. Sample setter which uses this to avoid ambiguity:
public void setName(String name) {
this.name = name;
}
methods - this.someMethod() is just longer than someMethod() and does not provide any benefit over the shorter someMethod(). If we call the latter, it is already known that we are in fact calling this.someMethod(). There is no ambiguity in calling just someMethod() like it is for parameters, so I would discourage the use of this.someMethod().
In my opinion, there is no common guidelines for all Java developers in the world defining good practices for using this. I'd rather follow the guidelines used in your company/project, or, if there are none, your own ways of writing well-read code.
There isn't a best-practice suggestion. Most teams simply have their own coding style.
Personally, I try to use use this for all my instance variables, but tend to avoid it for methods.

Categories

Resources