Saturday, April 27, 2024
HomeJavaQuiz your self: Verifying the operation of smelly Java code

Quiz your self: Verifying the operation of smelly Java code


Your colleague is engaged on an software that analyzes statistics for autos of various makes and fashions. A enterprise rule requirement is that every automotive occasion within the software will need to have a novel manufacturing 12 months; making a second occasion of a car with the identical 12 months should fail.

Quiz yourself, Java code, Oracle Java Career, Java skills, Java Jobs, Java Tutorial and Materials, Java Learning, Java Prep, Java Preparation, Java Certification

The Automobile class created by the colleague is as follows:

Copy code snippet

Copied to ClipboardError: Couldn’t CopyCopied to ClipboardError: Couldn’t Copy

public class Automobile {

  Integer 12 months;

  String make;

  String mannequin;

  Record<Integer> existingYears = new ArrayList<>();

  public Automobile(Integer 12 months, String make, String mannequin) {

    this.12 months = 12 months;

    this.make = make;

    this.mannequin = mannequin;

    existingYears.add(12 months);

    checkYear(12 months);

  }

  void checkYear(Integer 12 months) {

    for (int i=0; i < existingYears.measurement()-1; i++ ) {

      if (existingYears.get(i).equals(12 months)) {

        throw new IllegalArgumentException(“Duplicated 12 months !”);

      }

    }

  }

}

public class Automobile {

  Integer 12 months;

  String make;

  String mannequin;

  Record<Integer> existingYears = new ArrayList<>();

  public Automobile(Integer 12 months, String make, String mannequin) {

    this.12 months = 12 months;

    this.make = make;

    this.mannequin = mannequin;

    existingYears.add(12 months);

    checkYear(12 months);

  }

  void checkYear(Integer 12 months) {

    for (int i=0; i < existingYears.measurement()-1; i++ ) {

      if (existingYears.get(i).equals(12 months)) {

        throw new IllegalArgumentException(“Duplicated 12 months !”);

      }

    }

  }

}

You surprise if the enterprise constraint is correctly carried out and determine to check the code utilizing the next code fragment:

new Automobile(2018, “Honda”, “Civic”); // line n1

new Automobile(2021, “Hyundai”, “Accent”); // line n2

new Automobile(2018, “Ford”, “Expedition”); // line n3

Which assertion is true? Select one.

A. The check code runs with out throwing an exception.

B. Line n1 will trigger IllegalArgumentException.

C. Line n1 will trigger IndexOutOfBoundsException.

D. Line n3 will trigger IllegalArgumentException.

E. Line n2 will trigger IndexOutOfBoundsException.

Reply. This instance is probably not code you’d be pleased with, however you didn’t write it, so there’s no want for embarrassment right here.

Have a look at the code offered and see that it appears the intention is roughly as follows:

◉ For every name to the constructor, add the proposed checklist to an inventory referred to as existingYears.

◉ Name the strategy checkYear, which performs two issues. First it determines if that 12 months has been used earlier than and, if it has, it throws an IllegalArgumentException.

The foundation downside right here is that the existingYears checklist is created as an example member of a Automobile object, and subsequently each Automobile object has a Record of its personal. Consequently, the years during which different Automobile objects have been created won’t be present in every Record. The code doesn’t work as meant and won’t stop two separate situations of Automobile from having the identical 12 months worth.

If as an alternative the existingYears area carried the static modifier, just one occasion Record would exist in this system. In that case, the comparability would test the present automotive’s 12 months with these seen earlier than and line n3 would throw an IllegalArgumentException. That change would make possibility D right. However since that wasn’t performed, possibility D is wrong.

You would possibly discover that the present automotive’s 12 months is added to the checklist earlier than the test is run. When you fail to pay shut consideration to the management of the loop that searches by means of the checklist, you would possibly count on that an exception could be thrown for each new automotive, based mostly on an anticipated collision with its personal 12 months. That might lead you to imagine that the code would throw an IllegalArgumentException for any and all makes an attempt to instantiate a Automobile. In that scenario, the primary exception would presumably stop additional execution, and you’ll count on an exception at line n1. Nevertheless, a extra thorough investigation reveals that the loop stops earlier than the final merchandise is checked, which is why possibility B is wrong.

Discover the next check within the loop:

i < existingYears.measurement()-1

As a result of the scale worth is diminished by one, the code would ignore the final merchandise within the checklist. That merchandise would be the present automotive’s 12 months, so the dreaded collision wouldn’t happen. Additional, as a result of existingYears is an occasion area, the checklist’s measurement within the checkYear methodology is at all times 1, and the physique of the loop by no means executes in any respect.

Two of the choices recommend that an IndexOutOfBoundsException could be thrown. Nevertheless, as simply famous, the scale of the checklist is at all times 1 when the checkYear methodology executes, and the physique of the loop won’t ever execute. No code outdoors that loop makes an attempt to entry information from the checklist utilizing an index; subsequently, no code that would presumably throw an IndexOutOfBoundsException will ever be executed. From this you possibly can conclude that choices C and E are incorrect.

From the observations above, you possibly can conclude that no exceptions are thrown, and possibility A have to be right.

Now that the reply has been decided, listed here are among the least nice elements of the code—in addition to the truth that it doesn’t work.

◉ Regardless that the code for avoiding a collision with the present automotive’s 12 months is functionally right, if an try is made so as to add a automotive that has a reproduction 12 months, existingYears will include the identical 12 months twice. Whereas this could not trigger errors within the code proven up to now, sudden behaviors comparable to this are complicated to programmers attempting to make sense of issues later, each when they’re studying code and when they’re debugging. It’s additionally widespread for this form of scenario to result in bugs later when the peculiarity is just not totally understood by all. It could be much better so as to add the 12 months solely after it has been authorized.

◉ Creating any object with nonprivate mutable fields is usually unwise. It permits modifications to be made by any code in the identical bundle. If such modifications are made with out understanding the implications and, thereby violating some consistency rule pertaining to the info, it’s simple to trigger bugs which are exhausting to trace down, particularly as a result of such a lot of code (your entire bundle or extra) may need been chargeable for the change.

◉ Checking to see if a Assortment accommodates a given object ought to be performed utilizing the accommodates methodology. It’s instantly and unambiguously clear what this methodology does. In contrast, writing a loop describing find out how to carry out the motion leaves the programmer who’s studying the code with the accountability for figuring out what the code is meant to attain. Usually talking, it’s preferable that code have a extra declarative nature and a much less crucial one. After all, to have the ability to use the accommodates methodology, you should first be sure that the present automotive’s 12 months is just not added earlier than validation.

◉ Iterating lists utilizing the normal C-style for loop to regulate an index for accessing checklist parts ought to be averted. Some lists in Java’s collections (usually these with array backing) iterate tolerably effectively this fashion, but when the implementation modifications to make use of a special construction (comparable to a LinkedList), the ensuing effectivity can be comparatively or exceedingly poor. If doable, give any information construction the possibility to carry out its personal iteration, because the programmer who created that construction ought to know finest find out how to iterate the weather effectively. As an alternative of utilizing an index-counting loop such because the C-style loop, use Java’s enhanced for loop or extract an Iterator (or maybe ListIterator, if the scenario requires it) and use that.

Conclusion. The proper reply is possibility A.

Supply: oracle.com

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments