像写诗一样写代码

一入编程深似海,我早已下海四年了。前段时间松懈犯懒了,没有及时更新博客。今天我来谈谈如何写一手好代码,好代码的前提是头脑中要构思好一个好的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{
public void at(String nowTime){
System.out.println(nowTime+"之后。。。。");
}
}


总结:

1、思考如何组织代码的过程中不断深入对面向对象的理解。

2、自表达的代码风格确实是一种值得追求的境界。

3、多看别人的代码风格,取长补短。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值