Whenever we talk about objects we have instances, methods : functions : behavior, member variable: state, like so many interchangeable words. but for "Class" till now i didnt see people who have used some other word. So is there any other word in java which can be used(or in use)(dont tell any English synonym) which i can use. while explaining my code.
EDIT: Dont invent looking at this question it should be in use which i might not know
The concept of class is related to 'universal' and all that logic (abstraction/universal against instantiation/particular) comes from Aristotle (derived from Plato) philosophy. The OOP seems to take concepts from that filosophy.
The question for me is very relevant. Here is a link from wikipedia (http://en.wikipedia.org/wiki/Aristotle#Universals_and_particulars), and if you read this resume you could understand the relations between Aristotle philosophy and OOP.
Aristotle disagreed with Plato on this point, arguing that all universals are instantiated. Aristotle argued that there are no universals that are unattached to existing things. According to Aristotle, if a universal exists, either as a particular or a relation, then there must have been, must be currently, or must be in the future, something on which the universal can be predicated. Consequently, according to Aristotle, if it is not the case that some universal can be predicated to an object that exists at some period of time, then it does not exist.
Cool ah?
I hope it helps...
Instances, methods, functions, behaviour, etc., are all English words, so I don't quite comprehend your restriction.
So, for Class: Type.
Actually, those all have slightly different meanings: A method is a function attached to a class (they are often incorrectly used interchangably), while behaviour refers at a higher level to what a function/method does.
State refers to the specific value of a variable, or of many variables combined.
To answer your question, another word for class would be object, as you said yourself.
[Edit] It appears I spoke too tongue-in-cheek. As many people have pointed out, 'object' can also refer to an instance of a class. I think your safest bet would be to use class when you mean a class, instance when you mean an instance, spade a spade etc.
Well I heard people referring to it as a blueprint (meaning that it is a definition of what kind of state and what operations an instance will provide).
I'm pretty sure that class is the best way to describe a class in Java.
It is a pretty specific idea, and any synonym will not be able to capture the full meaning of the word.
I saw many times the word Clazz used in the code to avoid the reserved word. Does that help?
Prototype?
I would suggest "Mould" to describe the role of a class
Refer to SoloLearn on google playstore.
Class is also known as Object Factory.
But FYKI, only "class" keyword is used to create a class.
Good luck
Related
I have a class which is implements the decorator pattern. I need to check whether a specific class appear in the inheritance chain. Normally, I would just use instanceof.
However, I don't have the class definition during dev time. In other words, I get the class name (as a String) at run time. In this situation, how could I check this given class name appears in the inheritance chain?
Firstly, sounds horrible. Reflection is usually a really bad idea.
Edit: As #Holger points out in the comments, dynamic checking of type hierarchies is also a really bad idea. (Shame there's more than one new language feature coming for that. Ho hum.) Even more generally, keep your type hierarchies flat. But that's a whole new kettle of fish. In my experience, it's reflection that typically (not always, Credit Suisse!) highlights and promotes confusion.
Having said that: You will, of course, need the fully qualified class name (although you could probe a sequence of packages). From there, Class.forName methods will allow you to recover the Class object (though if you are using multiple class loaders, it could get messier). Then you just need Class.isAssignableFrom.
Is it good/bad/acceptable practice to pass the current object in a method call. As in:
public class Bar{
public Bar(){}
public void foo(Baz baz){
// modify some values of baz
}
}
public class Baz{
//constructor omitted
public void method(){
Bar bar = new Bar();
bar.foo(this);
}
}
Specifically, is the line bar.foo(this) acceptable?
There's nothing wrong with that. What is NOT a good practice is to do the same inside constructors, because you would give a reference to a not-yet-completely-initialized object.
There is a sort of similar post here: Java leaking this in constructor
where they give an explanation of why the latter is a bad practice.
There's no reason not to use it, this is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.
So use it.
As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common java.lang classes, the String one, and of course I found instances of this use, for example
1084 // Argument is a String
1085 if (cs.equals(this))
1086 return true;
Look for (this in big "accepted" projects, you won't fail to find it.
Yes, but you should be careful about two things
Passing this when the object has not been constructed yet (i.e. in its constructor)
Passing this to a long-living object, that will keep the reference alive and will prevent the this object from being garbage collected.
It's perfectly normal and perfectly acceptable.
this stands for the current object. What you are doing is sytatically correct but i don't see a need of this if you are calling the method in the same class.
It is bad practice to pass the current object in a method call if there less complex alternatives to achieve the same behaviour.
By definition, a bidirectional association is created as soon as this is passed from one object to another.
To quote Refactoring, by Martin Fowler:
Change Bidirectional Association to Unidirectional (200)
Bidirectional associations are useful, but they carry a price. The
price is the added complexity of maintaining the two-way links and
ensuring that objects are properly created and removed. Bidirectional
associations are not natural for many programmers, so they often are a
source of errors
...
You should use bidirectional associations when you need to but not
when you don’t. As soon as you see a bidirectional association is no
longer pulling its weight, drop the unnecessary end.
So, theoretically, we should be hearing alarm bells when we find we need to pass this and try really hard to think of other ways to solve the problem at hand. There are, of course, times when, at last resort, it makes sense to do it.
Also it is often necessary to corrupt your design temporarily, doing 'bad practice things', during a longer term refactoring of your code for an overall improvement. (One step back, two steps forward).
In practice I have found my code has improved massively by avoiding bidirectional links like the plague.
Yes. you can use it.Its just common in programming to pass this.But there are pros and cons about using that.Still it is not hazardous to do so.
Just to add one more example where passing this is correct and follows good design: Visitor pattern. In Visitor design pattern, method accept(Visitor v) is typically implemented in a way it just calls v.visit(this).
Acceptable
Snippet from Oracle JAVA docs:
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field
is shadowed by a method or constructor parameter.
Everything in java is passed by value. But objects are NEVER passed to the method!
When java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself. Hence this is pefectly used method in java. And most commonly followed usage.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am maintaining some Java code that utilizes an interface (let's call it BunchOfConstants) to simply store an abundance of public static final Strings. Occasionally these string names change or string names are added / removed. (which causes a bit of a headache for maintanance)
The only current use for this interface is to compare to input later in a big ugly if/then construct like this:
if(BunchOfConstants.CONSTANT1.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT2.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT3.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}
...
I thought it would be more elegant to create a class that implements Iterable or even a class that stores this data in a hashMap.
I can not figure out why the original developers decided to use an interface for this design as the interface is never actually implemented anywhere. Does anyone have any input?
Would you agree that an iterable class with these members as constants would be more appropriate?
Use enums. Then get myenum.values() and then apply a for-each loop over the values.
I would consider using enums instead as constants are not type safe (e.g., they are just ints, or strings, etc.).
This (having dedicated interface for storing constants) was a fairly common way of storing constants before the era of enums. (Pre Java 5 times.) It saved you the hassle of prefixing your constants with the containing class name. I personally never really liked this practice, but this is the reason people did it.
As for what it can be replaced with:
An enum and a switch/case construct. This requires the least modification but only has modest benefits in readability. It does give you type and value safety, plus you can get warnings out of your IDE if you forget to handle a possible value (no case for it and no default block either).
A properties file. This obviously only works if you don't want to branch based on your constant values. (I.e. if your constants don't have to appear in your source code.) This is important, otherwise you'd end up with a secondary set of constants and a properties file, which is as bad as it gets.
A doSomeStuff() factory. For this you have to wrap your doSomeStuff() implementations in separate operation classes and you can configure your factory either statically or from a properties file. (via a constant value->operation class mapping). This is the most "enterprisey" solution, which means that although it looks nice and is very flexible, a lot of the time it is an overkill.
I think this is a good candidate for enum
Well, this looks like the Constant Interface antipattern and maybe should not be used. Using an enum might be a way as suggested, or at least using a final class with private constructor.
If you want to have different implementations for doSomeStuff based on the input string, you might also consider using the strategy pattern, i.e. have a Map<String, Strategy> and then lookup the strategy for whatImLookingFor. If you found the strategy, execute its doSomeStuff, otherwise handle the "not found" case.
I would suggest you to use a property file to store all your constants. This way you can load your properties into a HashMap as you suggest in your question.
Note that property support is brought natively with java: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html
Well, enums are the way to go ... but if the 'dosomestuff' is semantically dependent upon the specific value then why not add a 'dosomestuff' method to the enum itself. That is one that this is really great about Java enums - they are not merely data but as all good objects they have semantics. Then you just loop over the enums invoking dosomestuff(whatIamLookingFor) and whatever happens happens.
Hard to say.
Yes, I agree, that it will be more elegant - at least for you. But think, what the next programmer will think about it. It will be even more complicated.
Previously mentioned strategy pattern and java's enum are definitely better solution, but since you are maintaining this code, I'm not sure if your boss will be happy with time consuming refactoring. My advice would be to use enums - not so big code change.
In my answer from yesterday I called the following piece of code "a hack":
final class MyMap extends HashMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier> {}
// declared MyMap as an alias for readability purposes only
MyMap a = new MyMap();
a.put("key", "val");
Giving it another thought, this does not seem like a bad idea at all, but I might be missing something. Are there any potholes I missed out on? Is this an acceptable (possibly creative) way for declaring aliases in Java?
The drawback would be that you won't be able to directly use any methods that return a correctly typed Map, because they will never return a MyMap. Even if they could return a Map<SomeSuperLongIdentifier, OtherSuperLongIdentifier>.
For example you wouldn't be able to use the filter() methods in Maps (provided by Google Collections). They would accept a MyMap instance as input, but they would return only a Map<SomeSuperLongIdentifier, OtherSuperLongIdentifier>.
This problem can be somewhat reduced, by writing your MyMap to delegate to another Map implementation. Then you could pass the return value of such a method into the constructor and still have a MyMap (without copying, even). The default constructor could just set the delegate to a new HashMap instance, so the default usage would stay the same.
I would object to the name MyMap: Since you create an alias, make it document its purpose by giving it a useful name. Other than that, I like it.
I think it surely a convenient way to declare type synonyms. Some languages have direct support for that (in Delphi (pascal), for example, you can do that like that:
type MyMap = HashMap<SomeSuperLongIdentifier, OtherSuperLongIdentifier>;
Since Java does not, I think you can use inheritance for that. You need to document, that this declaration is just a synonym and noone should add meethods to this class. Note also, that this consumes a little memory for VMT storage.
I personally would not do this, and would flag it in a review, but this is a matter of opinion.
Google Collections helps mitigate this problem, by letting you declare:
Map<SomeSuperLongIdentifier, OtherSuperLongIdentifier> a = Maps.newHashMap();
I'd look for ways to refactor code to not have to declare so many instances of this Map, perhaps.
As long as developers using your code have IDEs and are able to quickly jump to the class definition and read the comments for its purpose (which are in place, no?), I can see nothing wrong with it.
I wouldn't call it an 'alias'. It isn't. It can't be used interchangeably with the type it is supposed to be aliasing. So if that's the intention, it fails.
I think that inheritance is a very big gun compared to the problem at hand. At the very least I would have made this "alias class" final, with a big fat comment describing the reason for its existence.
Well, there are two contradictory aspects here.
On a modelling point of view, your declaration is right, because it emphasizes the encapsulation your class provides.
On a coding point of view, your declaration may be considered as wrong because you add a class only as a modelling support, with absolutely no added feature.
However, I find your approach quite right (although I never though about it before), since it provides a much appreciated (well, to me, at least) compilable model : classes from your model are perfectly reflected in your code, making your specifications executable, what is very cool.
All this brings me to say it's definitely a great idea, provided you support it with documentation.
I wouldn't call it a hack. Personally, I've created an alias for the purpose of declaring generic type parameters which cannot be changed and creating some clarity.
You also couldn't use this map in serialization if sending to another jvm which does not have your MyMap class.
One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a this. For example: this.process(this.event).
A few of my students commented on this, and I'm wondering if I am teaching bad habits.
My rationale is:
Makes code more readable — Easier to distinguish fields from local variables.
Makes it easier to distinguish standard calls from static calls (especially in Java)
Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.
Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?
Note: I turned it into a CW since there really isn't a correct answer.
I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see "this" is when it is required, for example:
this.fieldName = fieldName
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m_fieldName" or "_fieldName"
This is a very subjective thing. Microsoft StyleCop has a rule requiring the this. qualifier (though it's C# related). Some people use underscore, some use weird hungarian notations. I personally qualify members with this. even if it's not explicitly required to avoid confusion, because there are cases when it can make one's code a bit more readable.
You may also want to check out this question:
What kind of prefix do you use for member variables?
I'd never seen this style until I joined my current employer. The first time I saw it I thought "this idiot has no idea and Java/OO languages generally are not his strong suit", but it turns out that it's a regularly-occurring affliction here and is mandatory style on a couple of projects, although these projects also use the
if (0 == someValue)
{
....
}
approach to doing conditionals, i.e. placing the constant first in the test so that you don't run the risk of writing
if (someValue = 0)
by accident - a common problem for C coders who ignore their compiler warnings. Thing is, in Java the above is simply invalid code and will be chucked out by the compiler, so they're actually making their code less intuitive for no benefit whatsoever.
For me, therefore, far from showing "the author is coding with a dedicated thought process", these things strike me as more likely to come from the kind of person who just sticks to the rules someone else told them once without questioning them or knowing the reasons for the rules in the first place (and therefore where the rules shouldn't apply).
The reasons I've heard mainly boil down to "it's best practice" usually citing Josh Bloch's Effective Java which has a huge influence here. In fact, however, Bloch doesn't even use it where even I think he probably should have to aid readability! Once again, it seems to be more the kind of thing being done by people who are told to do it and don't know why!
Personally, I'm inclined to agree more with what Bruce Eckel says in Thinking in Java (3rd and 4th editions):
'Some people will obsessively put this in front of every method call and field reference, arguing that it makes it "clearer and more explicit." Don't do it. There's a reason that we use high-level languages: They do things for us. If you put this in when it's not necessary, you will confuse and annoy everyone who reads your code, since all the rest of the code they've read won't use this everywhere. People expect this to be used only when it is necessary. Following a consistent and straightforward coding style saves time and money.'
footnote, p169, Thinking in Java, 4th edition
Quite. Less is more, people.
3 Reasons ( Nomex suit ON)
1) Standardization
2) Readability
3) IDE
1) The biggie Not part of Sun Java code style.
(No need to have any other styles for Java.)
So don't do it ( in Java.)
This is part of the blue collar Java thing: it's always the same everywhere.
2) Readability
If you want this.to have this.this in front of every this.other this.word; do you really this.think it improves this.readability?
If there are too many methods or variable in a class for you to know if it's a member or not... refactor.
You only have member variables and you don't have global variables or functions in Java. ( In other langunages you can have pointers, array overrun, unchecked exceptions and global variables too; enjoy.)
If you want to tell if the method is in your classes parent class or not...
remember to put #Override on your declarations and let the compiler tell you if you don't override correctly. super.xxxx() is standard style in Java if you want to call a parent method, otherwise leave it out.
3) IDE
Anyone writing code without an IDE that understands the language and gives an outline on the sidebar can do so on their own nickel. Realizing that if it aint' language sensitive, you're trapped in the 1950's. Without a GUI: Trapped in the 50's.
Any decent IDE or editor will tell you where a function/variable is from. Even the original VI (<64kb) will do this with CTags. There is just no excuse for using crappy tools. Good ones are given away for free!.
Sometimes I do like writing classes like this:
class SomeClass{
int x;
int y;
SomeClass(int x, int y){
this.x = x
this.y = y
}
}
This makes it easier to tell what argument is setting what member.
More readable, I think. I do it your way for exactly the same reasons.
I find that less is more. The more needlessly verbose junk you have in your code, the more problems people are going to have maintaining it. That said, having clear and consistent behavior is also important.
In my opinion you are making it more readable. It lets potential future troubleshooters know for a fact where the function you are calling is.
Second, it is not impossible to have a function with the exact same name global or from some namespace that that gets "using"'ed into conflict. So if there is a conflict the original code author will know for certain which function they are calling.
Granted that if there are namespace conflicts some other rule of clean coding is being broken, but nobody is perfect. So I feel that any rule that does not impede productivity, has the potential to reduce errors(however minuscule a potential), and could make a future troubleshooters goal easier, is a good rule.
There is a good technical reason to prefer to use or avoid this - the two are not always equivalent.
Consider the following code:
int f();
template <typename T>
struct A
{
int f();
};
template <typename T>
struct B : A<T>
{
int g()
{
return f();
return this->f();
}
};
Now, there are two f() calls in B<T>::g(). One would expect it to call A<T>::f(), but only the second one will. The first will call ::f(). The reason behind this is that because A<T> is dependent on T, the lookup does not normally find it. this, by being a pointer to B<T>, is also dependent on T however, so if you use it, the lookup will be delayed until after B<T> is instantiated.
Note that this behavior may not be present on some compilers (specifically, MSVC) which do not implement two-phase name lookup, but nonetheless it is the correct behavior.
Python folks do it all the time and almost all of them prefer it. They spell it 'self' instead of 'this'. There are ways around it putting explicit 'self' in, but the consensus is that explicit 'self' is essential to understanding the class method.
I have to join the 'include this' camp here; I don't do it consistently, but from a maintenance standpoint the benefits are obvious. If the maintainer doesn't use an IDE for whatever reason and therefore doesn't have member fields and methods specially highlighted, then they're in for a world of scrolling pain.
I use this for at least two reasons:
Fallacies reasons
I like to have consistent code styles when coding in C++, C, Java, C# or JavaScript. I keep myself using the same coding style, mostly inspired from java, but inspired by the other languages.
I like also to keep a coherence inside my code in one language. I use typename for template type parameters, instead of class, and I never play mixer with the two. This means that I hate it when having to add this at one point, but avoid it altogether.
My code is rather verbous. My method names can be long (or not). But they always use full names, and never compacted names (i.e. getNumber(), not getNbr()).
These reasons are not good enough from a technical viewpoint, but still, this is my coding way, and even if they do no (much) good, they do no (much) evil. In fact, in the codebase I work on there are more than enough historical anti-patterns wrote by others to let them question my coding style.
By the time they'll learn writing "exception" or "class", I'll think about all this, again...
Real reasons
While I appreciate the work of the compiler, there are some ambiguities I'd like to make UN-ambiguities.
For example, I (almost) never use using namespace MyNamespace. I either use the full namespace, or use a three-letters alias. I don't like ambiguities, and don't like it when the compiler suddenly tells me there are too functions "print" colliding together.
This is the reason I prefix Win32 functions by the global namespace, i.e. always write ::GetLastError() instead of GetLastError().
This goes the same way for this. When I use this, I consciously restrict the freedom of the compiler to search for an alternative symbol if it did not find the real one. This means methods, as well as member variables.
This could apparently be used as an argument against method overloading, perhaps. But this would only be apparent. If I write overloaded methods, I want the compiler to resolve the ambiguity at compile time. If a do not write the this keyword, it's not because I want to compiler to use another symbol than the one I had in mind (like a function instead of a method, or whatever).
My Conclusion?
All in all, this problem is mostly of style, and with genuine technical reasons. I won't want the death of someone not writing this.
As for Bruce Eckel's quote from his "Thinking Java"... I was not really impressed by the biased comparisons Java/C++ he keeps doing in his book (and the absence of comparison with C#, strangely), so his personal viewpoint about this, done in a footnote... Well...
Not a bad habit at all. I don't do it myself, but it's always a plus when I notice that someone else does it in a code review. It's a sign of quality and readability that shows the author is coding with a dedicated thought process, not just hacking away.
I would argue that what matters most is consistency. There are reasonable arguments for and against, so it's mostly a matter of taste when considering which approach.
"Readability"
I have found useful the use "this" specially when not using an IDE ( small quick programs )
Whem my class is large enough as to delegate some methods to a new class, replacing "this" with "otherRef" it's very easy with the most simple text editor.
ie
//Before
this.calculateMass();
this.perfornmDengerAction();
this.var = ...
this.other = ...
After the "refactor"
// after
this.calculateMass();
riskDouble.calculateMass();
riskDouble.setVar(...);
this.other = ...
When I use an IDE I don't usually use it. But I think that it makes you thing in a more OO way than just use the method.
class Employee {
void someMethod(){
// "this" shows somethings odd here.
this.openConnectino() ; // uh? Why an employee has a connection???
// After refactor, time to delegate.
this.database.connect(); // mmhh an employee might have a DB.. well..
}
... etc....
}
The most important as always is that if a development team decides to use it or not, that decision is respected.
From a .Net perspective, some of the code analysis tools I used saw the "this" and immediately concluded the method could not be static. It may be something to test with Java but if it does the same there, you could be missing some performance enhancements.
I used to always use this... Then a coworker pointed out to me that in general we strive to reduce unnecessary code, so shouldn't that rule apply here as well?
If you are going to remove the need to add this. in front of member variables, static analysis tools such as checkstyle can be invaluable in detecting cases where member variables hide fields. By removing such cases you can remove the need to use this in the first place. That being said I prefer to ignore these warnings in the case of constructors and setters rather than having to come up with new names for the method parameters :).
With respect to static variables I find that most decent IDEs will highlight these so that you can tell them apart. It also pays to use a naming convention for things like static constants. Static analysis tools can help here by enforcing the naming conventions.
I find that there is seldom any confusion with static methods as the method signatures are often different enough to make any further differentiation unnecessary.
I prefer the local assignment mode described above, but not for local method calls. And I agree with the 'consistency is the most important aspect' sentiments. I find this.something more readable, but I find consistent coding even more readable.
public void setFoo(String foo) {
this.foo = foo; //member assignment
}
public doSomething() {
doThat(); //member method
}
I have colleagues who prefer:
public void setFoo(String foo) {
_foo = foo;
}
less readable unless of course your students are still on green screen terminals like the students here... the elite have syntax highighting.
i just heard a rumour also that they have refactoring tools too, which means you don't need "this." for search and replace, and they can remove those pesky redundant thisses with a single keypress. apparently these tools can even split up methods so they're nice and short like they should have been to begin with, most of the time, and then it's obvious even to a green-screener which vars are fields.