【发布时间】:2014-09-30 08:40:45
【问题描述】:
我正在使用 libldap 从 OpenLDAP 服务器获取信息。到目前为止,代码运行良好,但我有点不确定如何设计结果集的处理。假设搜索返回 2 个属性,它们都是多值的并且可以有很多值(例如 memberOf 属性)。
现在我使代码尽可能紧凑:
for (ldap_result = ldap_first_message(ldap_handle, ldap_result); ldap_result != NULL; ldap_result = ldap_next_message(ldap_handle, ldap_result)) {
switch (msgtype = ldap_msgtype(ldap_result)) {
case LDAP_RES_SEARCH_ENTRY:
{
/* iterate over all requested attributes */
for (attr = ldap_first_attribute(ldap_handle, ldap_result, &ber); attr != NULL; attr = ldap_next_attribute(ldap_handle, ldap_result, ber)) {
/* iterate over attribute values */
if ((bvals = ldap_get_values_len(ldap_handle, ldap_result, attr)) != NULL) {
int i;
for (i = 0; bvals[i] != '\0'; i++) {
char *value = bvals[i]->bv_val;
ber_len_t len = bvals[i]->bv_len;
// if attribute == x
if (strcmp(attr, "x")) == 0) {
// do_x();
// do_y();
// if attribute == y
} else if (strcmp(attr, "y") == 0) {
// do_sth_different();
}
/* free values structure after each iteration */
ldap_value_free_len(bvals);
}
}
}
/* free attributes structure */
ber_free(ber, 0);
break;
}
default:
{
// whatever
break;
}
}
}
那么这里发生了什么?我得到了第一个具有例如 100 个值的属性。对于每个值,如果其属性 a 或 b,我都会进行字符串比较。在现代硬件和较少的价值上,这不会是一个问题,但可能是更多的价值。代码紧凑,但效率可能会更好。
让我们看看如何让它与众不同:
for (ldap_result = ldap_first_message(ldap_handle, ldap_result); ldap_result != NULL; ldap_result = ldap_next_message(ldap_handle, ldap_result)) {
switch (msgtype = ldap_msgtype(ldap_result)) {
case LDAP_RES_SEARCH_ENTRY:
{
/* iterate over all requested attributes */
for (attr = ldap_first_attribute(ldap_handle, ldap_result, &ber); attr != NULL; attr = ldap_next_attribute(ldap_handle, ldap_result, ber)) {
// if attribute == x
if (strcmp(attr, "x")) == 0) {
/* iterate over attribute values */
if ((bvals = ldap_get_values_len(ldap_handle, ldap_result, attr)) != NULL) {
int i;
for (i = 0; bvals[i] != '\0'; i++) {
/* iterate over attribute values */
char *value = bvals[i]->bv_val;
ber_len_t len = bvals[i]->bv_len;
// do_x();
// do_y();
/* free values structure after each iteration */
ldap_value_free_len(bvals);
}
/* free attributes structure */
ber_free(ber, 0);
}
// if attribute == y
} else if (strcmp(attr, "y") == 0) {
/* iterate over attribute values */
if ((bvals = ldap_get_values_len(ldap_handle, ldap_result, attr)) != NULL) {
int i;
for (i = 0; bvals[i] != '\0'; i++) {
/* iterate over attribute values */
char *value = bvals[i]->bv_val;
ber_len_t len = bvals[i]->bv_len;
// do_sth_different();
/* free values structure after each iteration */
ldap_value_free_len(bvals);
}
/* free attributes structure */
ber_free(ber, 0);
}
}
}
}
default:
{
// whatever
break;
}
}
}
现在只有一个字符串比较,如果它的属性 a 或 b。不幸的是,这两个属性都有很多代码重复。
有什么更适合的解决方案的建议,或者有没有我还没见过的建议?
【问题讨论】: