Structuring return result enums - java

I am looking for a way where I can structure java enums in an efficient / elegant way. These enums hold return results.
there are functions like "delete item" (enums: OK, DOESNT_EXIST, ACCESS_DENIED..) or create item (OK, ALREADY_EXISTS, ACCESS_DENIED..), changeItem (OK, INVALID_PARAMETER, INVALID_CLASS, ACCESS_DENIED)
As you see they have both own and shared enums. therefore some enums should be implemented in every return function (OK, ACCESS_DENIED), while others are exclusive (DOESNT_EXIST, ALREADY_EXISTS...).
also, there are complex functions like changeOrCreate where an item may be created if it does not exist and changed elsewise (enums: all createItem enums, all changeItem enums).
Basically I can
build different enums for every function (createItemResult, changeItemResult..) or
put them all into one RESULT enum class.
But whatever I choose I can never accomplish all of these
When a complex function like "changeOrCreate" fails, I want to know whether the returned enum "ACCESS_DENIED" was caused by the creation or the change.
I would highly prefer the caller of any function getting the same enumType
(I would prefer the functions no to be able to return illegal enums. e.g.: createUser shouldnt have DOESNT_EXIST)
Any ideas? Or is there any convention for return type enums?
Update:
The reason I cannot use (Non-Standard-)Exceptions is that I have to provide an API and it was a requirement that no Exceptions can be thrown.

When a complex function like "changeOrCreate" fails, I want to know whether the returned enum "ACCESS_DENIED" was caused by the creation or the change.
Then name them CREATE_DENIED and CHANGE_DENIED, or something like that.
I would highly prefer the caller of any function getting the same enumType
So do the one RESULT enum class you suggested.
I would prefer the functions no to be able to return illegal enums.
Since you're writing the functions, you control which of the enums it returns, i.e. you make sure createUser never returns DOESNT_EXIST.

It seems you're using HTTP status codes in Java, and while this can work well for your program, is not an elegant way to write Java programs.
Java has exceptions for two reasons (that I know of):
Something unexpected happened, and the program doesn't know how to handle it. What you do: Throw it to the next layer~!
Something expected happened, so you catch it, and resolve it.
Since you are expecting an exception, what this means for you is:
Create some classes for your enum-cases, like UserNotAuthorizedException, (or just use the built-in AuthenticationException), and throw those to your program.
If you want to know who didn't get access you can either select it with an argument to your exception (an ID for each use-case, the instance that failed (which can include a static type), or even a string. It's up to you), you can create a subclass...
At the end of the day, Java likes classes.

Related

How to determine if java function executed successfully

In c++, I'd usually pass a byRef variable as a parameter to the function to get the information that I need returned, and I'd return a boolean or int value from the function to determine if the function was executed successfully (no errors occurred at any point).
I can't do that in Java since you can only pass byVal, and can get one thing returned.
I guess you can return some array or list, but I feel like that's bad coding practice.
What are some proper ways to deal with this problem?
If you want to do it exactly like in c++, you can pass a primitive by reference via its wrapper-class (e.g. class Integer for primitive int). But I agree with the comments below the question that the 'proper way' of doing this in Java is to throw an exception in case of failure. In case you do not like both ideas, you can still use static variables in the class that implements the method you are executing, let them be set by that method and read by the invoking method/class, but this is no good coding practice either and should not be done unless there is no other option for whatever reasons.

Checking String parameters corresponding to field names

