Avoiding hard-coded format strings

In C, we like to use #define or const globals to avoid hard-coding values and strings.

How can we avoid hard-coding strings that need to be formatted? Consider, for instance, a filepath to an i2c bus in linux:

int format_i2c_bus(char *dev, size_t size, unsigned int bus_no) {   return snprintf (dev, size, "/dev/i2c-%u", bus_no); } 

I don't like the idea of adding a #define I2C_BUS_FMT "/dev/i2c-%u" to the top of the file (or the header file), because when you read snprintf (dev, size, I2C_BUS_FMT, bus_no) you can't see how many and of what type the format specifiers are... you need to take it by faith that it accepts a single unsigned int or go check.

The same problem applies to const globals.

How can I avoid hard-coding format strings without moving important information away from the place where it is used?

Replay

Don't feel obliged to define every constant as a preprocessor symbol just because someone calls it a best practice. There are good reasons for and against it, and the best way to decide is to look at the situation and use your judgment.

The question to ask yourself is "if I define this as a preprocessor symbol, where will it be used?" If the answer is "in one function," there's no reason it shouldn't be hard-wired in the one place where it's used. That keeps all of the knowledge of how it works concentrated in one place.

I'm going to stick my neck out and assume that in your program, format_i2c_bus() is the API for formatting those paths. This means anyone who wants it done should be calling that function to get the job done. If you define a symbol for the format string, you make it available for use in any other function that can see it. That leaves room for someone to do their own formatting, which is the last thing you want because you no longer have a single place to make adjustments when the formatting of the path changes.

There's an old guideline in user interface design that says if the user can't do something, it shouldn't be shown to them as an option. That applies to software, too: if other modules shouldn't be making use of something, make sure it's not visible to them.

Category: c# Time: 2016-07-28 Views: 2
Tags:

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.150 (s). 12 q(s)