Making a code more readable - java

I have two classes in my app with identicall names, I cannot rename them, on of them is from packageA second from packageB, the name of this class is State, and I have to use it in one place in my program like this:
Map<Integer,Set<org.omg.PortableServer.POAManagerPackage.State>>
is there any way (but using this class) to make this somewhat more readable(to shorten it somewhat)?

Possibly derive from one of the classes to disambiguate. For example, in POAState.java:
import org.omg.PortableServer.POAManagerPackage.State;
public class POAState extends State {}
then:
Map<Integer,Set<POAState>> my_map;

Create wrapping class that will have only Set<org.omg.PortableServer.POAManagerPackage.State> and all the needed Set methods.
usage in client:
Map<Integer,GoodWrappingSetName>

If you use the two different State classes in the same piece of code (*.java file), then the answer is "No", Java does not provide a short hand notation. You must be explicit and include the full package names to remove the ambiguity.
#dantuch has raised an interesting idea, but rather than wrap the class, if you can extend one of them, you can create an empty sub-class of State that simply defers all of it's implementation to the parent class.
public MyState extends State {
// no implementation required
}
Then you can then refer to MyState

Related

Subclass contained in parent class

Looking through some source code for a Settings App I found something that ressembles what you see below, where there are child classes of a class mentioned within the original class. These classes are not abstract and have no body.
public class mySettings extends PreferenceActivity {
...
//Class definition
...
public static class myColorSettings extends mySettings {/*empty*/ }
public static class myConnectSettings extends mySettings {/*empty*/}
}
In the actual app, there are buttons "My Color" and "My Connect" that each open up new activities (or fragments if the screen is dual pane).
So I have two questions: what is the use of declaring subclasses within a class itself - from an Object Oriented programming point of view - as shown above?
And my second question is, if the classes are clearly empty and not abstract, but the end result is not empty, what is the use of these empty declarations?
EDIT 1
As pointed out in the comment, the Android repo has a nearly identical setup. See the link http://tinyurl.com/nbkv7zg
(around line 1070)
Here is Oracle's answer to your first question:
Why Use Nested Classes?
Compelling reasons for using nested classes include the following:
•It is a way of logically grouping classes that are only used in one
place: If a class is useful to only one other class, then it is
logical to embed it in that class and keep the two together. Nesting
such "helper classes" makes their package more streamlined.
•It increases encapsulation: Consider two top-level classes, A and B,
where B needs access to members of A that would otherwise be declared
private. By hiding class B within class A, A's members can be declared
private and B can access them. In addition, B itself can be hidden
from the outside world.
•It can lead to more readable and maintainable code: Nesting small
classes within top-level classes places the code closer to where it is
used.
Source: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Without seeing the rest of the project's code, my best guess would be that those two classes, although empty, must be declared as required by some part of the PreferenceActivity parent class.
I'd call this generally a bad design.
Nested classes may be used as alternative to organizing them in a package, especially when their use is limited to or make only sense in the context of the containing class. If they are used outside, refactor them out.
As both classes are obviously empty, they are a complete waste and could be removed. Instead, each instance of the parent class could be used in a different role
mySettings colorSettings = new mySettings();
mySettings connectSettings = new mySettings();
Btw. starting the name of a class with lower case is a bad practice

Extending a class vs. adding boolean parameter

