Bad Thoughts Creat Poisons

美国爱尔姆·哈力斯住其著作《恶念致毒》(Bad Thoughts Creat Poisons)中说:“在华盛顿心理实验室所作的试验,显示人的恶念能于生理上引起化学变化,产生—种毒质注入血液,使身体生病。据无法证实的来源所说,其中妒忌毒质之凝集物,可在几分钟之内毒死一只猪;而内心充满深刻怨恨达—小时者,其毒汁之凝集物可毒死八十个人。”


some thoughts about immutable programming


Today, when I was reading C++ View, I saw an interesting example. rnDescription:rnwe have a list in memory that holds all the friends we have. We'll also need to add it to database.rnSuppose we have a method rnvoid addFriend(Person p)rnrn friends.add(p);rn addToDb(p);//if exception's thrown out, we need to undo in friends!rnrnThe problem exists when either friends.add() or addToDb() throws exception. then we have to undo the changes we've made to db and to the list.rnrnAccording to the author, "try-catch" can work, but it'll become very tedious and hard to maintain when the number of statements requiring "try-catch" scales up. So a transaction object should be used here.rnrnHere, although transaction object can work, but it still requires us to write an undo operation for each one, and sometimes it's not trivial to write an undo method.rnrnSo what do I suggest?rnAlthough db operation cannot be immutable, in-memory operation certainly can! If we do immutable programming, we don't need to undo at all!rndon't believe?rnSuppose the friends list is an immutable structure, i.e.rnListrn List cons(Person);rnrnwhere list.cons(p) only returns a new list instance without touching the old instance. (curious how this can be implemented by constant-time and linear storage? I'll give it later)rnrnok, if that's true, what can we do to the addFriend method?rnvoid addFriend(Person p)rnrn List tmp = friends.cons(p);rn addToDb(p);rn friends = tmp;rnrnHa ha, does that solve the undo easily?rnrnrnrnHere is an immutable list implrnrnpublic interface Listrnrn public List cons(Object obj);rn public Object getFirst()throws java.util.NoSuchElementException;rn public List getTail();rn public boolean isEmpty();rn private static final EmptyList singleton = new EmptyList();rn public static List instance()return singleton;rnrnrnclass ConsListrnrn public List cons(Object obj)return new ConsList(obj, this);rn public Object getFirst()return hd;rn public List getTail()return tl;rn public boolean isEmpty()return false;rn private final Object hd;rn private final List tl;rn ConsList(Object hd, List tl)this.hd = hd; = tl;rnrnclass EmptyListrnrn public List cons(Object obj)return new ConsList(obj, this);rn public Object getFirst()throw new java.util.NoSuchElementException();rn public List getTail()throw new java.util.NoSuchElementException();rn public boolean isEmpty()return true; rn EmptyList() rnrnrn