Skip to main content
黑话筒

关于产品的代码问题

本来打算写封邮件回复,后来想想还是算了吧。但是辛苦码好的字不能浪费,就贴到这里了。邮件是发给不懂代码的人,所以避开了术语。

Refactoring is the key.

In my opinion, we can do this over our source code.

Our current situation on source code is: we have many huge classes and long functions.

For example, if I am the chef, I want to cook an egg.

In our system, we will write the whole thing in one function:

  1. Get an egg from fridge
  2. Crack it
  3. Put it in to pan
  4. Drop some salt
  5. Flip it
  6. Put it into dish
  7. Take the dish to meal table

This will works fine if there is no change.

But what about if I want 2 eggs with sauce, don’t drop salt, cook in oven, with only one side cooked. How do we change the code as usual?

  1. Get x egg(s) from fridge
  2. Crack it/them
  3. If is cooking use pan: Put it/them to pan otherwise, put it into oven.
  4. If need salt: Drop some salt
  5. If need sauce: put sauce
  6. If not only need one side: Flip it
  7. Put it into dish
  8. Take the dish to meal table

OK, this will works. But if someone want to cook the egg on rock with double sauce, double salt, how do we change the code?

This is our problem. We cannot change our code from time to time. We must refactoring our source code. Our code will be open for extension but closed to modification(Open Closed Principle in software design)

We can split the function to multiple function. So we can reuse these function when needed, and add corresponding interfaces, in order to replace one by another.

An improved function to do this could be:

  1. Get egg from Egg Storage(this could be anything, e.g. fridge, basket)
  2. Send them to Egg Cracker(can do this by hand or anything else), and get cracked egg.
  3. Sent them to Egg Cooker(can be pan or oven or microwave)
  4. Decorate the egg with sauce, salt(Decorate Pattern in software design)
  5. Put it into container
  6. Send the container to destination

Now each step is a abstract method, all methods are called by a main function. These abstract method can have various implementations. We do not care which implementation we use.

If we need to fry beef instead egg. We could do the following changes, make these method more abstract.

  1. Get food from Storage(this could be anything, e.g. fridge, basket)
  2. Prepare food before cooking. (can do this by hand or anything else), and get prepared food.
  3. Sent food to Cooker(can be pan or oven or microwave)
  4. Decorate the food(with sauce, salt using Decorate Pattern in software design)
  5. Put the food into container
  6. Send the container to destination

So, if I want to cook chicken instead of beef. I just write the different code and add to this flow. No historical code will changed. Risks can be controlled.

Refactoring is not stop and refactoring , but is improving in small step.