I'm heavily using Java.lang.Class.getField() method which requires a String variable as an argument. The problem I'm facing is when I change field names, that getField() refers to, Eclipse doesn't warn me that argument points nowhere (since it's String) and I end up having methods working improperly unnoticed.
So far I can see two ways out. It's either using try-catch blocks around every getField() call and running application to see what will be the next line to throw an exception. Fix it and watch out for the next exception. Or it's using Find/Replace feature every time I change a field name to manually look for the String value and replace it. Is there a more friendly (i.e. automatic) way to update String parameters in such cases?
Maybe there's a method (which I fail to find) that accepts a full field path as a non-String argument and returns a Field object? Something like turnToFieldObject(car.speed) returning Field object corresponding to speed field so that Eclipse would automatically check if there's such a field car.speed.
PS
First of all, thank you for your replies.
I can see that a lot of you, guys, suggest that I'm using reflection too much. That's why I feel I need to add extra explanation and would be glad to hear suggestions as well.
I'm doing a research about modeling social evolution and I need the entities to evolve new features that they don't have at the start. And it seemed to me that adding new fields to represent some evolutional changes is better understanding wise than adding new elements to arrays or collections. And the task suggests I shouldn't be able to know what feature will be evolved. That's why I rely so heavily on reflection.
AFAIK, there is no such method. You pass a reference (if it's an object) or value (if it's primitive); all data about the variables that they were originally assigned to is not available at runtime.
This is the huge downside of using reflection, and if you're "heavily" using this feature in such way, you're probably doing something wrong. Why not access the field directly, using getters and setters?
Don't get me wrong, reflection has its uses (for example, when you want to scan for fields with certain annotations and inject their values), but if you're referencing fields or methods by their name using a simple string, you could just as well access fields or methods directly. It implies that you know the field beforehand. If it's private, there is probably a reason why it's encapsulated. You're losing the content assist and refactoring possibilities by overusing reflection.
If you're modeling social evolution, I'd go with a more flexible solution. Adding new fields at runtime is (near?) impossible, so you are basically forced to implement a new class for each entity and create a new object each time the entity "evolves". That's why I suggest you to go with one of these solutions:
Use Map<String, Object> to store entities' properties. This is a very flexible solution which will allow you easily add and remove "fields" at the cost of losing their type data. Checking if the entity has a certain property will be a cheap contains call.
If you really want to stick to a million custom classes, use interfaces with getters and setters in addition to fields. For example, convert private String name to interface Named { String getName(); void setName(String name); }. This is much easier to refactor and does not rely on reflection. A class can implement as many interfaces as you want, so this is pretty much like the field solution, except it allows you to create custom getters/setters with extra logic if desperately needed. And determining if entity has a certain property is a entity instanceof MyInterface call, which is still cheaper than reflection.
I would suggest writing a method that use to get your fields supply it a string and then if the exception is thrown notify whatever needs to be notified that it was not valid and if the exception isn't caught return the field.
Although I do agree with the above that reflection should not be used heavily.

Java syntax - what does this code mean?

I am starting to learn Android programming with Java, mainly from online Android documentation. I also looked through several books but they don't seem to address this issue: a feature of Java syntax which I have come across several times and which is a mystery to me. Here is just one example from about half-way through the Contacts Provider documentation at
http://developer.android.com/guide/topics/providers/contacts-provider.html
I have removed the comments to unclutter the code snippet:
op =
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType);
This is all one statement, I think. What is confusing me is all those "dot operators" that look as though they belong in a Visual Basic "with clause". Where can I find out what all this means?
youre looking at a builder pattern, where the return value of each such with* method is the builder itself (or the object, if its not a builder exactly). theyre handly when you want to chain a lot of setters, or when there are a lot of constructors for the underlying object and you dont want people using it to get confused. or, as fge stated below, when you want the returned object to be immutable (so it cant have setters).
more specifically to your case, the return value of ContentProviderOperation.newInsert() is a ContentProviderOperation.Builder, all of who's methods return itself. usually such a chain of configuration calls will end in a call to build(), which will produce an operation.
This is an instance of so called fluent interfaces (link to wikipedia). There is noting special about it: the value returned from the previous call is being used as the target of the subsequent call.
API like this present a useful alternative to methods with lots of optional parameters, because the resulting code is much easier to read and understand. The code is somewhat more verbose, but in this case it is a good thing, because the parameters passed to constructors get better "tagging". This style is also preferable when you have multiple parameters of the same type (say, strings) next to each other, because it lets the readers avoid parameter counting.
each of those methods returns an ContentProviderOperation.Builder object that has been modified by the method. So you can chain together calls to methods like that and do everything in a more compact way. It's similar to how jQuery works in the javascript world.
It may clear things up a bit to look at the newInsert method on the Android documentation, then look at the documentation for the ContentProviderOperation.Builder class. note that all of the methods on that object also return ContentProviderOperation.Builder objects.

Should you return a passed parameter just to signal mutability in Java