When writing a program in Java, if I have a special case of an object that needs to be treated differently by the main class but that does not require any additional methods, is it better to add a boolean parameter to the constructor of the object such as isSpecial and to check whether the object is special in the main class or to create a new object that extends the original?
Example:
I have a Cat class. If a cat has whiskers, I want to print "This cat has whiskers!" in the Main class.
Would it be better to have a WhiskerCat class or to simply add a boolean parameter to the Cat constructor such as hasWhiskers?
Simply add the boolean parameter. You don't want to end up with an excess of classes that do roughly the same thing. For example, in the Cat class, the default value for hasWhiskers should be false, and remain false if they don't call the constructor that explicitly requires them to specify it. Then you can have a hasWhiskers() method that returns this boolean attribute.
In general, only extend a class if the new class has additional functionality (additional methods etc) that cannot simply be tacked on to the original.
It's a problem of responsibilities: which class is doing what?
Your "main" class should not probably be aware of the internals of the "Cat" class.
In your case that means the implementation of the Cat class would probably need to be adjusted to either have a new interface that the main class could use to print that message.
Then the Cat class itself could either have that boolean, a (list of) component that make up the cat or you could go the inheritance way. This will most likely depend on the real problem: is there many more variations? is that really the only difference? are you taking a class/exam? (in the last case it might be more useful to just apply the way you've been taught).
I think the problems are about design patterns instead of coding style.
In general,if you want to add some new features in a class.
First,you should ask yourself is it a interface or a property?If it is a property,then there are two ways to tackle it.
Way 1:subclass as you metioned
Way 2:you should use delegate (i.e. add a hairclass to consider whether it is a long hair cat
or it is short hair cat.)
Just wondering, is adding a boolean the only way to recognize if the object is special? For sure there must be other characteristics that make it special?
Anyway, it's not the responsibility of the main class to know if it is. Leave what should be printed to the Cat class, not on the Main class.
In my opinion it depends on how special that attribute is.
If we consider another example:
cars...
The attribute 'sunroof' or 'navi' is quite common and has no special requirement to the car and may be part of the base class.
But a siren and flash light are quite uncommon and would be better fit if they are attributes of another extended class.

Understanding the difference between extending a class and importing a class [duplicate]

This question already has answers here:
What's the difference between importing and extending a class?
(10 answers)
Closed 7 years ago.
I have seen several threads that define extending a class as a way for a personalized class to inherit the methods of the class that it is extended to. When you import a class and create an instance of that class you have access to its methods, can someone please explain to me how extending a class to provide those methods to your own class is effectively different, in other words, the only difference I see is that when you import you create an instance of a standardized class, and when you extend you effectively turn your personalized class into the standardized class only with a different name. I am aware I am wrong, but the answers I have read have failed to help me fundamentally understand the difference.
Importing and extending are two very different things.
Importing
Classes are organized in packages, which provide a namespace facility that avoids name conflicts. Importing allows you to use the class in your code without the namespace information.
Importing is optional. You never have to import anything if you always use the fully qualified name of the class, but that makes your code hard to read.
If you want to make a list of Calendar objects, for example, you either import java.util.List, java.util.ArrayList and java.util.Calendar and use:
List<Calendar> array = new ArrayList<>();
Or import nothing and use:
java.util.List<java.util.Calendar> array = new java.util.ArrayList<>();
Sometimes you have two classes with the same name in different packages. In that case, if you use both of them in your code you can't import both. You will have to refer to one of them by their fully qualified name. For example:
List<java.awt.List> array; // you have to import java.util.List, but can't also import java.awt.List
Extending
When you extend in Java you are saying that the subclass is a type of the original class. That's the most important aspect you have to be aware of when using extends. Is you say Bus extends Vehicle you are saying that Bus is a Vehicle. You not only inherit all the non-private methods and fields of the superclass, but also can use the subclass anywhere you could legally use the superclass. For example, if you have this method:
public park(Vehicle v) {
v.drive();
v.turn(Direction.LEFT);
v.stop();
}
you could pass a Bus as an argument, because Bus is a Vehicle.
parkingLot.park(new Bus());
and the drive(), turn() and stop() methods will be called in the Bus. That is polymorphism.
Although you inherit methods, inheritance is not the best way to reuse code. Most of the time when you need to reuse code you can do it by using composition (making your class have a reference to another class, instead of being one). A Car shouldn't extend Motor because a car is not a motor, but it could have a motor and delegate a call to the motor's turnOn() method when the car's drive() method is called.
You can also have polymorphism without inheritance in Java using interfaces.
To make a simple example (but bad :/ ). Lets say you have a Person class.
public Person
{
int age;
string name;
}
Then you have different type of persons that inherit the Person class, eg.
public SoftwareDeveloper extends Person
{
string codingLanguage;
}
Now you can easily create a SoftwareDeveloper and use its attributes like this:
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.name);
}
If you would "import" instead, you would have to create an instance of Person in SoftwareDevelopers constructor and make it public. So your code would be to access the attribute:
public SoftwareDeveloper
{
public Person person;
string codingLanguage;
public SoftwareDeveloper(){
person = new Person();
}
}
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.person.name);
}
I think in small scale your reasoning works fine but the idea of extending is that your class inherits all the methods of the extended class.
But if you start with a simple idea or program and want to expand it massively the use of instantiating all the classes you need becomes much more consuming. On even a simple idea the increase in imports can explode.
Example:
Animal - warm blooded - biped - human
Animal - warm blooded - quadruped - feline - cougar - panther
Now you want to have your panther have all the methods of the 5 classes its built apoun.
So that 5 imports and objects you have to manipulate to get to all the methods you want to access. But if all these are extending each other you just have direct access to the methods. And this is a simple example now imagine a huge accounting program.
So point I trying to make....I think...Is that its much more prevalent and easier to understand the usefulness in extending classes when you look at it in the large scale.
Hope this helps or makes as much sense as it does to me.
Extending a class means that your class is "inheriting" the methods of the standard class; in other words, you are taking an existing class and building your class on top of it. That is how Java manages all objects (i.e. every class that you create actually extends the default Object class). When you import a class, on the other hand, you have access to all its functionality, but you cannot build on top of it as you could with inheritance.
Let's start with importing a class. You import a class in order to use it in another class, if that class is in another package. It's really just a shortcut that's saying when you see a class called X used, what I really mean if com.somepackage.X.
Extending is taking a class and using it as a base for a new class. There's alsorts of reasons to do this (well beyond the scope of an answer here) but the important thing is that you inherit the behaviour of the class you are extending and have the choice of whether or not to override that behaviour or add additional behaviour.
For good example of classes being extended, look at the Collection API in java.util where you can see java.util.AbstractList is extended to ultimately create two different types of list, each with different characteristics - java.util.ArrayList and java.util.LinkedList.
Lets look on an example.
We have class which provide an update function to database and containing a String variable.
public class DBupdate {
public String StrVar = "Hello";
...
public void doUpdate(String expression) {
try {
connect();
runExp(expression);
disconnect();
} catch ...
}
}
If you import it. You will do something like
log(new DBupdate.StrVar);
String myExp = "UPDATE ..."; // SQL
new DBupdate.doUpdate(myExp);
If you extend.
log(StrVar);
String myExp = "UPDATE ..."; // SQL
doUpdate(myExp);
doUpdate() function and StrVar became part of your new class. So all functions and variables (which are public or protected) are part of your new class (inherited).
Example for usefull import (and not extend/inherit) is log4j. It is doing work like writing to console and into a file. But you want just to use it "log" function and no speacial functions it is using for its work.
Example for usefull inherit is java.lang.Thread. If you class became a thread it can be treated as a Thread and will be splitted to run parallel, if you use java.lang.Thread function "start()". (Override run() method to do so some stuff...)
At the very simplest case it can be said that, Import Statement improves readability and reduces the length of the code.
In java we implement dynamic loading, language import statement no class file is loaded at the time of import statement, when ever we are suing a class, at the time of only the corresponding .calss file will be loaded.
Extends-
In Java, when we wish to extend the usefulness of a class, we can create a new class that inherits the attributes and methods of another. We don't need a copy of the original source code (as is the case with many other languages) to extend the usefulness of a library. We simply need a compiled '.class' file, from which we can create a new enhancement. I could not find a better way to explain so just refer this link..(source -http://www.javacoffeebreak.com/java104/java104.html)

