论坛首页 海阔天空论坛

古龙的编码风格

浏览 1458 次
精华帖 (0) :: 良好帖 (1) :: 灌水帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-12-17   最后修改:2008-12-17
如果古龙是一个程序员的话
他的编码风格或许会是这样的

package liveness;

//他已经记不得是什么时候写的这段代码
public class Transfer
{
	private static final Object tieLock = new Object();
	
       //每个程序员都会有感到不安时候
	public void transferMoney(
							  Account from,
							  Account to,
							  int amount
							  )
	{
		synchronized(from)
		{
			synchronized(to)
			{
				if((from.getBalance()-amount)<0)
				{
					from.debit(amount);
					to.credit(amount);
				}
			}
		}
	}
	
	
	//这里他感到了些许的安全
	public void transferMoneySafe(
								  final Account from,
								  final Account to,
								  final int amount
								  )
	{	
		class Helper
		{
			public void transfer()
			{
				if((from.getBalance()-amount)<0)
				{
					from.debit(amount);
					to.credit(amount);
				}
			}
		}
		
		int fromHash = System.identityHashCode(from);
		int toHash = System.identityHashCode(to);
		
		if(fromHash < toHash)
		{
			synchronized(from)
			{
				synchronized(to)
				{
					new Helper().transfer();
				}
			}
		}
		else 
			if(fromHash < toHash)
			{
				synchronized(to)
				{
					synchronized(from)
					{
						new Helper().transfer();
					}
				}
			}
			else
				{
					synchronized(tieLock)
					{
						synchronized(to)
						{
							synchronized(from)
							{
								new Helper().transfer();
							}
						}
					}
				}
	}
}


大量的换行,加上大量的旁白(代码注释)
或许他的代码风格很不错
   发表时间:2008-12-17  
噢买疙瘩!
0 请登录后投票
论坛首页 海阔天空版

跳转论坛:
Global site tag (gtag.js) - Google Analytics