writing clean code with modern java

Posted CherryTab

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了writing clean code with modern java相关的知识,希望对你有一定的参考价值。

https://www.youtube.com/watch?v=uEHJ5CHaF08

主要顺便练练英文

 

YouTube上真的很多超赞的视频,有关语言特性的,架构的,代码整洁的...最近一直在每天花一个小时左右看英文相关的speak,然后基本每天会看一下medium的文章,练英文。

 

 

1.接口的deafault method and private method

public interface MyInterface {

    default void defaultMethod() {
        privateMethod();
    }

    private void privateMethod() {
        System.out.println("private method for default method");
    }
}
public class MyClass implements MyInterface {

    public static void main(String[] args) {
        new MyClass().defaultMethod();
    }
}

输出

private method for default method

这里是不能通过实现类调用接口的private方法的,private的意思本来就是类私有,对象私有。

 

 

 

 

2.try-with-resource

public class Reader {


    private void readFile (String file) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        try (reader) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new Reader().readFile("D:\\\\program\\\\java project\\\\Java8InAction\\\\src\\\\main\\\\java\\\\clean\\\\MyInterface.java");

        // trasferTo can do the same thing like readFile
        new FileInputStream("D:\\\\program\\\\java project\\\\Java8InAction\\\\src\\\\main\\\\java\\\\clean\\\\MyInterface.java").transferTo(System.out);
    }
}

输出,两次都是一样的输出,读的文件为上面的接口类

package clean;

public interface MyInterface {

    default void defaultMethod() {
        privateMethod();
    }

    private void privateMethod() {
        System.out.println("private method for default method");
    }
}

 

 

 这里第三点的确需要改进,比如最近的项目就规定必须要用helper objects for reading or writing file

 

3.switch expressions

 

boolean result = switch(ternaryBool) {
    case TRUE -> true;
    case FALSE -> false;
    case FILE_NOT_FOUND -> throw new UncheckedIOException(
        "This is ridiculous!",
        new FileNotFoundException());
    // as we\'ll see in "Exhaustiveness", `default` is not necessary
    default -> throw new IllegalArgumentException("Seriously?! 

以上是关于writing clean code with modern java的主要内容,如果未能解决你的问题,请参考以下文章

Command /bin/sh failed with exit code 1

超实用教程!一探Golang怎样践行Clean Architecture?

CLEAN GNOME 41 Look with Qogir

ruby clean_google_enginge_with_fog

文件操作-with和上下文管理器

[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component