简体   繁体   English

Java龙目岛 - 最佳实践?

[英]Java Lombok - best practice?

I have inherited a class with the following Lombok annotations: 我继承了一个带有以下Lombok注释的类:

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class PricingAndCosting {

//variables and constants

}

is it better practice to just do the following to get the same functionality: 是否更好的做法是只需执行以下操作即可获得相同的功能:

@Entity
@Data
public class PricingAndCosting {

//variables and constants

}

The class you had inherited is only 1 step removed from being fully open to the outside (it would require making the fields public ) which is potentially bad as few bugs could hide in uses of this class. 你继承的这个类只有一步从完全开放到外面(它需要将字段public )这可能是坏的,因为这个类的使用中很少有bug可以隐藏。 Even if the class is being consumed in sane way, you cannot guarantee it into the future unless you close it off a bit. 即使课程以理智的方式消费,除非你稍微关闭它,否则你不能保证将来。

You can construct it with no values, with all values, you can build it with only some values and you can mutate it through setters. 你可以构造它没有值,使用所有值,你可以只使用一些值来构建它,你可以通过setter来改变它。

This most likely breaks the equals and hashcode contract too (those should be calculated using the same set of immutable fields - a very rough rule of thumb which makes sense when using lombok, but obviously there is more). 这很可能会打破equalshashcode合约(那些应该使用相同的一组不可变字段来计算 - 这是一个非常粗略的经验法则,在使用lombok时很有意义,但显然还有更多)。

I would first identify the uses of this class and find out whether it can be refactored to something closer to immutable. 我首先要确定这个类的用法,并找出它是否可以重构为更接近不可变的东西。

Short answer is it depends. 简短的答案取决于它。 Long answer is in general, Lombok is generating code for you to avoid boilerplate code, however, you should know what you really need to use? 一般来说,龙克的答案很长,为了避免样板代码而生成代码,但是,你应该知道你真正需要使用什么? suppose you need only getters then use @Getter. 假设您只需要吸气剂然后使用@Getter。

Moreover, sometimes it is really helpful for you; 而且,有时它对你真的很有帮助; something which is common heavily uses like Builder pattern can be offered to you with just one annotation, and also Throwing an exception is another fancy feature and more and more. 只有一个注释可以为您提供像Builder模式一样常用的东西,并且抛出异常是另一个奇特的功能,而且越来越多。 You can check this to see a good example https://www.baeldung.com/intro-to-project-lombok 您可以查看这个以查看一个很好的示例https://www.baeldung.com/intro-to-project-lombok

As code efficiency; 作为代码效率; it sounds that using little code with @Data will be better, but actually, it is not! 听起来使用@Data的小代码会更好,但实际上,它不是! you are consuming resources which you may not need. 你正在消耗你可能不需要的资源。 So try to use what you really need is a good practice. 所以尽量使用你真正需要的是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM