This is the first day of my participation in the August More Text challenge

1. Class design principles

Solid class design principles:

  • Single Responsibility Principle (SRP) : A class should only be responsible for one thing.
  • Open closed Principle (OCP) : Software components should be developed for extension and closed for modification.
  • Richter’s Substitution Principle (LSP) : Subclasses must be able to replace the base class completely.
  • Interface Isolation Principle (ISP) : clients should not rely on interfaces they do not need.
  • The Dependency Lead Principle (DIP) : Rely on abstractions, not details.

2. Static classes handle exceptions

public class TestExceptions {
    public static void main(String[] args)
    {
        try
        {
            throw new DBExeption.NoData("No row found for id : x");
        }
        catch(Exception e) { e.printStackTrace(); }}}Copy the code

Advantages:

  1. Even if a developer writes an error message that is hard to read, the specific error can be understood.
  2. Support different exception instances to handle different exception scenarios.
  3. There is no need to override many exceptions with a single exception.
  4. Logs are more meaningful and readable.

3. Java exception

Exception hierarchies in Java

  1. Don’t swallow the abnormality. Treat it.
  2. Throws a checked exception
  3. Do not catch the Exception class but a specific subclass
  4. Never grab a Throwable class
  5. Always wrap exceptions correctly in custom exceptions so that stack traces are not lost
  6. Logging an exception or throwing it but never simultaneously
  7. Never throw any exceptions from a finally block
  8. Always catch only exceptions that you can actually handle
  9. Do not use printStackTrace () statements or similar methods
  10. If you do not intend to handle exceptions, use a finally block instead of a catch block
  11. Remember the “hurry up early” rule
  12. Always clean up after handling exceptions
  13. Only relevant exceptions are thrown from the method
  14. Do not use flow control exceptions in your program
  15. Validate user input to catch adverse conditions early in request processing
  16. Repeat the try-catch using the template method

4. Spring configuration file best practices

1) add header comments for each configuration file 2) use consistent naming conventions 3) No version numbers in schema references 4) preferred setter injection for constructor injection 5) Preferred index type matching constructor arguments 6) Use shortcut forms on extended forms 7) Reuse bean definitions as much as possible 8) Always use ID as bean identifier 9) Avoid autowaging as much as possible 10) always use classpath prefixes 11) Always externalize properties 12) Use dependency checking during development 13) Do not abuse/overuse dependency injection

5. Java wrapper class internal cache

Integer cache

public class IntegerCacheDemo {
 
    public static void main(String[] args) {
 
        Integer a1 = 100;
        Integer a2 = 100;
        Integer a3 = new Integer(100);
 
        System.out.println(a1 == a2);
        System.out.println(a1 == a3);
    }
}
 
Output:
 
true
false
Copy the code

The first print statement will print true; Indicates that both variables refer to the same instance. However, the second print statement prints false because of the new Integer (..) A new instance is created in a separate memory location. Therefore, if you want to use this cache, always use raw assignments to reference variables or use the valueOf () method.

Changing the cache size

If you want to store more examples, you can use the runtime parameters, as shown in the following: – Djava. Lang. Integer. IntegerCache. High = 2000 the statement above will enable the cache instance storage from 127 to 1000. Please keep in mind that so far, not like _ – Djava. Lang. Integer. IntegerCache. Low_ such properties. It may be added in the future.

Other Packaging

I’ve already discussed caching in the Integer class in the previous discussion, but if in fact all wrapper classes provide this functionality. So as not to see them:

  1. Java.lang. Boolean stores two built-in instances as TRUE and FALSE, and returns references to them if the new keyword is not used.
  2. Java.lang. Character has a cache for characters between unicodes 0 and 127 (ASCII-7 / US-ASCII).
  3. The java.lang.Long cache length is between -128 and +127.
  4. Java.lang. String has a whole new String pool concept.

ToString Best practices

  • Java overrides toString () with ToStringBuilder

7. Java 8 Streams

Another big change is the Java 8 Streams API, which provides a mechanism to process a set of data in a variety of ways, including filtering, transforming, or any other way that might be useful to your application.

The Streams API in Java 8 supports different types of iterations, so you just define the set of items to process, the actions to perform on each item, and the output to store from those operations.

Example of a stream API. In this example, items is a collection of String values, and you want to remove items that begin with some prefixed text.

List items; String prefix; List filteredList = items.stream().filter(e -> (! e.startsWith(prefix))).collect(Collectors.toList());

This kitems.stream () means that we want items to use the Streams API to process the data in the collection.

Java 8 date/time API changes

The new date and time API/classes (JSR-310), also known as _ThreeTen_, simply change the way you handle dates in Your Java applications.

The date of

The Date class is even out of Date. The new classes to replace the Date class are LocalDate, LocalTime, and LocalDateTime.

  1. thisLocalDateClass represents a date. There is no representation of time or time zone.
  2. thisLocalTimeClass represents a time. There is no representation of dates or time zones.
  3. thisLocalDateTimeClass represents a date-time. No time zone representation.

If you wish to use the date function of the region information, then Ramda provides you with 3 additional classes similar to one, namely OffsetDate, OffsetTime and OffsetDateTime above. The time zone offset can be expressed in the “+ 05:30” or “Europe/Paris” format. This is done by using another class for ZoneId.

LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.of(12.20);
LocalDateTime localDateTime = LocalDateTime.now();
OffsetDateTime offsetDateTime = OffsetDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
Copy the code

Timestamp and duration

To represent a specific timestamp at any given moment, you need to use class Instant. This Instant class represents an Instant of accuracy in nanoseconds. Actions on Instant include comparing Instant to another operation and adding or subtracting duration.

Instant instant = Instant.now();
Instant instant1 = instant.plus(Duration.ofMillis(5000));
Instant instant2 = instant.minus(Duration.ofMillis(5000));
Instant instant3 = instant.minusSeconds(10);
Copy the code

Durationclass is a new concept introduced for the first time in the Java language. It represents the time difference between two timestamps.

Duration duration = Duration.ofMillis(5000);
duration = Duration.ofSeconds(60);
duration = Duration.ofMinutes(10);
Copy the code

Duration Handles small time units, such as milliseconds, seconds, minutes, and hours. They are better suited for interacting with application code. To interact with people, you need to get larger durations, which are presented with the Period lesson.

Period period = Period.ofDays(6);
period = Period.ofMonths(6);
period = Period.between(LocalDate.now(), LocalDate.now().plusDays(60));
Copy the code