Using unnecessary "this" in constructor to set instance variables? [duplicate] - java

This question already has answers here:
Should I use "this" keyword when I want to refer to instance variables within a method?
(8 answers)
Closed 4 years ago.
I had written a piece of code along the lines of:
public abstract class TestService extends Base {
protected final MappedObject<A, B> mappedObject;
public TestService(Provider provider, ObjectMapper objectMapper) {
mappedObject = new MappedObject.Builder<A, B>(...);
...
}
...
}
However, I have been instructed to prefix this to mappedObject, as it is convention when it comes to setting instance variables. Is this true?
I was under the impression that this as a prefix would only need to be used if there were a parameter with the same name that could cause ambiguity. Hence, a this would be necessary to reference the instance variable rather than the argument passed.

As you seem to be aware, it's not necessary, as long as there is no ambiguity between local and member variables of a class.
However, there are a number of different schools on this, and whether it's "convention" or not varies depending on who you ask (different developers have different preferences, different companies have different conventions, etc.). I would say it's mostly common in school courses. In the real world you might see it in a constructor from time to time, but in my personal experience it's quite rare.
Something that I find is more of a convention, and somewhat ties into this question, is prefixing member variables with m, as in mMappedObject, to indicate that it is a member variable. This is very common - in fact, one could argue that it's probably more common than prefixing this.

Related

Java: place of constructors, static methods, public methods, private? [duplicate]

This question already has answers here:
Are there any Java method ordering conventions? [closed]
(8 answers)
Closed 7 years ago.
I have come to the question: what is the most preferred way of placing methods? I mean, should first declare static methods, then constructors, then public methods, then protected, then private, etc? Is there some kind of convention, like I guess everyone places fields (instance variables) on top of the code. Is there the same policy about methods?
I guess it depends on the language you use. What about Java?
This is somewhat opinion based, but the Google Java Style doc puts it nicely:
The ordering of the members of a class can have a great effect on learnability, but there is no single correct recipe for how to do it. Different classes may order their members differently.
What is important is that each class order its members in some logical order, which its maintainer could explain if asked. For example, new methods are not just habitually added to the end of the class, as that would yield "chronological by date added" ordering, which is not a logical ordering.
https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s3.4.2-class-member-ordering
Most of the code I see in the open source world uses some variation of
static fields
instance fields
constructors
methods (instance and static)
anonymous classes
It comes down to team preference, but it is always good to follow convention
Talking about execution, JVM guarantees the order which we cannot change.manage.
But from code readability point of view , YES ordering does looks good. Following coding standards is what should do.
Static fields -> instance fields/variables
As we know, Static Block is always called once class is loaded, so we should have it.
Then constructors, for object creation, there is no point of writing constructor at the end.
also a good read here as suggested above.

final static variables and their use [duplicate]

This question already has answers here:
private final static attribute vs private final attribute
(22 answers)
Closed 8 years ago.
I've created an interface with the following code
final static char RIVER = '~';
final static char PATH = 'Y';
The list will increase (not hundres or even tens but maybe at most 15 symbols)
Originally I was just coding the values directly into the object but I started wondering why I couldn't just create a single file with the global constansts (for the symbols on the map and only the symbols) for easy access.
I'm aware that per OO logic, encapsulation is how we should program. At the same time, final static variables exist so surely they do have a purpose.
My question then is there a reason for me to avoid using the global constants and go back to putting each symbol with each object? Does global constants have a role to play within OO programming at all or is it purely for Procedural Programming?
This is a project that only I will ever work on however I am using as a testbed to improve my standards and as such I would like to use the best method possible (in terms of standard).
Defining global constants in an interface is an anti-pattern. Either use classes to define constants and then use static imports. Or simply use enums, which gives more flexibility.
Defining global (public static) constants is okay. It helps to keep you code clear and maintainable, by giving certain values meaningful names.
What you should not do, is define global constants in an interface and then add an implements-clause to each class that uses these constants. The reason for this, that you pollute the public signature of your class in this way. Instead, alsways refer to the constants by their full name (e.g. SomeClass.SOME_CONSTANT) or statically import them (import SomeClass.SOME_CONSTANT).
I would not define all global constants in one single file however, but define each of them in the class or interface that makes the most sense, for example because they define methods that return these constants or where the constants are typical arguments.
There are several benefits in use the constants, these are some of them:
Readability: If you hard code the number, when you or some other programmer have to use the code, they have to know what the value means. If a constant is used, a meaningful name is provided.
Reusability: If the same constant needs to be used in several place, when a modification is needed, you only have to change the value in one place instead of all the places where the constant is used.
Maintainability: If you have your constants in a single place instead of multiple places in the code, it is easier to modify.
It is considered a bad practice to use interfaces to hold the constants, use classes instead. If the constants are related with the class, you can define the constants within the class. If they are general purpose constants and used in several classes, you can create an utility class to hold all the constants.
public class MyUtilityClass {
public static final int MY_INT_CONSTANT = 1234;
public static final String MY_STRING_CONSTANT = "example";
...
/* Create a private constructor to avoid creation of instances of this class */
private MyUtilityClass() {
}
}
Global constants are absolutely fine.
That having been said, do not even try programming without the maximum number* of compiler warnings enabled. If you had enough warnings enabled, your compiler would be telling you that fields in interfaces do not need to be declared final and they do not need to be declared static.
(* warnings that make sense. Every compiler has its own set of warnings that are rather nonsensical and best disabled, but these are generally few.)
Encapsulation is the mechanism which protects you from changes - for example, changing the implementation of a class, will not affect the rest of your code as long as the interface (the public or protected methods) does not change.
So you can apply this reasoning to your case. Will future changes of these constants affect the rest of the code? If not, then putting all those constants as final static instances in a single class is fine. But think of this. What if you want to change how you represent your map? (from the names of the variables I assume you're using them to represent a map) Maybe you want to use special objects which also have their own behaviour, not just how to represent them on the map. Then maybe you'll want to abstract those in new classes, and not use constants anymore. And this will affect all the code where you reference these constants - probably lots of classes.
Of course, you can start with this simple representation, and if at a later point you find it's not working anymore, then you can switch. This is what I would do. I don't think it's wrong.

Anonymous inner Comparable class in Java method? [duplicate]

This question already has answers here:
How are Anonymous inner classes used in Java?
(18 answers)
Closed 8 years ago.
My professor offered this bit of code in an exercise about scope and lifetime:
class AnonymousInnerClassInMethod {
public static void main(String[] args) {
int local = 1;
Comparable compare = new Comparable () {
public int compareTo(Object value) {
return (Integer)value - local;
}
};
System.out.println(compare.compareTo(5));
}
}
Putting aside the fact that local isn't accessible (that's the exercise) and that Comparable isn't parameterized (oversight?) ... I have never seen this construct and had no idea it was even possible.
Is it done this way to avoid extending Comparable for the whole class?
If so, why? Is it that much easier/readable/something else?
Can this type of anonymous class be written for any interface?
It allows you to use a class and override a method in a specific case where the usage is isolated and/or relies on access to local variables.
Whether it is easier or not is somewhat subject and down to personal taste. However it means everything is in situé in your code which enables you to understand what is happening without having to browse to another file or another location in your file. In simple cases, like the above, that is generally easier to work with than having to jump around your codebase.
For local to be accessible it would need to be declared final.
To answer your questions specifically:
No; it is anonymously extending another class, thus equivalent to defining a class that extends another, so the same rules apply. You must override any abstract methods.
It is more readable because it is all in the same location as the code that requires it.
Yes, any interface or class.
It will definitely affect the scope in terms of whether or not the compare class is accessible outside of your main method.
Increased write-ability. IMHO, at the expense of read-ability. Yeah it looks simple now, but try reading a class with a lot of them. Again, a matter of opinion. How we do things is we typically start off with an anonymous or local class then promote them as the read-ability decreases. However it is great for simple callbacks. The Oracle docs provide a good statement: "Use them if you need to use a local class only once." Oracle Docs
Yes. Any interface or abstract class can be used this way.

Constructor name and class name are the same in Java. Why? [duplicate]

This question already has answers here:
Why constructors will always have same name as of class and how they are invoked implicitly?
(7 answers)
Closed 8 years ago.
Please give me a logical answer of naming a class and constructor with same name. Why we cannot choose a different name other than class name for a constructor?
class Temp
{
Temp()
{
}
};
Because this syntax does not require any new keywords. Aside from that, there is no good reason.
To minimize the number of new keywords, I didn't use an explicit syntax like this:
class X {
constructor();
destructor();
}
Instead, I chose a declaration syntax that mirrored the use of constructors.
class X {
X();
~X();
This may have been overly clever. [The Design And Evolution Of C++, 3.11.2 Constructor Notation]
Constructor name being same as class name is simply a convention. A logical one too - consider the objects could be constructed like this also
Temp t = Temp();
It might have been called constructor() but then if you are looking at only snippet you wouldn't know what is it constructing?
According to the standard which defines the C++ language, a constructor does not have a name, at least not in the sense of an identifier which becomes declared by a declaration (a declarator-id). It is an anonymous function declared with a particular syntax, and referenced only under certain circumstances by more special syntax. In other contexts, the same term Temp::Temp refers to class Temp itself.
The constructor is declared using a member declaration naming the immediate injected-class-name. It may be referenced by an injected-class-name or other type-name used with the :: punctuation (a nested-name-specifier) in the form type::type, with the last two ::-delimited parts being the same token, in particular contexts such as delegating and inheriting constructors.
The reason for all this is that you cannot take a reference to a constructor, such as to get a function pointer to it or call it without creating a new object. Constructors are intrinsically tied to object lifetimes.
Historically, constructors evolved from factory functions, which returned initialized object of a given type. This pattern, where function names may alias types and constructors are merely convention, may still be seen in some languages. The current syntax evolved from something like what you might see in JavaScript. Some early C++ compilers (thinking about THINK C, not sure about earliest versions of Cfront) did not treat constructors as members at all.

Encapsulation good practice [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Private vs. Public members in practice (how important is encapsulation?)
Recently I've been coming across a situation where I declare a class variable as public, because it will be used in another class. Someone told me recently that I should make such variables private and write a public method returning the value of the variable. I was told this was good practice. I searched through my Java book and couldnt find any reference to this. My question is, is it good practice to declare as many as possible class variables as private?
Yes. Generally, all variables should be private (not protected, private), and there should be methods to get their values (and possibly set them) if (and only if) you want to allow that by outsiders. The variables you use are an implementation detail, and usually contain data that has to be a certain way. Getters and setters allow you to take responsibility for that data, validate it, synchronize it, etc, instead of letting some jackass store random stuff in it and potentially make your object unusable.
The sole exception might be classes whose only purpose is storage of data so you can ship it around as one object, kinda like a C/C++ struct. But then, you're making a decision that no, you don't want to validate, synchonize, encapsulate that data in any way...and changing your mind later breaks binary compatibility (meaning any code that touched that class will need to be recompiled). Not a big deal in a little private project; huge deal in a public framework/API.

Categories

Resources