java值的传递_Java 8可选–基于值的类使用指南

java值的传递

In this article, we will go through the use of Java 8 Optional class and understand what a Value-Based class is. What are the scenarios for using a value-based class? and finally, see the usage guidelines for Optional.

在本文中,我们将使用Java 8 Optional类,并了解什么是基于值的类。 使用基于值的类的方案是什么? 最后,请参阅“可选”的使用指南。

Java 8可选 (Java 8 Optional)

Optional is a container object which may or may not contain a non-null value. You can read more about Optional here. There has been some improvements in Optional class in Java 9, read about them here.

可选的是包含或不包含非null值的容器对象。 您可以在此处阅读有关Optional的更多信息。 Java 9中的Optional类已进行了一些改进,请在此处阅读有关它们的信息

为什么要使用可选类? (Why use Optional Class?)

  • Promotes better and cleaner design and code

    促进更好,更清洁的设计和代码
  • It declares the purpose and the intent of the variable.

    它声明了变量的目的和意图。
  • Reduces testing effort

    减少测试工作
  • Avoids NullPointerException

    避免NullPointerException
  • It supports Fail Fast approach of programming

    它支持快速失败编程方法
  • Removes boiler plate conditional checks.

    取消锅炉板的条件检查。
  • Supports fluent style

    支持流利的风格
  • Promotes the use of functional style of programming.

    促进使用函数式编程。

Optional is a value-based class. We will cover the value-based class later in this article.

可选的是基于值的类。 我们将在本文后面介绍基于值的类。

值类型 (Value Types)

Before we delve into value-based class lets understand what a value-type is? A value type is a data type which, is designed for being passed by value in and out of methods, and stored by value in data structures. The only value types which the Java language directly supports are the eight primitive types.

在深入研究基于价值的类之前,让我们了解什么是价值类型 ? 值类型是一种数据类型,旨在按值传入和传出方法,并按值存储在数据结构中。 Java语言直接支持的唯一值类型是八种原始类型。

In the article “State of the Values” Brian Goetz proposed that Java VM and language can be gently extended with a new kind of type, a value type, which usefully combines the properties of Java’s current classes and primitive types, and these should be small immutable & identity-less.

Brian Goetz 在“价值的状态 ”一文中提出,可以使用一种新的类型(一种值类型)来温和扩展Java VM和语言,该类型可以有效地结合Java当前类和原始类型的属性,并且这些属性应该很小不变且无身份。

A value type should be synonymous to “Codes like a class, works like an int”.

值类型应与“像类一样的代码,像int一样工作”的同义词。

基于价值的类 (Value-Based Class)

The concept of value type formed the basis of Value-Based classes. A boxed form of every value type will be a value-based class.

值类型的概念构成了基于值的类的基础。 每个值类型的框式形式都是基于值的类。

A Value-Based class is a Container class which is a wrapper for value-based types, where the instances of Value-based classes follow following principle (from Java Documentation):

基于值的类是Container类,是基于值的类型的包装器,其中基于值的类的实例遵循以下原则(来自Java文档):

  • are final and immutable (though may contain references to mutable objects)

    是最终且不可变的(尽管可能包含对可变对象的引用)
  • have implementations of equals, hashCode, and toString which are computed solely from the instance’s state and not from its identity or the state of any other object or variable

    具有equals,hashCode和toString的实现,这些实现仅根据实例的状态而不是根据其标识或任何其他对象或变量的状态进行计算
  • make no use of identity-sensitive operations such as reference equality (==) between instances, identity hash code of instances, or synchronization on an instances’ intrinsic lock

    不使用身份敏感的操作,例如实例之间的引用相等(==),实例的身份哈希码或实例的固有锁上的同步
  • are considered equal solely based on equals(), not based on reference equality (==)

    仅基于equals()而不是基于引用相等(==)被视为相等
  • do not have accessible constructors, but are instead instantiated through factory methods which do not commit as to the identity of returned instances

    没有可访问的构造函数,而是通过工厂方法实例化的,这些方法不承诺返回实例的身份
  • are freely substitutable when equal, meaning that interchanging any two instances x and y that are equal according to equals() in any computation or method invocation should produce no visible change in behavior.

    在相等时可以自由替换,这意味着在任何计算或方法调用中互换等于equals()的任意两个实例x和y都不会在行为上产生任何可见的变化。