Can you name an abstract class Object?

Considering everything is object oriented etc, so names have to describe the object and what it is, I have an abstract class that sub classes inherit from. These are all objects on the screen (it's a game), i.e, player, and a weight (trapezoid weight). I have it currently named Character but it doesn't seem fitting as the weight is not a Character itself, it only inherits properties from Character.
Could I call this class "Object" without it breaking conventions? - could someone come up with a more appropriate name?
Technically, you could - but it's a very, very bad idea, so don't.
Longer explanation: The Object class already in Java is java.lang.Object - so there's no technical reason why you could create another Object class in another package, just as you could create another String class in another package. (Actually, technically speaking you could even create your own java.lang.Object, but I'm not even going to go there!)
However:
Could I call this class "Object" without it breaking conventions?
Without breaking convention? Not in the slightest. You should never duplicate such commonly used class names elsewhere, especially those in java.lang. It would be considered incredibly bad code design.
In terms of a better name, Actor or Sprite may be two good alternatives.
Java's Object class is part of the java.lang package which is automatically imported for every class file. If you name your class Object and forget to explicitly import it in other classes, you will have issues, thinking you're using com.custom.Object (your class), but actually using java.lang.Object, the JDK's.
Use a more descriptive name, ApplicationObject.
Yes you can. The class beside the name has the path that is package.
package org.stackoverflow
public class Object {
}
By default java.lang is prohibited package name so you can not do declare
package java.lang
public class Object {
}
The class names does not have to be unique in scope of whole world. Using the class path you are able to override the JVM definition of class.

