2

Is it right to return null,if object not found in array,I think it not usefull,or how can do right?

public Product FindByProductName(Product [] products,String productName){

            for(Product item:products)
                if(item.GetProductName().equals(productName))
                    return item;
            return null;
        }

Not usefull beacause I must use that function like this

Product result = products.FindByProductName(productsArray, "someName");

        if(result == null)
            System.out.print("Object not found!");
        else result.Show();

public void Show() {
        System.out.println("Название продукта = " + this.GetProductName() + ";" + " Код продукта = " + this.GetProductCode() + ";" + " Марка металла = " + this.GetBrandMetal() + ";" + " Вес продукта = " + this.GetWeightOfProduct() + ";");
    }
  • 4
    Either you throw null, but then the calling method will have to check for null each time, or you throw an Exception, which then must be handled by the client, or you return a default Object, depending on your requirements. – Stultuske Oct 02 '15 at 06:58
  • Another way would be first to verify whether the element exists, before trying a get. – Stultuske Oct 02 '15 at 06:59
  • 1
    You mean it's not useful because the consumer code is annoyingly verbose? There often isn't a better solution. (You could return an `Optional` but it wouldn't be any less verbose, it would only help you not forget the null check) – user253751 Oct 02 '15 at 07:00
  • 2
    Actually checking if an element exists before trying to get it is a bad idea because it has to find the element twice(one to check if exists, and one to get the element). also something else might remove it from the list once its verified the object exists but before it actually removes it. returning null is the best option and the least overhead. You should be reading the javadoc of the methods you're using anyways, so you won't forget to check if it's null. – WalterM Oct 02 '15 at 07:04
  • Another way is to make a 'null product' then you don't have to check for null. Eg. in the example use the null product would print out the "Object not found" – matt Oct 02 '15 at 07:13
  • This post http://stackoverflow.com/questions/271526/avoiding-null-statements states on how and when using null ;) – Fundhor Oct 02 '15 at 07:15

1 Answers1

4

Is it right to return null,if object not found in array

This is a common choice, unless of course having null in the array is valid. This is what Map#get does, for instance. And the fact that it's what Map#get does means that if you have a map where it's valid to store nulls, you have to call containsKey first to know whether get returning null means not found or means that the key is mapped to null. (Which is awkward.)

Here's a roundup of your options, which are not all mutually-exclusive:

  1. Return null if not found.

  2. Throw if not found.

  3. Offer a findIndex method that finds the index of the product, returning -1 if not found.

  4. Offer both a throwing version (findByProductName) and a null-returning version (findByProductNameOrDefault), and let the caller decide which is best for their scenario.

  5. Offer an optional argument that's the value to return if not found; the caller can then pass null if that's what they want, or something else.

  6. Offer a lambda callback for the "not found" case; again the caller can do what they want in the lambda.


Side note: The overwhelming convention in Java is that method names start with a lower-case letter, e.g. findByProductName rather than FindByProductName.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875