java variable names - java

Could you give some good reasons for having the class name as part of the name of any variable? We use to have this policy, which I find quite useful. Some team member wants to revert the decision.
My arguments for the moment:
you can directly know what you're talking about:
for (Student student: students) {
...
}
is quite easy to understand (vs Student s or Student anyone)
it helps self-commenting the code
our ide provides direct support for that
you can directly see wheter you're using apples instead of pears (or bears ;-) )
Less confusion where subtle differences matter:
criteriaBuilder.equal(nameExpression, name);
The only argument I can see against this is that it makes the code longer (which I think isn't an issue with modern IDEs).
Is there public provisioning for such a recommendation? Anyone using the same rule? Any alternative?

That sounds like Hungarian Notation to me.
In principle it sounds like a good idea but I'm honestly not sure there are good reasons for it:
Self commenting / documenting code - this should be possible without putting types in the variable names;
An IDE should also provide support for seeing what type a variable is without putting it in the variable name (e.g. Eclipse can do this)
I don't know that this is really an advantage.
One problem with Hungarian Notation that you don't mention is that if you refactor code, you have to change all the variable names as well. There are plenty of examples on The Daily WTF where variables are named 'strSOMETHING' or 'intSOMETHING', even though the types are defined as something else.
In general, IMO the case for using Hungarian Notation is pretty flimsy and generally I wouldn't recommend making it a policy.
(If this isn't exactly what you are talking about, I apologise!)

Your bible on this question is Steve McConnel's book, Code Complete, which is the most comprehensive book on software construction practice like this. He has a whole chapter on variable naming and why it is important.
The key is to make the name a full description of what the variable does, so that it is easy to understand for the person reading it. If it achieves that, then it's good practice.
Student student looks like a simple to understand policy, but it has an immediate disadvantage - it contains no extra information about the variable. You already know its a student. If you know anything else about the object then add it to the variable name - studentUnderReview, graduatingStudent etc. "student" should only be used if you know absolutely nothing else, such as the variable is used to iterate over all Students. Now in a long method it's useful to know the type by just looking at the name, but if the variable has short scope then it's marginal whether its useful or not. There are some studies (see McConnel) which indicate that for variables with very short scope, such as for loop indices, short names are better.
As soon as you have two variables, this system breaks down. If the default is to call one variable "student" then the temptation is to call two variables "student1" and "student2", which is bad practice indeed (see McConnel for details). You need to make names that describe the object - goodStudent and badStudent; studentBeingSaved and studentBeingRead.

The policy should be to use descriptive variable names. One-letter variable names are bad, but so are variable names based exclusively on class names. Your main argument is really for descriptive variable names.
As for the others:
it helps self-commenting the code - no, it duplicates information from the variable declaration
our ide provides direct support for that - that would only be an argument if the alternatives provide no benefits
you can directly see wheter you're using apples instead of pears (or bears ;-) ) - that's the job of the type system
Of course, if your class names are descriptive, then sometimes it will make sense to have variables with the same name - when the variable describes an instance of the class without any distinctive characteristics. As in your example:
for (Student student: students) { ... }
If you're looping over all students, this is fine. But if you have a non-generic instance of Student, the variable name should describe what particular role that student has in this part of the program (e.g. candidate or graduate).

Generally your variable names should help the developer see quickly what they actually represent.
Student student would be ok if the relation that defines expresses a anything-to-student relation, like Student[] students (or better some collection of Student) would be ok for a class Professor or the like.
String string is generally a bad idea, since it doesn't say anything about the use of that variable. Better names would be String name, String description or similar. In some cases, where all that matters is that you're dealing with one string - like general string utilities - you might call the variable string but if you have two or more, you should use better names (e.g. source and target etc. depending on the class/method).
IMHO, adding prefixes/suffixes might be a good idea if they tell you something about the variable that its base name wouldn't, e.g. in a web environment you might deal with strings that are input by the user as well as escaped strings (e.g. to prevent code injection), so you might use a prefix/suffix to make a disctinction between the user input version and the escaped counterpart.

Related

Is there anything inherently wrong with long variable/method names in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When is a Java method name too long?
I know this is probably is a question of personal opinion, but I want to know what's standard practice and what would be frowned upon.
One of my profs in university always seems to make his variable and method names as short as possible (getAmt() instead of getAmount) for instance.
I have no objection to this, but personally, I prefer to have mine a little longer if it adds descriptiveness so the person reading it won't have to check or refer to documentation.
For instance, we made a method that given a list of players, returns the player who scored the most goals. I made the method getPlayerWithMostGoals(), is this wrong? I toiled over choosing a way to make it shorter for awhile, but then I thought "why?". It gets the point across clearly and Eclipse makes it easy to autocomplete it when I type.
I'm just wondering if the short variable names are a piece of the past due to needing everything to be as small as possible to be efficient. Is this still a requirement?
Nothing inherently wrong, it's better to make it descriptive than cryptic. However, it's often code-smell for a method that is trying to do too much or could be refactored
Bad: getActInfPstWeek
OK: getAccountInformationForPastWeek()
Better getAccountInformation(DateRange range)
I prefer to have long variable/method names that describe what's going on. In your case, I think getPlayerWithMostGoals() is appropriate. It bothers me when I see a short variable name like "amt" and I have to transpose that in my head (into "amount").
Something like getAmt() is looks like C++ code style... In java usually are used more descriptive names.
Your professor made a good understandable method. But it's very popular word. It's not a general case. Use your "longWordStyle" style it's more java.
As per standards, longer descriptive names are advised to make it more readable and maintainable on longer term. If you use very short naming e.g. a variable as a, you will forget yourself, what that variable is meant for after sometime. This becomes more problematic in bigger programs. Though I don't see an issue in using getAmt() in place of getAmount(), but definitely getPlayerWithMostGoals() is preferable over something like getPlayer().
Long names, short names, it all depends. There are a lot of approaches and discussions but in fact a method's name should reflect its intention. This helps you to further understand the code. Take this example.
public void print(String s)
Nifty name, short, concise... isn't it? Well, actually no if there's no documentation to tell you what do you mean by "Printing". I say System.our.println is a way of printing a string but you can define printing as saving the string in a file or showing it in a dialog.
public void printInConsole(String s)
Now there are no misunderstandings. Most people can tell you that you can read the method's JavaDoc to understand it but... are you going to read a full paragraph to decide if the method you're going to use does what you need?.
IMO, methods should describe at least an action and an entity (if they're related to one). "Long" is also a perception... but really long names make the code hard to structure. It's a matter of getting the proper balance.
As a rule of thumb, I'd void abreviations and use JavaDoc to further describe a method's intention. Descriptive names can be long but the reward is both readability and a self-explainatory code.

String vs. A new Data class

I overheard two of my colleagues arguing about whether or not to create a new data model class which only contains one string field and a setter and a getter for it. A program will then create a few objects of the class and put them in an array list. The guy who is storing them argue that there should be a new type while the guy who is getting the data said there is not point going through all this trouble while you can simple store string.
Personally I prefer creating a new type so we know what's being stored in the array list, but I don't have strong arguments to persuade the 'getting' data guy. Do you?
Sarah
... a new data model class which only contains one string field and a setter and a getter for it.
If it was just a getter, then it is not possible to say in general whether a String or a custom class is better. It depends on things like:
consistency with the rest of your data model,
anticipating whether you might want to change the representation,
anticipating whether you might want to implement validation when creating an instance, add helper methods, etc,
implications for memory usage or persistence (if they are even relevant).
(Personally, I would be inclined to use a plain String by default, and only use a custom class if for example, I knew that it was likely that a future representation change / refinement would be needed. In most situations, it is not a huge problem to change a String into custom class later ... if the need arises.)
However, the fact that there is proposed to be a setter for the field changes things significantly. Instances of the class will be mutable, where instances of String are not. On the one hand this could possibly be useful; e.g. where you actually need mutability. On the other hand, mutability would make the class somewhat risky for use in certain contexts; e.g. in sets and as keys in maps. And in other contexts you may need to copy the instances. (This would be unnecessary for an immutable wrapper class or a bare String.)
(The simple answer is to get rid of the setter, unless you really need it.)
There is also the issue that the semantics of equals will be different for a String and a custom wrapper. You may therefore need to override equals and hashCode to get a more intuitive semantic in the custom wrapper case. (And that relates back to the issue of a setter, and use of the class in collections.)
Wrap it in a class, if it matches the rest of your data model's design.
It gives you a label for the string so that you can tell what it represents at run time.
It makes it easier to take your entity and add additional fields, and behavior. (Which can be a likely occurrence>)
That said, the key is if it matches the rest of your data model's design... be consistent with what you already have.
Counterpoint to mschaef's answer:
Keep it as a string, if it matches the rest of your data model's design. (See how the opening sounds so important, even if I temper it with a sentence that basically says we don't know the answer?)
If you need a label saying what it is, add a comment. Cost = one line, total. Heck, for that matter, you need a line (or three) to comment your new class, anyway, so what's the class declaration for?
If you need to add additional fields later, you can refactor it then. You can't design for everything, and if you tried, you'd end up with a horrible mess.
As Yegge says, "the worst thing that can happen to a code base is size". Add a class declaration, a getter, a setter, now call those from everywhere that touches it, and you've added size to your code without an actual (i.e., non-hypothetical) purpose.
I disagree with the other answers:
It depends whether there's any real possibility of adding behavior to the type later [Matthew Flaschen]
No, it doesn’t. …
Never hurts to future-proof the design [Alex]
True, but not relevant here …
Personally, I would be inclined to use a plain String by default [Stephen C]
But this isn’t a matter of opinion. It’s a matter of design decisions:
Is the entity you store logically a string, a piece of text? If yes, then store a string (ignoring the setter issue).
If not – then do not store a string. That data may be stored as a string is an implementation detail, it should not be reflected in your code.
For the second point it’s irrelevant whether you might want to add behaviour later on. All that matters is that in a strongly typed language, the data type should describe the logical entity. If you handle things that are not text (but may be represented by text, may contain text …) then use a class that internally stores said text. Do not store the text directly.
This is the whole point of abstraction and strong typing: let the types represent the semantics of your code.
And finally:
As Yegge says, "the worst thing that can happen to a code base is size". [Ken]
Well, this is so ironic. Have you read any of Steve Yegge’s blog posts? I haven’t, they’re just too damn long.
It depends whether there's any real possibility of adding behavior to the type later. Even if the getters and setters are trivial now, a type makes sense if there is a real chance they could do something later. Otherwise, clear variable names should be sufficient.
In the time spent discussing whether to wrap it in a class, it could be wrapped and done with. Never hurts to future-proof the design, especially when it only takes minimal effort.
I see no reason why the String should be wrapped in a class. The basic perception behind the discussion is, the need of time is a String object. If it gets augmented later, get it refactored then. Why add unnecessary code in the name of future proofing.
Wrapping it in a class provides you with more type safety - in your model you can then only use instances of the wrapper class, and you can't easily make a mistake where you put a string that contains something different into the model.
However, it does add overhead, extra complexity and verbosity to your code.

Java enumerations vs. static constants

I'm looking at some Java code that are maintained by other parts of the company, incidentally some former C and C++ devs. One thing that is ubiquitous is the use of static integer constants, such as
class Engine {
private static int ENGINE_IDLE = 0;
private static int ENGINE_COLLECTING = 1;
...
}
Besides a lacking 'final' qualifier, I'm a bit bothered by this kind of code. What I would have liked to see, being trained primarily in Java from school, would be something more like
class Engine {
private enum State { Idle, Collecting };
...
}
However, the arguments fail me. Why, if at all, is the latter better than the former?
Why, if at all, is the latter better
than the former?
It is much better because it gives you type safety and is self-documenting. With integer constants, you have to look at the API doc to find out what values are valid, and nothing prevents you from using invalid values (or, perhaps worse, integer constants that are completely unrelated). With Enums, the method signature tells you directly what values are valid (IDE autocompletion will work) and it's impossible to use an invalid value.
The "integer constant enums" pattern is unfortunately very common, even in the Java Standard API (and widely copied from there) because Java did not have Enums prior to Java 5.
An excerpt from the official docs, http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html:
This pattern has many problems, such as:
Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.
And this just about covers it. A one word argument would be that enums are just more readable and informative.
One more thing is that enums, like classes. can have fields and methods. This gives you the option to encompass some additional information about each type of state in the enum itself.
Because enums provide type safety. In the first case, you can pass any integer and if you use enum you are restricted to Idle and Collecting.
FYI : http://www.javapractices.com/topic/TopicAction.do?Id=1.
By using an int to refer to a constant, you're not forcing someone to actually use that constant. So, for example, you might have a method which takes an engine state, to which someone might happy invoke with:
engine.updateState(1);
Using an enum forces the user to stick with the explanatory label, so it is more legible.
There is one situation when static constance is preferred (rather that the code is legacy with tonne of dependency) and that is when the member of that value are not/may later not be finite.
Imagine if you may later add new state like Collected. The only way to do it with enum is to edit the original code which can be problem if the modification is done when there are already a lot of code manipulating it. Other than this, I personally see no reason why enum is not used.
Just my thought.
Readabiliy - When you use enums and do State.Idle, the reader immediately knows that you are talking about an idle state. Compare this with 4 or 5.
Type Safety - When use enum, even by mistake the user cannot pass a wrong value, as compiler will force him to use one of the pre-declared values in the enum. In case of simple integers, he could even pass -3274.
Maintainability - If you wanted to add a new state Waiting, then it would be very easy to add new state by adding a constant Waiting in your enum State without casuing any confusion.
The reasons from the spec, which Lajcik quotes, are explained in more detail in Josh Bloch's Effective Java, Item 30. If you have access to that book, I'd recommend perusing it. Java Enums are full-fledged classes which is why you get compile-time type safety. You can also give them behavior, giving you better encapsulation.
The former is common in code that started pre-1.5. Actually, another common idiom was to define your constants in an interface, because they didn't have any code.
Enums also give you a great deal of flexibility. Since Enums are essentially classes, you can augment them with useful methods (such as providing an internationalized resource string corresponding to a certain value in the enumeration, converting back and forth between instances of the enum type and other representations that may be required, etc.)

Merits/Reasons for using "get" as a prefix in the name of an accessor method

I know that in Java, it is common practice to use "get" as a prefix to an accessor method. I was wondering what the reason for this is. Is it purely to be able to predict what it is returning?
To clarify: In some java classes (eg String) a variable like length can be accessed by calling "length()" rather than "size()". Why are these methods written like this, but others like "getSomeVariable()"?
Thank you for your time.
Edit: Good to see I'm not alone about the confusion & such about the size and length variables
'get' prefix (or 'is' for methods returning booleans) is a part of JavaBean specification which is used throughout the java but mostly in views in web UI.
length() and size() are historical artefacts from pre-javabean times; many a UI developer had lamented the fact that Collection has a size() method instead of getSize()
Because properties are nouns and methods are verbs. It is part of the bean pattern that is well-established and therefore expected by anyone using your class.
It might make sense to say:
String txt="I have " + car.GetFuelLevel() + " liters of petrol.";
or ...
String txt="I have " + car.FuelLevel + " liters of petrol.";
but not ...
String txt="I have " + car.FuelLevel() + " liters of petrol.";
I mean, it doesn't make sense to say "Hey, car. Go FuelLevel for me." But to say "Hey, car. Go GetFuelLevel for me." That's more natural.
Now, why did they break rank with String.length() and others? That's always bothered me, too.
The get prefix is particularly useful if you also have set, add, remove, etc., methods. Of course, it's generally better to have an interface full of gets or full of sets. If almost every method has get then it just becomes noise. So, I'd drop the get for immutables and the set for builders. For "fundamental" types, such as collections and strings, these little words are also noisy, IMO.
The get/set conventions stem from the java Bean specification. So people strongly tend to use that.
And the .size(), .length(), and even .length attribute of arrays are all examples of Java's failures to follow its own conventions. There are many more, it's "fun" to discover them!
They may be failures to the specification, however they improve readability. size and length allow you to read the following line of code:
for (int i=0; i<thing.size(); ++i){
As...
While i is less than the thing's size...
There's no real convention behind this, but it does make it easier to translate into a sentence directly.
The historical reason was that the JavaBean specification stated that accessors to class properties should be done with getPropertyName/setPropertyName. The benefit was that you could then use Introspection APIs to dynamically list the properties of an object, even one that you hadn't previously compiled into your program. An example of where this would be useful is in building a plug-in architecture that needs to load objects and provide the user access to the properties of the object.
You have different names to retrieve size in different classes simply because they were written by different people and there probably wasn't at the time a design guideline for naming class methods in a consistent manner. Once millions of lines of code had been written using these inconsistent names, it was too late to change.

Naming convention for a variable that works like a constant

I have a variable that I'm using like a constant (it will never change). I can't declare it as a constant because the value gets added at runtime.
Would you capitalize the variable name to help yourself understand that data's meaning?
Or would you not because this defies convention and make things more confusing?
The larger question:
Do you follow conventions even if the scenario isn't typical of the convention, but close enough that it might help you, personally, to understand things?
If it will aid you (and everybody else) in understanding your code six months down the line, do it. If it won't, don't. It's really that simple.
Personally, I would capitalise it. This is the convention in Java, where constants are always allocated at runtime due to its object-oriented nature. I'd be much more comfortable knowing that if I accidentally assigned to it, I'd definitely notice the next time I scanned through that chunk of code.
I don't consider my personals need to be paramount here -- if I've written the code, I'm already better placed to retrace it in the future if and when that's needed, than anybody else; so it's the "anybody else" I put first and foremost -- a present or future teammate that will need to understand the code (ideally) as thoroughly as I do.
Besides, with mandatory code reviews as a prereq to committing ANYthing to the codebase (an excellent practice, and the unfailing rule at my present employer), I'm likely to be called up on it should I ever let my attention slip (it does happen -- which is why I LOVE those mandatory code reviews, as applied to myself as well as everybody else!-).
A "variable set only once at startup" is a special-enough case that may be worth adding to your team's guidelines -- treating it as "closer to a constant than a variable" may make a lot of sense, but that only helps if the same rule/guideline is used consistently across the codebase. If the rule is not there I would check if there's consensus about adding it; otherwise, I would NOT break the guidelines for the sake of my personal tastes... that's the root of "egoless programming" and "team ownership of the codebase", two principles I serve with burning ardor.
BTW, were I on a single-person team in terms of coding guidelines (it happens, though it's not an optimal situation;), I think I'd have no trouble gaining unanimous consensus by myself that treating "set-once at startup" variables as constants in terms of naming conventions!-). But with a larger team, that's more work, and it could go either way.
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;
}
This should make it pretty clear that you shouldn't be setting this value anywhere else but at the startup of the application. If you want added protection, you can add some private guard boolean variable to throw an exception if initializeAtStartup is called more than once.
I would name it as a variable, I prefer to keep my naming very consistent.
As Rob already suggested, what about readonly (available in C# at least).
Or a property with no setter.
My immediate impression is that something that you "set at runtime, then never change" is a constant, only so far as the business rules are constant. Also, you should be using mutators/accessors, since using ALL CAPS can hardly guarantee "constness".
public class BadClass
{
public static final double PI = 3.1;
// PI is very constant. Not according to the business roles modeled by my
// application, but by nature. I don't have a problem making this publicly
// accessible--except that [Math] already does, with much better precision)
public static /*final*/ int FOO = null;
// FOO is constant only by convention. I cannot even enforce its "constness".
// Making it public means that my enemies (overtime, for example) can change
// the value (late night programming), without telling me.
}
Instead,
public class BetterClass
{
public static final double PI = 3.1;
private /*final*/ Integer foo = null;
public int getFoo() {
return this.foo.intValue();
}
public void setFoo(int value) {
// The business rules say that foo can be set only once.
// If the business rules change, we can remove this condition
// without breaking old code.
if ( null == this.foo ) {
this.foo = value;
} else {
throw new IllegalStateException("Foo can be set only once.");
}
}
}
If you always use the mutator to set the value, even within [BetterClass] itself, you know that the foo's "constness" will not be violated. Of course, if someone is going to set the value of foo directly (I need to quit working before 2:00 am!), there are still no guarantees. But something like that should be pointed out at code review.
So my recommendation is to treat foo as a normal member variable--there doesn't need to be a special naming convention for something that is almost const.
However, use mutators/accessors, even on private variables. These are typically very fast, and you can enforce business rules inside of them. This should be you convention.
(If you are writing code for embedded medical devices, pretend that you never saw this posting).
is it possible to mark it as readonly? Then conventions are not as important.
Do you follow conventions even if the
scenario isn't typical of the
convention, but close enough that it
might help you, personally, to
understand things?
Following a convention when the scenario is atypical might confuse or slow down others (or even you, after a while.) I would avoid giving a variable the guise of something that it isn't.
Also, the fact that you have this atypical scenario could be an indication that perhaps some other, more typical paradigm could be followed. Though, I don't have any immediate suggestions for a alternative.
I would make it capitalized (since it's more constant than variable from a design perspective) and add a comment around it stating its uniqueness to the application.
FWIW my own convention is to use all caps for #defines and for enums. For const variables I either use no particular convention, or when I do it's to prefix the name with a 'k' (for 'konstant' - not 'c' which is already over used for things like 'count' or 'char').
I'm finding that I like the 'k' convention and will probably use it more often, and may even use it for enums, reserving the screaming, all-caps identifiers for the dreaded preprocessor macros.
Conventions are just that, conventions. They are there to help the code understandable. They usually do if they are not too badly chosen and if they are applied consistently. The last point is probably the most important thing about them: they should be applied consistently.
One thing which prevent some conventions to make code more readable even when they are applied consistently -- at least for new comers and people switching between code base -- is when they are conflicting with other conventions. In C and C++, I'm aware of two common conventions about the use of names in ALL_CAPS:
reserve them for the preprocessor; that one has my preference as the preprocessor identifier are special: they don't obey usual scoping rule and preventing clashes with them is important
use them for constant (macro and enumerators).
Two problems comes in addition to the unfamiliarity if you use them for logically constant things which are in fact variable:
they aren't usable in places (like array size) where the language expect constant expression
my experience teach me that maintenance will tend to make them even less constant that they are now.
Create a wrapper class with a single private static field. Create an initField(..) and a getField(..) static method. initField throws/asserts/otherwise errors if the static field is not null. (For primitives, you may have to use a primitive and a boolean to track initialization.)
In java, I prefer to pass these types of variables in as system properties. A static class can then do something like:
public final int MY_INT = Integer.getInteger("a.property.name");
You could also use a property file (see java.util.Properties) instead of using -D to specify it. Then you get:
public class Foo {
public static final int MY_INT;
static {
Properties p = new Properties();
try{
p.load( new FileInputStream("app.props"):
} catch(IOException e) {
//SWALLOW or RETHROW AS ERROR
}
MY_INT=Integer.parseInt( p.getProperty("my.int","17") ); //17 is default if you swallo IOException
}
...
}
First of all, follow your project's coding standards. You should be coding for other people reading the code, not yourself. Your personal preferences should not take precedence over project-wide rules and conventions, etc.
In the absence of a project coding standard you should follow "best practice" for the language you are dealing with.
In Java, best practice is that you should declare a pseudo-constant with a camel case identifier. That's what the Sun Java coding standard says, and that is what the vast majority of professional Java developers use.
In C and C++ the (classical) convention is that all-caps is used for constants defined as preprocessor symbols. So since this is not a preprocessor symbol, you should use whatever your coding standard says is appropriate for a variable.
The fact that the pseudo-constant is not supposed to change won't stop someone from modifying the code so that it actually changes, accidentally or deliberately. If you use / abuse a coding convention that makes the identifier look like a real constaint, you will be part of the problem:
Someone trying to read / debug your code will first assume the identifier is a real constant and not investigate the possibility thatit is not.
Then when they do lookat the declaration, there will be alot of shouting and threats of
defenestration.
Actually, a better way to deal with a pseudo-constant is to encapsulate it. In Java, you would declare it as private member and provide a getter and setter. The setter should do something to prevent the pseudo-constant from being changed after it has been set the first time. Any decent Java JIT compiler will inline a simple getter, so this should not affect runtime performance.
Giving wrong information is generally not best practise.
Implicitly claiming something is a constant, when it is merely currently not changed, is giving out wrong information.
I'm not sure if this is legal in your language of choice, but in C++, this would work for your purpose:
#include <iostream>
int main()
{
int i = 0;
std::cin >> i;
const int CONST = i;
std::cout << CONST; //displays i
system("PAUSE");
return 0;
}
I'm not sure if this is a moral thing to do, but this does solve your problem (unless you really need your memory).
Just like anything else - scope and context are required to know in what way something is constant. So - there's no way to to satisfy everyone.
Follow the style used in your language of choice - 80% of the time, that will be clear enough. The alternative is a highly over-though nameing system that sacrifices productivity for ideal technical correctness (which few people will even really appreaciate if you can ever achieve it.)
one question would be: what kind of variable?
in the case of static variables, that don't change after what i'd call "boot-time" for the lack of a better term, i use ALL_CAPS ... same thing for global variables (if the language supports them at all) ...
communicating semantics is actually the point of naming conventions, and seeing an ALL_CAPS clearly states, that a) i will not write to it b) i can cache it (to a local variable for example, or in AS3 even an instance variable makes sense, since static access is very slow) ...
whether it's a "real constant" or not does not really matter ... that's more of an implementation detail, that should be hidden away (reliably! information hiding is good, and important, but it is crucial, that the information that is shared, can be trusted!) ... it can really be exchanged ... for example, i often start building apps vs. some hardcoded config, containing some static constants ... later, i decide that i don't want this to be hardcoded, but rather coming from some config file, so i load it, and during boot process, i init all the pseudo-constants ... the actuall app still treats them as constants, because after booting, that is what these values are ... this seems perfectly valid to me ...
at instance level, i am not 100% sure, if i ever ran into a case, where i could be very certain, that some field would never change ... usually, this makes the class unflexible ...
other than that, you can usually declare readonly properties, to have compile time errors, which is also a good thing to have ...

Categories

Resources