A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization, or any other identity-sensitive mechanism. Use of such identity-sensitive operations on instances of value-based classes may have unpredictable effects and should be avoided.

如果程序尝试直接通过引用相等性或通过呼吁同步,身份哈希,序列化或任何其他身份敏感机制间接地将两个引用区分为基于值的类的相等值,则可能会产生不可预测的结果。 在基于值的类的实例上使用此类身份敏感的操作可能会产生不可预测的影响,应避免使用。

Simply put an instance of the value-based class is final, immutable and these instances do not have a proper state and identity, due to which certain operations are identity-specific and should be disallowed.

简单地说,基于值的类的实例是最终的,不可变的,并且这些实例没有适当的状态和标识,因此某些操作是特定于标识的,因此不应使用。

Java is gradually moving towards a functional style of programming and Value-Based classes help to promote immutability which is an integral aspect of the functional style of programming.

Java逐渐朝着编程的功能风格发展,基于值的类有助于促进不变性,这是编程的功能风格不可或缺的一部分。

Java可选类用法指南 (Java Optional Class Usage Guidelines)

Java Optional is just thought to be used in the context of replacement for NullPointerException and since its introduction, there are various scenarios for which this is recommended, however when we see it through the lens of value-based class, we get the limitation and purpose of using Optional:

Java Optional仅被认为是在NullPointerException的替代上下文中使用的,并且自从引入以来,在各种情况下都推荐使用此方法,但是当我们通过基于值的类的视角来查看它时,我们会得到限制和目的。使用可选:

  1. Optional should not be used for equality check or identity-based operations. The following should not be done:
    Optional<Actor> actor1 = Optional.of(new Actor());
    Optional<Actor> actor2 = Optional.of(new Actor());
    actor1.equals(actor2);

    可选不应该用于相等性检查或基于身份的操作。 不应执行以下操作:
  2. It should not be used as a Key in a HashMap. Following should not be allowed:
    Map<Optional<Actor>, String> actorMap = new HashMap<>();

    不应将其用作HashMap中的键。 不允许以下行为:
  3. Optional should not be used as a non-transient variable in a Serializable class. The following should be avoided:
    class Actor implements Serializable{
        Optional<Movie> movie;  
    }

    可选不应该在Serializable类中用作非瞬态变量。 应避免以下情况:
  4. Should not be used as an element of Entity, Data or Model class. These classes are used for persistence and hence would need identity and serialization; hence we should not use Optional instance variable.
    class Actor {
        Optional<Movie> movie;  
    }

    不应用作Entity,Data或Model类的元素。 这些类用于持久性,因此需要标识和序列化。 因此,我们不应使用Optional实例变量。
  5. Java Optional class should not be used for synchronization. Following code should be avoided:
    Optional<Actor> actor1 = Optional.of(new Actor());
    synchronized(actor1){
        //
    }

    Java Optional类不应用于同步。 应避免以下代码:
  6. Optional is primarily intended for use as a method return type where there is a clear need to represent “no result” and where using null is likely to cause errors.

    A variable whose type is Optional should never itself be null; it should always point to an Optional instance. Following way of coding is allowed:

    public Optional<String> getName(){
        //code
        return Optional.ofNullable(name);
    }

    Optional主要用于在明显需要表示“ 无结果 ”并且使用null可能导致错误的情况下用作方法返回类型。

    类型为Optional的变量本身不应为null。 它应始终指向Optional实例。 允许以下编码方式:

结论 (Conclusion)

In this article we discovered what a value-based class is? What are the scenarios for using a value-based class and the usage guidelines for Optional.

在本文中,我们发现了什么是基于值的类? 使用基于值的类的方案是什么,可选的使用准则是什么。

翻译自: https://www.journaldev.com/19640/java-8-optional-value-based-class

java值的传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值