I have a basic question relating to the #SuppressWarnings("unused") annotation. Basically, I would like to suppress unused warnings on a block of code in my declarations section of my class. I would prefer not to suppress unused warnings on the entire class.
Currently, I am doing this:
public class MyClass {
//Constants
private final String ACCEPT = "Yes";
#SuppressWarnings("unused")
private final String DENY = "No"; //Not currently used
private final String TENTATIVE = "Maybe";
#SuppressWarnings("unused")
private final String POSTPONE = "Later"; //Not currently used
//Variables
private int counter;
....
I find the above code to be a bit messy with the annotations thrown in randomly like that. What I would like to do is something like:
//Constants
#SuppressWarnings("unused")
{
private final String ACCEPT = "Yes";
private final String DENY = "No"; //Not currently used
private final String TENTATIVE = "Maybe";
private final String POSTPONE = "Later"; //Not currently used
}
//Variables
private int counter;
....
This is, of course, illegal in Java as a block cannot be simply made like this. Its not a huge deal or anything, but I am curious if I am missing an obvious and elegant solution.
If you reeeeealy want to keep all those unused constants, a quick and dirty trick would be;
public class MyClass {
//Variables
private int counter;
#SuppressWarnings("unused")
private static final class UnusedConstants{
private final String ACCEPT = "Yes";
private final String DENY = "No";
private final String TENTATIVE = "Maybe";
private final String POSTPONE = "Later";
}
}
And i would make them static too, but your call.
EDIT:
Or, what i think is much nicer:
public class MyClass {
private enum Answer {
ACCEPT ("Yes"),
DENY ("No"),
TENTATIVE("Maybe"),
POSTPONE("Later");
private final String answer;
private Answer(String answer) {
this.answer = answer;
}
public String toString() {
return answer;
}
}
}
This way you don't get the unused warning as long as you use at least one of the values.
Related
I want to know what is the best way to use final constants in the same class? since i have to use a lot for the same class and looks very meshy, thanks.
How i can make it look more readable, since if I need to store more variables there will be many........... thanks
public class Default {
private static final String CLASS_FILE_EXTENSION = ".class";
private static final String JAVA_PACKAGE = "java.";
private static final String NO_PREFIX = "";
private static final String SUFFIX = "sfx";
private static final String TEMP_SUFFIX = "tmp";
private static final String NO_PARAMETERS = "()";
private static final String STRING_DESCRIPTOR = "Ljava/lang/String;";
private static final String RETURNS_VOID = "V";
private static final String JAR = "jar";
private static final int ONLY = 0;
private static final int BUFFER_SIZE = 1024;
private static final int PACKAGE_LOOKUP = 0x8;
private static final int BASE_VERSION = 44;
private static final Class<?> NOT_FOUND = null;
private static final URL NOT_SEALED = null;
private final TypeDescription instrumentedType;
private final TypeAttributeAppender typeAttributeAppender;
private final AsmVisitorWrapper asmVisitorWrapper;
private final ClassFileVersion classFileVersion;
private final AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy;
private final AnnotationValueFilter.Factory annotationValueFilterFactory;
private final AnnotationRetention annotationRetention;
private final Implementation.Context.Factory implementationContextFactory;
private final MethodGraph.Compiler methodGraphCompiler;
private final TypeValidation typeValidation;
private final ClassWriterStrategy classWriterStrategy;
private final LatentMatcher<? super MethodDescription> ignoredMethods;
private final List<DynamicType> auxiliaryTypes;
private final ClassFileLocator classFileLocator;
public Default(..... etc)
There is no objective answer possible for this. A few points to consider:
Having a lot of constants in one class might mean that the class is doing a lot of work. See if you can split the class into multiple classes and declare the constants as per the usage within those classes.
Since all these are private fields, see if they are really being used more than once in the same class. If not you can directly use the string rather than having a constant for that. The downside is, in the future, if you want to use it again in the same class at a different place, you have to remember to make it a constant (which is very easy to forget).
(I don't prefer this) I have seen cases where people will have an interface just for holding constants and static import them into the class to use it. That interface is like a big dumping ground for the constants.
I am pretty new in Android and I do not know how is the proper way to manage static constants. I mean, I need to use several constants (such as COMMAND_BACK = 100) in several Java classes and activities. It is not beautiful to declare them as attributes in each single activity so, what is the correct way to do this?
I though about declaring them in strings.xml, but it does not seem suitable neither...
Thanks in advance.
You can make a class like this :
public final class AppConstants {
//put all the constant here
// Eg :
public static final int SPLASH_TIME = 1000;
}
The disadvantage by declaring it in a resource.xml file is that you need a context to receive the value. This is fine as long as you need those values inside a context class otherwise you have to pass one around.
The elegant solution would be extending the Application class since the android os itself uses static fields that way.
Declare
public final class ConstantClass {
public final static int COMMAND_BACK = 100;
}
Usage
int num = ConstantClass.COMMAND_BACK;
Add a Constants class to the project
public class Constants {
public static final String STRING1 = "First String";
public static final String STRING2 = "Second String";
public static final int INTEGER1 = 1;
public static final float FLOAT1 = 0.1f;
}
// Use
textView.setText(Constants.STRING1);
Create a common interface where you can declare all the constants.Constants can further be grouped here to make it mode clean.
public interface Constants {
public interface XYZ{
public static final int A= 1;
public static final int B= 2;
}
public interface REPORT_TYPE_FLAGS{
public static final String C= "0";
public static final String D= "1";
}
}
Another elegant way is to define a constant class with other inner subclasses
`private final class Constant {
public static class TypeOne {
public static final String NAME = "Type 1";
public static final int CODE = 1;
}
public static class TypeTwo {
public static final String NAME = "Type 2";
public static final int CODE = 2;
}
}
`
And you can access it in this way
`String typeOneName = Constant.TypeOne.NAME;
int typeTwoCode = Constant.TypeTwo.CODE;
`
This question already has answers here:
Elegant alternatives for huge amount of arguments in class constructor [closed]
(4 answers)
Closed 7 years ago.
I have a client library in which I am making http remote calls to my rest service and then I am returning List<DataResponse> back to the customer who is calling our library with the response I am getting from my REST service along with any errors if there are any wrapped around DataResponse object.
public class DataResponse {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
// constructors and getters here
}
Here is my ErrorCode enum class:
public enum ErrorCode {
// enum values
private final int code;
private final String status;
private final String description;
// constructors and getters
}
And here is my StatusCode enum class:
public enum StatusCode {
SUCCESS, FAILURE;
}
As you can see in my DataResponse class I have lot of fields so basis on that I have a very long constructor and everytime when I make a DataResponse object I have a big line with new DataResponse(.......). In future I might have more fields but for now I only have these fields.
Is there any better way I can use to make a DataResponse object and then return back List<DataResponse> from my library?
Do not use the builder pattern right away. It is not for types with tons of required fields. It's for types with tons of optional fields.
Builders' required properties are specified via the constructor. You are not forced to define values using methods, which makes those values optional.
This leaves potential for your object being only partially constructed. Using a builder for this would be abuse of the design.
With that said, you should decompose your type. I'm not sure what lmd or ctime is, or really what a DataResponse is supposed to represent, so I cannot tell you in which way you should decompose. But I can tell you cohesion is what determines such.
isLink, maskInfo and idType could possibly be decomposed into a DataResponseDetails object:
class DataResponseDetails {
private boolean isLink;
private String maskInfo;
private TypeOfId idType;
public DataResponseDetails(boolean isLink, String maskInfo, TypeOfId idType) {
//...
}
}
Now your DataResponse could be composed of DataResponseDetails:
class DataResponse {
private DataResponseDetails details;
private String response;
//...
public DataResponse(DataResponseDetails details, String response, ...) {
//...
}
}
Feel your constructor requires too much still? Decompose more!
Maybe you can identify smaller logical groups of fields an move them into objects of an own class. Then you can assemble all these objects in your DataResponse objects.
As Joshua Bloch stated it in Item 2 of Effective Java 2nd Edition, you should consider using a builder pattern, as it is a best practice.
Here is what you code could look like using it :
public class DataResponse {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
// constructors and getters here
public static class Builder {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
public Builder reponse(final String response) {
this.response = response;
return this;
}
public Builder isLing(final boolean isLink) {
this.isLink = isLink;
return this;
}
public DataResponse builder() {
return new DataResponse(this);
}
...
}
private DataResponse(final Builder builder) {
this.response = builder.response;
this.isLink = builder.isLink;
}
}
and then do something as follow :
DataResponse response = new DataResponse.Builder().reponse(anyResponse).isLink(isLink).build();
I am trying to do the following redundant code - copying a Class FeedDBTableRow's object into a Feed object - where they mostly have overlapping set of variables, and I am trying to copy those common set of variables. Is there a design pattern or an annotation processor that helps me reduce these (potentially bug-prone) lines of code?
The reason for doing this basically I want to use Retrofit with GSon and Realm (and Realm due to its own construction, needs the Pojo to extend from RealmObject class, while doing this creates a GSON error - it is documented at several places)
public static Feed getFeedFromDBFeedRow(FeedDBTableRow f){
Feed x = new Feed();
x.setId(f.getId());
x.setText(f.getText());
x.setTime_created(f.getTime_created());
x.setTime_modified(f.getTime_modified());
x.setComments_count(f.getComments_count());
x.setLikes_count(f.getLikes_count());
x.setFeed_type(f.getFeed_type());
x.setObj_id(f.getObj_id());
x.setImage(f.getImage());
x.setUser_name(f.getUser_name());
x.setUser_earthmile_points(f.getUser_earthmile_points());
x.setLiked(f.isLiked());
x.setCommented(f.isCommented());
x.set_private(f.isIs_private());
x.setUrl(f.getUrl());
x.setFeed_creator_id(f.getFeed_creator_id());
return x;
}
My Feed class is:
public class Feed {
int id;
String text;
Date time_created;
Date time_modified;
int comments_count;
int likes_count;
String feed_type;
int obj_id;
String image;
String user_name;
String user_earthmile_points;
boolean liked;
boolean commented;
boolean is_private;
String url;
int feed_creator_id;
public Feed() {} // required for being Parcelable
}
And the FeedDBTableRow class is :
public class FeedDBTableRow extends RealmObject{ // having this necessity to extend RealmObject is the source of all problem, but I have to do this, hence two classes with similar composition
private int id;
private String text;
private Date time_created;
private Date time_modified;
private int comments_count;
private int likes_count;
private String feed_type;
private int obj_id;
private String image;
private String user_name;
private String user_earthmile_points;
private boolean liked;
private boolean commented;
private boolean is_private;
private String url;
private int feed_creator_id;
}
Take a look at Apache BeanUtils: http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/index.html
In particular, BeanUtils.copyProperties() might be something you find useful.
I saw sometime in the last month an implementation of Null Object pattern as what seemed like a Singleton field on a type. I can't really remember the approach though. I'm working on patterns and conscious of implementing them out of place.
From my mind I think it would be as follows but can I get a review on that?
public final class SearchCriteriaAnomalyFilter {
public static final SearchCriteriaAnomalyFilter NULL_INSTANCE;
private final T2AnomalyStatus status;
private final T2AnomalyType type;
private final boolean limitMaxOneAnomaly;
public SearchCriteriaAnomalyFilter(T2AnomalyStatus status, T2AnomalyType type,
boolean limitMaxOneAnomaly){
this.status = status;
this.type = type;
this.limitMaxOneAnomaly = Boolean.valueOf(limitMaxOneAnomaly);
}
private SearchCriteriaAnomalyFilter(){}
public static SearchCriteriaAnomalyFilter instanceOfNullObject(){
if (NULL_INSTANCE == null) {
NULL_INSTANCE = new SearchCriteriaAnomalyFilter();
}
return NULL_INSTANCE;
}
...
}
public static final SearchCriteriaAnomalyFilter NULL_INSTANCE = new SearchCriteriaAnomalyFilter();
public static SearchCriteriaAnomalyFilter instanceOfNullObject(){
return NULL_INSTANCE;
}
The rest of your code seemed fine.
The reason to use the above construct is that there is no need for a lazy initialization: the null-object won't change, nor does it need any special construction (as you properly implemented with the private constructor).