Java Tip 27: Typesafe constants in C++ and Java

本文介绍了一种替代使用枚举和常量的方法来帮助消除范围检查和运行时错误。通过在C++中使用类常量和静态初始化,实现类型安全和常量特性。同时,提供了Java实现的示例,并讨论了可能的改进和限制。
This article offers an alternative to using enums or const ints to help eliminate range checking and runtime errors -- first looking at C++ and then exploring an implementation of the same using Java. The summary above shows one of the problems associated with using these constructs. Another problem is the additional range checking that is required to validate the parameter (see below).

Probably the best known and most widely used approach in C++ is through the use of enum.


class Car
{ public:
enum{FORD,VW,SAAB,MAX_CAR}; }; void car_wash(int car)
{
//requires range checking on Cars
if(car>=0 && car<MAX_CAR)
{
//ok
}
} void main(void)
{
car_wash(Car::FORD);
}


The main problem with the approach above is that any int value or object with a conversion to int (that is, a class with operator int()) can be passed to car_wash(). For example, there is nothing stopping someone from using car_wash() like this: car_wash(100); -- or someone who knows that Car::FORD is zero from being lazy and callingcar_wash(0). This leaves the implementor of car_wash() with the responsibility of range-checking the parameter.

The next example takes advantage of the C++ compiler's type checking, but it is still open to abuse through the use of a cast.


class Car
{ public:
enum Type{FORD,VW,SAAB}; }; void car_wash(Car::Type c)
{
//do something with c
} void main(void)
{ Car::Type car=Car::FORD;
car_wash(car); //OK car_wash is expecting a Car::Type parameter

car_wash(1); // error, no conversion from int Car::Type
}


Even though Car::Type is an enum and therefore ultimately is an int, the compiler stops clients of car_wash() from passing an intas a parameter. However, although this approach is an improvement on the previous example, it is still open to abuse by undermining the compiler's type checking through the use of a cast. For example, the compiler can not prevent someone from casting an int to a Car::Type.


void main(void)
{ Car::Type car=(Car::Type)100;
car_wash(car);
}


Now this leaves us back at square one. Again a cautious implementor of car_wash() will feel obliged to do some form of range checking.

NOTE: The class keyword can be replaced by namespace in these C++ examples if your compiler supports it and the enums could also be replaced by const int. But the problem we are trying to eliminate remains the same: the need for range checking and the potential for runtime errors.

Below I offer an alternative to the above methods that gives both type safety and "constness."


class Car
{ private: //private ctor to stop instantiation of client Car objects
Car() {}
public:
static const Car FORD;
static const Car VW;
static const Car SAAB; int operator==(const Car &car) const
{
return &car==this;
} }; //static initialization const Car Car::FORD;
const Car Car::VW;
const Car Car::SAAB; void car_wash(const Car &car)
{ if(Car::FORD==car)
{
cout << "The Car being washed is a FORD" << endl;
}
else if(Car::VW==car)
{
cout << " The Car being washed is a VW" << endl;
}
//
} void main(void)
{
car_wash(Car::VW);
}


Notice the use of the private ctor (constructor) this stops the instantiation of client Car objects. Because clients of class Carcan not instantiate their own objects, the need to perform any range checking in car_wash() is eliminated.

One last area of improvement would be to remove the nasty if, else if clauses from car_wash(). The presence of these clauses is a common problem with enumerated types or constants. Although client code becomes more readable through the use of constant objects, the class methods that receive these objects as parameters can become giant switch statements or a series of if, else if clauses.

In a future tip I will explore various techniques that can be used to eliminate these problems.

In the meantime I will leave it as an exercise for the reader to come up with an alternative design for car_wash()that removes the if, else if clauses.

Finally, for those of you who have been patient enough to wade through C++ desperate to get your hands on some Java (and who can blame you!), here is the Java implementation of the Car class. The AWT (abstract windowing toolkit) uses a similar approach in some classes.


public final class Car
{
private Car() {}
public static final Car FORD=new Car();
public static final Car VW=new Car();
public static final Car SAAB=new Car();
}


Notice that in this case, as in many others, the Java implementation is more elegant than the C++ implementation. Also note the use of "final" in the class declaration. The "final" keyword declares that a class can not be subclassed.

At this point some of you may be thinking that the declaration of class Car as final may be too restrictive and that the class should be non-final with a protected ctor to allow subclasses to add new cars. Although not an award-winning design, the Java code below illustrates how the subclassing of class Car can reintroduce the problems we have been trying to eliminate.


