从校园到工作的路(六)——关于阅读源码的方法

作为一名程序猿,阅读别人的代码是我们日常工作中必须的一部分。而代码的水准是不定的。
那么我们如何阅读别人的源码,并从中受益呢?
下面是JAVA类库中的String类的部分代码

    /**
     * Allocates a new {@code String} that contains characters from a subarray
     * of the character array argument. The {@code offset} argument is the
     * index of the first character of the subarray and the {@code count}
     * argument specifies the length of the subarray. The contents of the
     * subarray are copied; subsequent modification of the character array does
     * not affect the newly created string.
     *
     * @param  value
     *         Array that is the source of characters
     *
     * @param  offset
     *         The initial offset
     *
     * @param  count
     *         The length
     *
     * @throws  IndexOutOfBoundsException
     *          If the {@code offset} and {@code count} arguments index
     *          characters outside the bounds of the {@code value} array
     */
    public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

其实对绝大多数语言来说,通过阅读其源码与说明都是深入了解一门语言的必经之路。
而单就在上面这一个简单的String的构造函数中,我也受益良多:
1、对参数的检查
2、对异常的抛出(PS:刚入门的时候还以为只能在try…throw…catch这种模式下抛出异常和处理异常的)
3、考虑到了一些极端的情况,比如为什么使用offset > value.length-count,而却没有使用offset + count > value.length,注释中有详细解释
// Note: offset or count might be near -1>>>1.(Σ( ° △ °|||)︴,一开始居然不记得>>>是逻辑右移,也就是无符号右移,汇编经验喂了狗了。。。)
其实这就是说offset+count,两个正数相加,可能会产生溢出,-1>>>1可以得到最大的正整数,这也是溢出的表现。
4、还有风格与命名。风格都是简单明了,便于阅读,而在命名上,基本上都能达到望文生义。

上面这些都是优秀的源代码不可欠缺的一部分。
现在主流的一些优秀的源代码的观点如下:
1、安全性
2、可测试性和稳健性
3、可维护性
4、简单
5、可重用性

自己编写代码的时候要时常回顾一下自己是否做到了这些。而在阅读别人代码的时候,要看到别人是否做到了这些,别人是怎么做到的,如果没有做到,那换做自己,該是怎么改。

代码写出来应该是优雅的,假如自己的实现不优雅,肯定是因为自己没有找到最好的方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值