一入编程深似海,我早已下海四年了。前段时间松懈犯懒了,没有及时更新博客。今天我来谈谈如何写一手好代码,好代码的前提是头脑中要构思好一个好的API,让代码自己表达内容和情感。
先上一首打油诗:
床前明月光,李白喝米汤。 |
就这首诗为例,我来撸一串代码,给读者奉上:
先看main方法,从这里看整体思路:
public static void main(String[] args) {
Poet poet=new Poet("李白").surroundWith("前","") .surroundWith("月光", "明亮")
.eatSoupOf(1);
Time nowTime=new Time();
nowTime.at("半夜");
poet.wedTrousers();
} |
构思好了,剩下的就是具体分类实现了。
class Poet{ private String name; private Map<String,String> surroundingEnvironment=new HashMap<String,String>(); public Poet(){ } public Poet(String name){ this.name=name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Poet eatSoupOf(int bowlsCount){ System.out.println(this.name+"喝了"+bowlsCount+"大碗米汤"); return this; } public Poet surroundWith(String stuff,String description){ System.out.println(this.name+"置身于:"+description+stuff); return this; } public Poet wedTrousers(){ System.out.println(this.name+" 尿裤子了!"); return this; } } |
class Time{ |
总结:
1、思考如何组织代码的过程中不断深入对面向对象的理解。
2、自表达的代码风格确实是一种值得追求的境界。
3、多看别人的代码风格,取长补短。