import java.util.Vector; public class Car
{
protected Car() {}
public static final Car FORD=new Car();
public static final Car VW=new Car();
public static final Car SAAB=new Car();
} public class FrenchCar extends Car
{
public static final Car CITROEN=new Car();

protected FrenchCar()
{

}
} public class CarWash
{
public void Start(Car car)
{
//
}
} public class SuperCarWash extends CarWash
{
public void Start(Car car)
{
if(FrenchCar.CITROEN==car)
{
//do some specialized washing
//could still call super.Start(car)
//to finish off
}
else
super.Start(car);
}
} public class SuperCarWashOwner
{
private SuperCarWash superCarWash= new SuperCarWash();
private Vector carsToWash = new Vector(); public void AddCar(Car c)
{
carsToWash.addElement(c);
}
public void WashCars()
{
//iterate cars an call superCarWash.Start
}
} public class Test
{
private SuperCarWashOwner scwOwner = new SuperCarWashOwner(); public void TestMethod()
{
scwOwner.AddCar(Car.VW);
//add more cars
scwOwner.WashCars();
}
}


The first thing to note in the code above is that the potential exists for clients of CarWash to pass a FrenchCar to CarWash.Start(). To improve matters, CarWash.Start() could throw an exception if a FrenchCar object is passed in, but all this leads us back to where we started -- trying to design typesafe constants!

It is left as an exercise for the reader to explore this last technique and balance the advantages with the tradeoffs.

About the author

Philip Bishop is technical director and a consultant at Eveque Systems Ltd. in the UK. Eveque specializes in designing and implementing distributed object systems using Java, CORBA, C++, ODBMS, and so on. He can be reached at phil@eveque.demon.co.uk.
同步定位与地图构建(SLAM)技术为移动机器人或自主载具在未知空间中的导航提供了核心支撑。借助该技术,机器人能够在探索过程中实时构建环境地图并确定自身位置。典型的SLAM流程涵盖传感器数据采集、数据处理、状态估计及地图生成等环节,其核心挑战在于有效处理定位与环境建模中的各类不确定性。 Matlab作为工程计算与数据可视化领域广泛应用的数学软件,具备丰富的内置函数与专用工具箱,尤其适用于算法开发与仿真验证。在SLAM研究方面,Matlab可用于模拟传感器输出、实现定位建图算法,并进行系统性能评估。其仿真环境能显著降低实验成本,加速算法开发与验证周期。 本次“SLAM-基于Matlab的同步定位与建图仿真实践项目”通过Matlab平台完整再现了SLAM的关键流程,包括数据采集、滤波估计、特征提取、数据关联与地图更新等核心模块。该项目不仅呈现了SLAM技术的实际应用场景,更为机器人导航与自主移动领域的研究人员提供了系统的实践参考。 项目涉及的核心技术要点主要包括:传感器模型(如激光雷达与视觉传感器)的建立与应用、特征匹配与数据关联方法、滤波器设计(如扩展卡尔曼滤波与粒子滤波)、图优化框架(如GTSAM与Ceres Solver)以及路径规划与避障策略。通过项目实践,参与者可深入掌握SLAM算法的实现原理,并提升相关算法的设计与调试能力。 该项目同时注重理论向工程实践的转化,为机器人技术领域的学习者提供了宝贵的实操经验。Matlab仿真环境将复杂的技术问题可视化与可操作化,显著降低了学习门槛,提升了学习效率与质量。 实践过程中,学习者将直面SLAM技术在实际应用中遇到的典型问题,包括传感器误差补偿、动态环境下的建图定位挑战以及计算资源优化等。这些问题的解决对推动SLAM技术的产业化应用具有重要价值。 SLAM技术在工业自动化、服务机器人、自动驾驶及无人机等领域的应用前景广阔。掌握该项技术不仅有助于提升个人专业能力,也为相关行业的技术发展提供了重要支撑。随着技术进步与应用场景的持续拓展,SLAM技术的重要性将日益凸显。 本实践项目作为综合性学习资源,为机器人技术领域的专业人员提供了深入研习SLAM技术的实践平台。通过Matlab这一高效工具,参与者能够直观理解SLAM的实现过程,掌握关键算法,并将理论知识系统应用于实际工程问题的解决之中。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值