Non-public top level class in Java

What's the reason of making top-level class non-public in Java?
Let's say we have Foo.java, there could be
class Foo {
}
or
public class Foo {
}
I understand that there will be some class - visibility issues with the former example (probably it won't be visible from other packages). But anyway, are there any reasons why someone may want to do as in the first code sample?
UPD: What cons I see in the former solution: nobody cares that it's non-public. That class can be simply extended by some other public class in the same package later, then, non-public part of the class may bring you visibility/access issues.
Here is an example.
No one needs to know about existence of our ConcreteDocument.
DocumentIF.java
public interface DocumentIF {
}
ConcreteDocument.java
class ConcreteDocument implements DocumentIF {
}
DocumentFactory.java
public class DocumentFactory {
public DocumentIF createDocument() {
return new ConcreteDocument();
}
}
Typically, you make a class package-private because you don't want the class to be used outside the package. When a top-level class isn't public, it's private to the package.
Say you have a package with a number of classes that must communicate the same sort of data with one another. But this data structure is an implementation detail and so you don't want it being used by user code. Making the transfer class package private maintains this sort of package level encapsulation.
I understand that there will be some class - visibility issues with the former example (probably it won't be visible from other packages).
That seems to me to be reason enough to use it if you want to keep the class private to that one package.
Just noticed another use! It seems you can only have one public top-level class per code file, but any number of non-public top-level classes. Haven't verified it personally, but if true that could be quite useful to prevent cluttering your project folder and to group classes with related functionality that aren't needed outside of the package.
Classes without a public or protected modifier are only visible inside the package they reside. If you think of components and interfaces there is a reason for leaving out the public modifier. Let's say you have a public class MyCompontent that internally uses other classes, but does not want to publish those to the outside world (users of the component) it makes sense to leave out the visibility modifier.
It is considered good design to keep the visibility of a class to the most minimum required. The reasons that I can think of:
The class can easily change in the future without causing breakages in external packages as the external packages do not have access to the class. In this regard it might be even better to start off a class by making it a private inner class.
The class being package visible cannot be extended by classes in external packages. This again makes it easier for this class to change without causing breaking changes in external packages. If this class was not meant to be extended then it would be even better to make this final.
A public visible class becomes a part of the exported API of your library. If you are a library designer, it is better to keep your exported API as small as possible because you do not want to confuse your consumer with un-necessary classes/details. Item 1 would again hold good in this case.
The book "Effective Java" by Josh Bloch is an excellent reference for Idiomatic Java code and design.

Categories