Using setProperty to set value of a Class Variable - java

Why do i need to use setProperty to be able to set the value of a variable in my java class
When i can just create the instance of the variable and use the intance to access my variable and assign a value.

What you are referring to is Encapsulation. It is one of the corner stones of object oriented programming. You usually want to restrict the ability of other code to mess around with the internal structure of your class.
Imagine a simple example where setting an integer value to a negative value will make your class fail catastrophically. With a setter in place, you could be able to handle this better, for instance with something like so:
public void setNumber(int number)
{
if (number < 0)
{
number = 1;
}
this.number = number
}
OR (more likely)
public void setNumber(int number)
{
if (number < 0)
{
throw new Exception("Number can't be less than 0");
}
else
{
this.number = number
}
}
As pointed out by Raveesh Sharma in the comment below, this is the reason why all instance variables should be declared as private.

You sure can assigned values by directly accessing the attributes from a given instance but that's definitely against the fundamentals of Java Object Oriented principles.
The best practices in Java OO recommend you to encapsulate the attributes from a class by making them private, and giving access to them through getter/setter.
Applying this principle is one way of reducing coupling between classes.

You don't need to use getProperty() or setProperty() (known as getter and setter methods), but it is the preferred way of accessing class-level properties in Java. It is a fundamental principle used in Obejct-Oriented programming, called Encapsulation, which defined which Objects should have access to which Properties, based on ownership, privacy levels, hierarchy in the Object tree, etc.
It also allows you to do more advanced things with your properties, such as making them synchronised. This allows you to make sure order is preserved when accessing a property, so that you don't overwrite values out of order.
All this stuff wasn't obvious to me when I was first learning programming either, but as you learn more about programming the reasons and benefits start to appear and make more sense.

