I need to check if the object entity satisfies certain rules. My object is a phone call, I need to check if it satisfies certain criteria or not to proceed with later logic. Please, find my solution below.
private static boolean isGPRS(CallXCD callXCD){
String serviceName = callXCD.getServiceName();
boolean isGPRS = false;
if(serviceName.compareTo("GPRSB")==0)
isGPRS = true;
return isGPRS;
}
private static boolean isVoice(CallXCD callXCD){
String serviceName = callXCD.getServiceName();
boolean isVoice = false;
if(serviceName.compareTo("TEL")==0)
isVoice = true;
return isVoice;
}
Then I will check if isGPRS returns true, I will do X. If isVoice returns true, I will do Y. I am not sure if what I did was the best practice because I pass the same object several times.
Is it better to build an array of booleans and pass the object one time in one method, do all calculations then pass the values to the boolean array. Or wouldn't it make any difference on performance?
None of this will make any measurable difference. Such trivial things won't affect performance in a way that you'll be able to tell.
I'd wonder why you have to do this at all. Why static methods? Why not make those members of the CallXCD class and let it simply tell you what kind of thing it is? Keep all the state and logic encapsulated in one place.
Why are you testing types this way? Could this be polymorphic? Object-oriented programming was born to eliminate this kind of "what am I?" if/then/else code.
Related
I'm trying to program a board for a game. The board has 25 fields, and each field can either contain a base or 4 different sizes of rings.
public class Field {
private Base base;
private Ring[] rings;
public Object getPieces() {
if (base == null) {
return rings;
} else {
return base;
}
}
}
I programmed the setter methods so that a Base only can be set if rings is null, and that a Ring only can be set if base is null.
The problem is that in order to paint the board, my view needs the contents of Field, which is either a Base or a Ring[]. I find it hard, however, to allow the method to return both types. Right now, I'm returning the contents as Object, but this is bad practice.
Is there any way in which I can allow my method to return both types?
If not, is there a way in which I can store my pieces more efficiently that allows me to return them as one type?
Also, Base and Ring both extends the same superclass Piece, so I could return them as pieces instead, but then I would still have the problem that one of the two return types is an array where the other is not.
You could return an array of pieces. If you need to return only the base, then you just put it inside an array of pieces which will be the only element. Otherwise you return the array or rings.
So, your method will be like this:
public Piece[] getPieces() {
Piece [] toReturn;
if (base == null) {
toReturn = rings;
} else {
toReturn = new Piece[]{base};
}
return toReturn;
}
Consider that if you implemented new methods in the Base or Ring classes, then those methods canĀ“t be called because you defined that the objets inside the array are from the Piece class, unless you make a cast - if the array has only one element it is a Base, otherwise is a Ring. This is like an implicit instanceOf, so be very carefull. The use of instanceOf should make you check if there is a better way of solving the problem!
You need to work out what you want to do with the things that this method returns and then create a superclass for them. This may be the Piece class, but it could be a Drawable or something else. Without knowing what you are doing it is hard to give a real answer.
As to your array or object you have two options. Again what is right for you is hard to give based on the information given. Either the getPieces can a collection of some sort regardless (array, List, Set etc) even if it is a collection of one, or your Piece (or Drawable or what ever) could work regardless of if what backs it is a single Piece or a collection of Pieces.
You should be attempting to encapsulate the logic rather than just handing things out willy-nilly. Again I don't know your application, but say in the case of a Bank rather than have a getBalance and setBalance you have a deposit, withdraw and display(onThis).
In the class where you are calling your getter, you could try using the instanceOf
Field field = new Field();
Object returnObject = field.getPieces();
if(returnObject instanceOf Base){
// add to Base
} else if(returnObject instanceOf Rings){
// add to rings
}
Unless you have a strict programming guidelines, in the long run the code can end extremely long and ugly, and after some point of time you might not be able to debug the code as well. So be careful.
I would say setting null is even a more "badder" practice than methods returning Object instances. As long as you can help it, don't set anything as null.
Your architecture propably violates the Tell, Dont Ask principle: The Board asks Field for it-s internal state getPieces().
If you reformulate this to: The Board tells Field to draw itself you find out that the drawing logic should belong to Field and not to board. This way there is no more need for the board to know the implementations detail that a field may contain a base or rings.
Can I do this in java?
private static boolean isRight(){
return new Random.nextBolean();
}
boolean test = true;
test = test && isRight()
My question is can I use a boolean to update the same boolean like I would if it were an int or double? Is this a good programming practice or there's a better way
Yes of course you can. boolean works in the same way as any other primitive type in Java.
Note however that this is an abuse of Random: you should not reinitialise the generator every time you want to draw from it. You could keep it as a static field in the class, taking care to synchronize on its monitor to help achieve thread safety.
Note also that test will remain false once it evaluates to false.
I have a function in which I have to send two states of an object:
void functionA(MyObject objStateOff, MyObject objStateOn){
}
And there would always be only two types states: on and off
But instead of having two parameters of the same type for this function, I was hoping to combine them. SO I was thinking of having a HashMap<Boolean, MyObject>.
But since this map would at most contain only two entries, it seems to be a waste of resources, as I am developing for Android.
So, is there a better way of passing these two objects, without having two either use a HashMap or having two parameters in the function signature?
Update: I want to see if any other method would basically improve the following:
Readability, performance(even though i think that won't change) and maintainability
Thanks.
I would create a custom class with two MyObject fields, and accessors for each. This has a couple big advantages based on your goals:
Readability: The accessor methods describe what each object does. states.get(true), what does that mean? states.getFooOnState(), that's pretty clearly getting me the state for when foo is on.
Maintainability: Adding new state is much easier, if you ever need to do that; you just add a new field to this class. Maybe you'll want a MyObject for when the foo's state is unknown/initializing, or maybe you want to add event handlers that get triggered when foo gets turned on or off. One disadvantage to your current approach is that these sorts of things will cascade through your signatures: functionA needs to add a new argument, which means functionB which calls functionA needs to now get that extra parameter (so it can pass it to functionA), which means functionC needs to get it, and so on.
One caveat to the readibility issue is that you'll be gaining readibility where you use these MyObjects, but not where you first set them up. There, you'll be creating a new MyObjectState (or whatever you name it), and the constructor will look just as generic as your functionA:
MyObjectState s = new MyObjectState(objStateOff, objStateOn);
You could address that by creating a builder for MyObjectState, but that'd probably be overkill.
Performance wise, you're not going to get better than what you already have. But a custom class is going to add fairly minimal overhead (in terms of extra memory, GC activity, etc) in the grand scheme of things.
There's always the Pair class (http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html). Or you could pass a MyObject[] with two elements.
I think this question doesn't have the only correct answer. Personally I would leave the function with two parameters, because that's not too much really and names of this parameters can help me to avoid confusion like "which element of map/array is for on state?".
You can always use composition.
Create a class that contains two objects of MyObject type.
It may look overkill at first, but it's safer than array.
Hope this helps.
You could use a simple ArrayList.
ArrayList<MyObject> a = new ArrayList<MyObject>();
a.add(objStateOff); a.add(objStateOn);
void functionA(ArrayList<MyObject>) {
...
}
functionA(a);
Or a simple argument logic:
void functionA(int x) {
MyObject state;
if (x == 0) {
MyObject state = objStateOff; // Supposing they were defined somewhere before.
} else if (x == 1) {
MyObject state = objStateOn;
}
if (state != null) {
// Use MyObject state.
}
}
In this way, you don't need to specify any convention, you just set the off or on right on the argument (You can use a string or a boolean instead of an int (I mean, you could use "ON" or "OFF", literally)).
if your requirement is to have two object states, then why you dont have a field in MyObject like boolean stateOfObject. Then in functionA, you can check the state and do the required logic. Why complicate by sending two objects when you have only two states? May be you have to mention the context where you are using it and why you need two objects to be passed to the functions when the object can be in only one state.
May be you could use enums:
public enum StateOfObject {
ON(10,2),
OFF(15,5);
private final int length;
private final int speed;
StateOfObject(int length, int speed) {
this.length = length;
this.speed = speed;
}
public MyObject getObject() {
MyObject myObj = new MyObject();
myObj.setLength(this.length);
myObj.setSpeed(this.speed);
return myObj;
}
}
Use it like this:
MyObject onObject = StateOfObject.ON.getObject();
System.out.print("Length: " + onObject.getLength() +
" Speed: " + onObject.getSpeed());
I encountered this problem several times, so I m asking here what is the best practice
I have process that goes true several objects, modifies them and rises some flags.
boolean erros = false;
for(MyData data: allData){
//...
//#ToDo move this to a function titleCheck()
if(data.getTitle().isEmpty()){
data.setTitle('none');
erros = true;
}
if(data.getTitle().equals('BIG')){
data.setTitle('small')
}
if(data.getTitle().equals('error')){
errors = true;
}
//...
}
I need a function to update the data and change one or more flags
so the preferred syntax is something like this:
MyData updatedData = titleCheck(MyData data, &erros){...}
but booleans cant be passed by reference so they was it works is:
boolean errors = titleCheck(MyData dataForUpdate){...}
Witch is way less intuitive .. (at least for me ... coming from PHP background)
The problem gets bigger if you have several flags to update.
So .. what is the proper Java way to handle such structure.
When you do this:
titleCheck(MyData data);
given your code above, you're actually changing the data object - not a copy of this. Hence you can return the success/failure boolean and you don't have to return the passed object. So now you can OR these values together.
boolean error = false;
error |= titleCheck(...);
error |= nameCheck(...);
etc.
If you want to pass the object and a status back, you can trivially declare a return class thus:
class ReturnResult {
public boolean error;
public MyData data;
}
(I've made the fields public since I'm using it as a simple structure). The advantage of this approach is that you're making use of OO to tie together related objects, and you can put methods on the above class to make it easy to merge successive results.
Finally I note that you're calling lots of methods on the MyData object and determining success/failure outside that object. I would rather put this within the MyData object. Then the MyData object can store its own valid/invalid state and you can ask it for its own state via an isValid() method or similar. This seems like a very OO method of doing things here.
Java doesn't support pass by reference. Even references are passed by value.
To do what you suggest you need to pass a reference to an object such as boolean[] or AtomicBoolean and use that instead.
I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java".
Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of:
Return a boolean, and pass in a StringBuilder to collect the message. This is the closest to a C-style way of doing it.
Throw an exception instead of returning false, and include the message. I don't like this since failure is not exceptional.
Create a new class called AuthenticationStatus with the boolean and the String. This seems like overkill for one small method.
Store the message in a member variable. This would introduce a potential race condition, and I don't like that it implies some state that isn't really there.
Any other suggestions?
Edit Missed this option off
Return null for success - Is this unsafe?
Edit Solution:
I went for the most OO solution and created a small AuthenticationResult class. I wouldn't do this in any other language, but I like it in Java. I also liked the suggestion
of returning an String[] since it's like the null return but safer. One advantage of the Result class is that you can have a success message with further details if required.
Returning a small object with both the boolean flag and the String inside is probably the most OO-like way of doing it, although I agree that it seems overkill for a simple case like this.
Another alternative is to always return a String, and have null (or an empty String - you choose which) indicate success. As long as the return values are clearly explained in the javadocs there shouldn't be any confusion.
You could use exceptions....
try {
AuthenticateMethod();
} catch (AuthenticateError ae) {
// Display ae.getMessage() to user..
System.out.println(ae.getMessage());
//ae.printStackTrace();
}
and then if an error occurs in your AuthenticateMethod you send a new AuthenticateError (extends Exception)
Avoid returning a "sentinel value", especially null. You will end up with a codebase where methods cannot be understood by the caller without reading the implementation. In the case of null, callers may end up with NullPointerExceptions if they forget (or don't know) that your method may return null.
The tuple suggestion from Bas Leijdekkers is a good one that I use all the time if I want to return more than one value from a method. The one we use is P2<A, B> from the Functional Java library. This kind of type is a joint union of two other types (it contains one value of each type).
Throwing Exceptions for control flow is a bit of a code smell, but checked exceptions are one way of getting more than one type of value from a method. Other, cleaner possibilities exist though.
You can have an Option<T> abstract class with two subclasses Some<T> and None<T>. This is a bit like a type-safe alternative to null, and a good way to implement partial functions (functions whose return value isn't defined for some arguments). The Functional Java library has a full-featured Option class that implements Iterable<T>, so you can do something like this:
public Option<String> authenticate(String arg) {
if (success(arg))
return Option.some("Just an example");
else
return Option.none();
}
...
for(String s : authenticate(secret)) {
privilegedMethod();
}
Alternatively, you can use a disjoint union of two types, as an Either<L, R> class. It contains one value which is either of type L or R. This class implements Iterable<T> for both L and R, so you can do something like this:
public Either<Fail, String> authenticate(String arg) {
if (success(arg))
return Either.right("Just an example");
else
return Either.left(Fail.authenticationFailure());
}
...
Either<Fail, String> auth = authenticate(secret);
for(String s : auth.rightProjection()) {
privilegedMethod();
}
for(Fail f : auth.leftProjection()) {
System.out.println("FAIL");
}
All of these classes, P2, Option, and Either are useful in a wide variety of situations.
Some more options:
Return an separate enum value for each type of failure. The enum object could contain the message
Return an int and have a separate method that looks up the appropriate message from an array
create a generic utility tuple class that can contains two values. Such a class can be useful in many more places.
simple tuple example, actual implementation may need more:
class Tuple<L, R> {
public final L left;
public final R right;
public Tuple( L left, R right) {
this.left = left;
this.right = right;
}
}
You could return a Collection of error messages, empty indicating that there were no problems. This is a refinement of your third suggestion.
I personally think creating a new class called AuthenticationStatus with the boolean and the String is the most Java like way. And while it seems like overkill (which it may well be) it seems cleaner to me and easier to understand.
Just because failed authentication is commonplace doesn't mean it isn't exceptional.
In my opinion, authentication failures are the poster-child use case for checked exceptions. (Well... maybe file non-existence is the canonical use case, but authentication failure is a close #2.)
I use the "tiny class" myself, usually with an inner class. I don't like using arguments to collect messages.
Also, if the method that might fail is "low level" - like coming from an app server or the database layer, I'd prefer to return an Enum with the return status, and then translate that into a string at the GUI level. Don't pass around user strings at the low level if you're ever going to internationalize your code, because then your app server can only respond in one language at a time, rather than having different clients working in different languages.
Is this the only method where you have such a requirement? If not, just generate a general Response class with an isSuccessful flag and a message string, and use that everywhere.
Or you could just have the method return null to show success (not pretty, and does not allow returning a success AND a message).
I would most probably go for something like :
class SomeClass {
public int authenticate (Client client) {
//returns 0 if success otherwise one value per possible failure
}
public String getAuthenticationResultMessage (int authenticateResult) {}
//returns message associated to authenticateResult
}
With this "design", you can ask for a message only when authentication fails (which I hope is the scenario that occurs 99,99% of time ;))
It may also be of good practice to delegate message resolution to another Class. But it depends of your application needs (mostly, does it need i18n ?)
This seems like a common idiom in other programming languages, but I cannot figure out which one ( C I guess as I read in the question ) .
Almost the same question is posted here and here
Attempting to return two values from a single function, may be misleading. But as it has been proved by the attempts of doing so, it may be very useful too.
Definitely creating and small class with the results should be the correct way to proceed if that is a common flow in the app as posted before.
Here's a quote about returning two values from a function:
As a matter of programming style, this idea is not
appealing in a object oriented programming language.
Returning objects to represent computation results
is the idiom for returning multiple values. Some
suggest that you should not have to declare classes
for unrelated values, but neither should unrelated
values be returned from a single method.
I've found it in a feature request for java to allow multiple return values
look at the "evaluation" section dated: 2005-05-06 09:40:08
Successful authentication should be the "normal" case, so an authentication failure is the exceptional case.
What are the different status strings for the user anyway. I can see only two, success or failure. Any further information is a potential security issue.
Another advantage of the solution with exceptions is that it cannot be called in the wrong way and the failure case is more obvious. Without exceptions, you write:
if (authenticate()) {
// normal behaviour...
}
else {
// error case...
}
You can accidently call the method ignoring the return value. The "normal behaviour" code is then executed without successful authentication:
authenticate();
// normal behaviour...
If you use exceptions, that cannot happen. If you decide to not use exceptions, at least name the method so that it is clear that it returns a state, e. g.:
if (isAuthenticated()) {
//...
}
There are a lot of good answers here so I will keep it short.
I think failure of a user to authenticate can be considered a valid case for a checked exception. If your style of programming favoured handling exceptions then there would be no reason not to do this. It also removes the "How to return multiple values from a method, my method does one thing It authenticates a user"
If you are going to return multiple values then spend 10 minutes creating a generic PairTuple (can also be more than a pair TripleTuple, I won't repeat the example listed above) and return your values that way.
I hate having small dto style objects to return various multiple values they just clutter the place.
How about returning a string. Empty or Null for success. Error Message in case of failure.
Simplest that would work. However not sure if it reads well.
Return the Object. It allows you to put additional functionality into the Class if you need it. Short lived objects in Java are quick to create and collect.
I would choose the Exception option in first place.
But, in second place, I would prefer the C-style technique:
public boolean authenticate(Client client, final StringBuilder sb) {
if (sb == null)
throw new IllegalArgumentException();
if (isOK()) {
sb.append("info message");
return true;
} else {
sb.append("error message");
return false;
}
}
This is not so strange and it's done in many places in the framework.
Instead of creating a special object for return type, I usually just return an array where all the returned information is stored. The benefit is that you can extend this array with new elements without creating new types and mess. The downside you have to know exactly what elements should present when array is returned from particular method to parse it correctly. Usually I agree on certain structure, like first element is always Boolean indication success, second is String with description, the rest is optional.
Example:
public static void main(String[] args)
{
Object[] result = methodReturningStatus();
if(!(Boolean)result[0])
System.out.println("Method return: "+ result[1]);
}
static Object[] methodReturningStatus()
{
Object[] result = new Object[2];
result[0] = false;
result[1] = "Error happened";
return result;
}