作為c的初學者,如果寫一個求四邊形的周長的函數的話,我傾向於像下面這樣書寫:
//計算四邊形的周長
#include <stdio.h>
#define RECTANGLE 0 //長方形
#define SQUARE 1 //正方形
//多邊形
struct polygon{
int type;
int length;
int width;
};
int get_circumference(struct polygon pygn)
{
if(pygn.type == RECTANGLE)
{
return 2 * (pygn.length + pygn.width);
}
else if(pygn.type == SQUARE)
{
return 4 * pygn.width;
}
else
{
//todo
}
}
int main(void)
{
struct polygon pygn_rec, pygn_squ;
pygn_rec.type = RECTANGLE;
pygn_rec.width = 6;
pygn_rec.length = 10;
pygn_squ.type = SQUARE;
pygn_squ.width = 6;
printf("get cir rec is: %d\n", get_circumference(pygn_rec));
printf("get cir squ is: %d\n", get_circumference(pygn_squ));
return 0;
}
今天,看了<linux c編程一站式學習>的“函數類型和函數指標”(http://learn.akae.cn/media/ch23s08.html)後,又學到了一種更好的方式:
//計算四邊形的周長
#include <stdio.h>
#define RECTANGLE 0 //長方形
#define SQUARE 1 //正方形
//多邊形
struct polygon{
int type;
int length;
int width;
};
int get_rectangle_cir(struct polygon pygn)
{
return 2 * (pygn.length + pygn.width);
}
int get_square_cir(struct polygon pygn)
{
return 4 * pygn.width;
}
int (* get_circumference[])(struct polygon pygn) = {get_rectangle_cir, get_square_cir};
#define get_cir(pygn) get_circumference[pygn.type](pygn)
int main(void)
{
struct polygon pygn_rec, pygn_squ;
pygn_rec.type = RECTANGLE;
pygn_rec.width = 6;
pygn_rec.length = 10;
pygn_squ.type = SQUARE;
pygn_squ.width = 6;
printf("get cir rec is: %d\n", get_cir(pygn_rec));
printf("get cir squ is: %d\n", get_cir(pygn_squ));
return 0;
}
當調用get_cir(pygn)時,用類型欄位pygn.type做索引,從指標數組get_circumference中取出相應的函數指標來調用,
也可以達到if ... else ...的效果,但相比之下這種實現更好,每個函數都只做一件事情,
而不必用if ... else ...兼顧好幾件事情,比如get_rectangle_cir和get_square_cir各做各的,
互相獨立,而不必把它們的代碼都耦合到一個函數中。
“低耦合,高內聚”(Low Coupling, High Cohesion)是程式設計的一條基本原則,
這樣可以更好地複用現有代碼,使代碼更容易維護。如果類型欄位pygn.type又多了一種取值,
只需要添加一組新的函數,修改函數指標數組,原有的函數仍然可以不加改動地複用。