It's a general implementation of of the object-oriented principle of encapsulation. There are a lot of cases when there is no or minimal advantage to using setters. However, there are cases when it can save you from hard to find bugs.
Example
Class Person
Integer age;
....
setAge(Integer age )
{
if (this.age<age || age>120)
{
Throw new RuntimeException("The age: "+age+"is invalid");
}
else {
this.age=age;
}
As the program grows in complexity, this can help you catch errors earlier. Since you may not know ahead of time how a program is going to evolve over time, it's often best to err on the side of caution and use getters/setters to start with. Most IDE's make this fairly painless.

Related

Does exist some Java8 convenient manner to incr a property of an object?

Latest project I used java8 , found it's very convenient to process Collection type, it gave me great surprise. But suddenly feel some conventional syntax are so cumbersome, for example I have an Object called BuyerOrderCountStats, every time buyer commit an order, will increase his order count,
BuyerOrderCountStats bocs = ...;
bocs.setOrderCount(bocs.getOrderCount()+1);
Is there some convenient manner for this situation in java 8 which I don't know?
Nothing very special exists in java-8 which would help to solve your problem. However you may design your class (even in Java 1.0) to fit the business logic better. Remove setOrderCount method and replace it with addOrder():
class BuyerOrderCountStats {
private int orderCount;
public void addOrder() {
orderCount++;
}
}
In many cases instead of plain setters you can create better business-logic specific methods which modify the object state.
Tagir Valeev’s answer points you into the right direction. Whenever there is a business logic to model, you should avoid public getters and setters (especially setters) and try to provide appropriate business logic specific update operations.
But since you asked about properties and Java 8 features in general, it’s worth noting that there is an alternative, if you still want (or need) to allow external update operations for a property:
class BuyerOrderCountStats {
private int orderCount;
// may still have getters and setters
public void updateOrderCount(IntUnaryOperator op) {
orderCount=op.applyAsInt(orderCount);
}
}
Then you may change the property like:
BuyerOrderCountStats stats= …
stats.updateOrderCount(count -> count+1 );
You only have to keep in mind, that you can’t use the postfix ++ here as count++ only modifies the lambda expression’s parameter but returns the old value. A prefix increment, i.e. ++count, would work here as it evaluates to the result, but the modification of the parameter would be pointless and misleading. Thus, don’t use neither ++ nor += here, use always + like in the above example. The same applies to other operators.
The updateProperty method can verify whether the result is within the legal range for the property before making a change just like setProperty can do. One advantage of the updateProperty method is, that it can provide locking if needed to avoid concurrent updates. This is something, a get-modify-set roundtrip cannot provide.

When should encapsulation be used? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am completing Sun/Oracle's Trail (http://docs.oracle.com/javase/tutorial/java/TOC.html) and it keeps reiterating the importance of encapsulation.
How important, really, is encapsulation? I mean, if I may need to access the value of a given class field, why would I do so through a method when I could just access the field directly? Since the field would be accessed through its corresponding object anyway, where could this really go wrong?
Is it just for code extensibility purposes? In other words, because that way in the future if I decide I want to somehow alter or sanitize the field before returning it I can?
I'm more looking for an example or two than anything.
Validation.
If you don't use a method, you can't add any validation on the field unless you validate it at every place you want to access the field: unsustainable.
It also separates the data from your class from the outside world. By hiding the actual implementation of data behind methods, you can manipulate your data the way you want (now and in the future) and no other pieces of code will get broken. This allows you to change the way something is represented without a problem, as long as you make sure it can still be returned trough the existing method.
Encapsulation is not only a matter of making getter and setter for a field.
It's about:
Validation (and also consistency)
Hidding implementation (programming to an interface not an implementation)
Getters and setters don't have to reflect the acutal fields. There could be getters (and even setters) for fields which value is calculated on demand
Hide complexity: A getter/setter could peform something more complex than just setting a value
Advanced: Use of a diffrent implementation/modification; patterns like lazy loading which is used in ORM framework wouldn't work if you would use public fields
Even if you as you said "need to access the value of a given class field" you can't be sure that this requirement won't change (cause it will most time).
Actually, I think you're thinking about this the wrong way. The issue isn't encapsulation per se, it's decoupling the behavior of your objects from their data.
Fields are data -- they are part of the internal state of the object. Methods are part of the object's API. Objects shouldn't just be clusters of fields -- if your objects are just dumb collections of data, then that's not object-oriented programming, that's just structured programming.
Objects should be designed to represent real-world entities, and have methods that represent operations you could take on those real-world entities. To put it another way, you don't ask an object for its fields (e.g. getFoo(), getBar()) to pass those to other functions -- instead you should put the relevant operations (e.g. purchase(), validate(), etc.) as methods directly on the object.
That said, there's nothing wrong with having accessor methods -- sometimes you do need to actually retrieve the value. But by making those accessors methods instead of just exposing fields directly, you are implementing information hiding: users of your class don't need to know what the internal state looks like to be able to use it or get data from it.
Basically, in Java (or in any object-oriented language) classes are nouns, and methods are verbs. If you write classes that don't have any verbs, then you're programming in the kingdom of nouns.
Encapsulation allows your object to make guarantees (part of an object's contract), by giving the object control over its own data, which happens to make debugging considerably easier. Consider this class:
public class TravelRoute {
public int distance = 1000;
public int travelSpeed = 60;
public int calculateTravelTime() {
return distance / travelSpeed;
}
}
Any other code is free to set travelSpeed to zero, which will cause all future calls to the calculateTravelTime method to fail. Worse, you will have no way to know who set it to zero, so debugging the problem is going to take a long time.
However, with encapsulation, the class has total control over the value, and can guarantee that it is always valid:
public class TravelRoute {
private int distance = 1000;
private int travelSpeed = 60;
/**
* This is GUARANTEED to return a positive value.
*/
public int getTravelSpeed() {
return travelSpeed;
}
/**
* Sets this instance's travel speed.
*
* #throws IllegalArgumentException if argument is not positive
*/
public void setTravelSpeed(int newSpeed) {
if (newSpeed <= 0) {
throw new IllegalArgumentException("Argument must be positive");
}
this.travelSpeed = newSpeed;
}
public int calculateTravelTime() {
return distance / travelSpeed;
}
}
Now it is absolutely impossible for any outside code to place the object in an invalid state. If anyone tries to do so, the resulting IllegalArgumentException will provide you with an informative stack trace that will immediately expose the culprit.
As a bonus, all other code which uses this class no longer needs to do any checks for its validity, because the object itself can already guarantee that validity. This makes overall development much faster for everyone.

Advanced Item Instance management trouble

I've been developing a massive Role Playing Game. The problem is that I'm having trouble engineering how will I manage the Item and Inventory system. Currently I have something similar to this:
public abstract class Item has 5 Nested classes which all are abstract and static that represent the types of Items. Every Nested class has an unique use(), delete() (Which finalizes the class instance) and sell()(triggers delete) void. They also have optional getter and setter methods, like the setAll() method which fills all necesary fields.
Default: Has base price, tradeability boolean, String name, etc... Very flexible
Weapon: Else than the things that the Default type has, it has integers for stat bonus on being equipped(used in the equip() and unequip() voids). Interacts with public class Hero.
Equipment: Similar to Weapon, just that it has an Enum field called 'EquipSlot' that determines where it is equipped.
Consumable: Similar to default, just that has a consume() void that enables the player to apply certain effects to an Hero when using it. Consuming usually means triggering the delete() void.
Special: Usually quest related items where the 'Tradeable' boolean is static, final and always false.
Now, the way that I make customized items is this.
First, I make a new class (Not abstract)
Then, I make it extend Item.ItemType
Then, I make a constructor which has the setAll(info) void inside.
Then, I can use this class in other classes.
It all looks like this:
package com.ep1ccraft.Classes.Items.Defaults;
import com.ep1ccraft.apis.Item.*;
public class ItemExample extends Item.Default {
public ItemExample() { // Constructor
this.setAll(lots of arguments here);
}
}
then I can do:
ItemExample something = new ItemExample();
And I have a perfect ItemExample with all the properties that I want, So, I can make various instances of it, and use amazing methods like 'getName()' and that kind of stuff.
The problems come to Naming the instances, as I do not know how to make an automated form that will give the instance a Different name from the other instance so they don't collide. Also, I want to implement an inventory system that uses slots as containers and can keep stacks (Stackable items only), also the main feature of it is that you can drag and drop them into other slots (For example, to reorganize or to move to another inventory instance like a bank, or to place in an hero's weapon or equipment slots, if it is allowed) and that you can click on them to display a screen that shows the name, description and possible actions of the Item (Which trigger the previously mentioned delete() and use() voids).
Thank you for reading all that! I know that maybe I'm asking for too much, but I'll appreciate any answers anyway!
So basically, you're asking for a unique identifier for your object. There are probably countless approaches to this, but the three different approaches that immediately come to mind are:
1: A UUID; something like:
java.util.UUID.randomUUID()
Pros: A very, very simple solution...
Cons: It does generate a large amount of bytes (16 + the object itself), taking memory / disk storage, which might be an issue in a MMO
2: A global running number; something like:
class ID {
private static volatile long id = 0;
public synchronized long nextId() {
return id++;
}
}
Pros: Again, a simple solution...
Cons: Even though this is a very simple class, it does contain "volatile" and "synchronized", which might be an issue for an MMO, especially if it is used heavily. Also, What happens after X years of running time, if you run out of numbers. A 64 bit long does require quite a lot of named objects to be created, it may not be an issue after all... you'll have to do the math yourself.
3: Named global running numbers; something like:
class NamedID {
private static volatile Map<String, Long> idMap = new HashMap<String, Long>();
public synchronized long nextId(String name) {
Long id = idMap.get(name);
if (id == null) {
id = 0;
} else {
id++;
}
idMap.put(name, id);
return id;
}
}
Pros: You get id's "localized" to whatever name you're using for it.
Cons: A bit more complex solution, and worse than "2" in terms of speed, since the synchronzation lasts longer.
Note: I couldn't figure out how to make this last suggestion faster; i thought of using a ConcurrentHashMap, but that won't work since it works on a lower level; i.e. it will not guarantee that two thread does not interfere with each other between the idMap.get and the idMap.put statements.

extract boolean checks to local variables

Sometimes i extract boolean checks into local variables to achief better readability.
What do you think?
Any disadvantages?
Does the compiler a line-in or something if the variable isn't used anywhere else? I also thought about reducing the scope with an additional block "{}".
if (person.getAge() > MINIMUM_AGE && person.getTall() > MAXIMUM_SIZE && person.getWeight < MAXIMUM_WEIGHT) {
// do something
}
final boolean isOldEnough = person.getAge() > MINIMUM_AGE;
final boolean isTallEnough = person.getTall() > MAXIMUM_SIZE;
final boolean isNotToHeavy = person.getWeight < MAXIMUM_WEIGHT;
if (isOldEnough && isTallEnough && isNotToHeavy) {
// do something
}
I do this all the time. The code is much more readable that way. The only reason for not doing this is that it inhibits the runtime from doing shortcut optimisation, although a smart VM might figure that out.
The real risk in this approach is that it loses responsiveness to changing values.
Yes, people's age, weight, and height don't change very often, relative to the runtime of most programs, but they do change, and if, for example, age changes while the object from which your snippet is still alive, your final isOldEnough could now yield a wrong answer.
And yet I don't believe putting isEligible into Person is appropriate either, since the knowledge of what constitutes eligibility seems to be of a larger scope. One must ask: eligible for what?
All in all, in a code review, I'd probably recommend that you add methods in Person instead.
boolean isOldEnough (int minimumAge) { return (this.getAge() > minimumAge); }
And so on.
Your two blocks of code are inequivalent.
There are many cases that could be used to show this but I will use one. Suppose that person.getAge() > MINIMUM_AGE were true and person.getTall() threw an exception.
In the first case, the expression will execute the if code block, while the second case will throw an exception. In computability theory, when an exception is thrown, then this is called 'the bottom element. It has been shown that a program when evaluated using eager evaluation semantics (as in your second example), that if it terminates (does not resolve to bottom), then it is guaranteed that an evaluation strategy of laziness (your first example) is guaranteed to terminate. This is an important tenet of programming. Notice that you cannot write Java's && function yourself.
While it is unlikely that your getTall() method will throw an exception, you cannot apply your reasoning to the general case.
I think the checks probably belong in the person class. You could pass in the Min/Max values, but calling person.IsEligable() would be a better solution in my opinion.
You could go one step further and create subtypes of the Person:
Teenager extends Person
ThirdAgePerson extends Person
Kid extends Person
Subclasses will be overriding Person's methods in their own way.
One advantage to the latter case is that you will have the isOldEnough, isTallEnough, and isNotToHeavy (sic) variables available for reuse later in the code. It is also more easily readable.
You might want to consider abstracting those boolean checks into their own methods, or combining the check into a method. For example a person.isOldEnough() method which would return the value of the boolean check. You could even give it an integer parameter that would be your minimum age, to give it more flexible functionality.
I think this is a matter of personal taste. I find your refactoring quite readable.
In this particualr case I might refactor the whole test into a
isThisPersonSuitable()
method.
If there were much such code I might even create a PersonInterpreter (maybe inner) class which holds a person and answers questions about their eligibility.
Generally I would tend to favour readability over any minor performance considerations.
The only possible negative is that you lose the benefits of the AND being short-circuited. But in reality this is only really of any significance if any of your checks is largely more expensive than the others, for example if person.getWeight() was a significant operation and not just an accessor.
I have nothing against your construct, but it seems to me that in this case the readability gain could be achieved by simply putting in line breaks, i.e.
if (person.getAge() > MINIMUM_AGE
&& person.getTall() > MAXIMUM_SIZE
&& person.getWeight < MAXIMUM_WEIGHT)
{
// do something
}
The bigger issue that other answers brought up is whether this belongs inside the Person object. I think the simple answer to that is: If there are several places where you do the same test, it belongs in Person. If there are places where you do similar but different tests, then they belong in the calling class.
Like, if this is a system for a site that sells alcohol and you have many places where you must test if the person is of legal drinking age, then it makes sense to have a Person.isLegalDrinkingAge() function. If the only factor is age, then having a MINIMUM_DRINKING_AGE constant would accomplish the same result, I guess, but once there's other logic involved, like different legal drinking ages in different legal jurisdictions or there are special cases or exceptions, then it really should be a member function.
On the other hand, if you have one place where you check if someone is over 18 and somewhere else where you check if he's over 12 and somewhere else where you check if he's over 65 etc etc, then there's little to be gained by pushing this function into Person.

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