I am sure this is more of a subjective question however I am curious people's oppinions...
Today at work I saw the following method....
public T execute(T dto){...return dto;}
This seemed redundant to me, in my mind this was better....
public void execute(T dto)
For now in this method lets say the following is called....
dto.setProperty(something);
But a colleague (and a few StackOverflow posts) suggest this is bad because it doesn't suggest that the method may be altering the T object. However this should be reflected on the object in the stack so why do I need a return.
Is this a valid reason, to me it seems to me this has to cause increases in overhead (although in all fairness we are using Java here)
Any insight as to which is better?
This depends on what T is, whether T is immutable, and what execute does. This question couldn't really be more generic and specifics matter.
void addPerson(Club clubFullOfPeople, Person person);
T clone(T t);
would both be valid and strike me as good design.
To answer your exact question - should you return to signal mutability? That absolutely strikes me as something that would signal IM-mutability if anything so, no, absolutely not, but you need clearer variable names, documentation etc. to communicate this.
It's not an unreasonable style, it's simply a decision that should be made (project by project) - go with the style used in the working environment. Next project/job may choose differently.
Neither style implies that the DTO can or cannot be altered. In fact, if anything, the first form would rather suggested that the parameterized DTO is not being altered, but if there are changes that are being made, they will be made in the returned object.
Advantages of returning the DTO:
Calls can be chained (this may be good or bad depending on the coding style and the use of the actual methods/objects). For example jQuery is built such that just about every call can be chained.
You can return a null value or some other object/form of the DTO to signify a failure of some sorts
In your "preferred" notation, the only way you can signify a failure is via Runtime Exceptions. Without know what the execute method is supposed to accomplish, this may be okay, or may indicate a larger problem in that Exceptions are being used to handle flow control (a bad thing).
Net result? I don't think there is a "better" solution - just something that matches more what you are currently doing in your existing codebase.

Best way to name methods that returns list of objects

I have a class named ActivityLog. This class holds a list of ActivityRecords. I want to return a list of ActivityRecords by these criterias: Environment and Condition. Should the method name include the "criteria"? See example:
activityLog.allRecords();
activityLog.allRecordsBy(Environment environment);
activityLog.allRecordsBy(Condition condition);
activityLog.allRecordsBy(Condition condition, Environment environment);
or
activityLog.allRecordsByEnvironment(Environment environment);
activityLog.allRecordsByCondtion(Condition condition);
I probably think the first is better because you will read the method name and you will understand from the parameter what it does, but I may be wrong? Which is the best, or are there even better alternatives?
I could have named the methods records(), recordsBy etc. too, but I want to have a consitency through my API where you always start writing all for lists of objects so you get help from for example Intelli Sense.
I like putting the criteria in the actual method name. So I would use:
activityLog.allRecordsByEnvironment(Environment environment);
To me proper method naming expresses a small summary of what the method does. Since the parameters are included in the method signature I would not consider the parameters to be part of the actual name, therefore not placing the criteria in the name gives the user of an api incomplete information about the methods functionality. (IMO)
I applaud your effort to practice self documenting code, great practice.
I like the overloaded variant (your first example), because it communicates that the methods are all related and provide largely the same functionality, aka, you are returning records, filtered by some criteria. You will see examples of this in many open source libraries and even the SDK itself.
I'd treat it the same as static factory methods, which are named constructors. And there not only parameter says what this method does, its name itself does it. So I'd choose 2nd option.
#Bob, about names being too long - even if you would put 2 parameters into its name, it still would be ok for me. Anyway you should avoid having methods with more than 3 parameters. Following this rule will prevent your methods' names from being enormous long.
I would take the first one.
If these methods are doing the same thing or providing the same functionality then they should have the same name. But be aware of Effective Java Item 41 and 42. You've to ensure that at least one corresponding param of overloaded method are having radically different types.
The 2nd approach becomes ugly very fast with every param added. I see this in often in Broker classes at work. There are people writing methods like findByFirstnameAndLastnameAndBirthdayOrderByUgliness(blablub). No comment.
Methods in OOP represent behavior, so I would name all of them getRecords() and made them overloaded.
In my opinion, specifying criteria in the name of method looks like naming heirarchy classes like this
Car -> BMW_Car -> X5_BMW_Car

Categories