Java – a naming convention for variables that work like constants

I have a variable that I'm using like a constant (it never changes) I cannot declare it as a constant because the value is added at run time

Do you capitalize variable names to help you understand the meaning of data?

Or won't you break the rules and make things more chaotic?

Bigger question: do you follow conventions, even if the scene is not typical, but close enough to help you understand things personally?

Solution

Encapsulate it

#include <iostream>

class ParamFoo
{
    public:
        static void initializeAtStartup(double x);
        static double getFoo();
    private:
        static double foo_;
};

double ParamFoo::foo_;

void ParamFoo::initializeAtStartup(double x)
{
    foo_ = x;
}

double ParamFoo::getFoo()
{
    return foo_;
}

int main(void)
{
    ParamFoo::initializeAtStartup(0.4);
    std::cout << ParamFoo::getFoo() << std::endl;
}

It should be very clear that you should not set this value anywhere except when the application starts If you want to add protection, you can add some private protected Boolean variables to throw an exception when initializeatstartup is called multiple times

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>