Why is it bad practice to have int attributes?

Asked

Viewed 1,775 times

28

I saw in the answer to that question /questions/17015/qual-o-uso-de-uma-variável-estática-ou-final-em-java/17136#17136, that:

It is bad practice to have int attributes, unless they are "constant" or you want to simulate structures like the C language.

'Cause this is bad practice?

I wish to index each object in my class with a unique index. For this I intend to use a counter.

private static int contador = 0;

public final int indice;

public Objeto(String nome){
        this.nome = nome;
        this.indice = contador++;
}

There would be a "good practice" alternative to this implementation that I made?

I declared the attribute indice as public, however final. There would be a need to do so private and a method getter, seeing that I have final?

  • 1

    I think the utluiz just typed wrong in his answer. By the context I think he wanted to write "public attributes" but for whatever reason write "int attributes" and it passed beaten. There’s nothing wrong with int attributes.

5 answers

32


Good practice

I’ll tell you what’s more important on this subject: they invented a plague on the developers' minds called "good practice".

The world of development will be much better when people stop talking about it. That’s one way of saying "do it the way I’m talking and don’t argue". The same goes for "bad practice" which is a "I’m saying it’s bad and bad". So you don’t have to explain anything. If it were good or bad, the person would explain. So the developer reading that can decide on their own if it’s good or bad and when to use it.

Almost everything that exists can be good or bad in most situations, but without understanding why, it serves for nothing. Everything has an exception, of course. So you said "good/bad practice," so get away from the answer. Either the person does not know what he is talking about or is biased (of course it may be just laziness/haste to answer, but how will you know?).

And what you’re calling attribute is actually called field.

int as "attribute"

That answer linked specifically is far beyond the scope of her question and then falls into the problem of not making you understand what really mattered.

It is completely absurd to say that an "attribute"/field should not be int. In this specific case I would say that there is not even a situation that prevents, creates difficulty, and especially is a "bad practice":). A field can be int whenever necessary.

Of course he shouldn’t be int if it is not necessary to be. But here is what I always say: the right is to do the right, not to do what is "good practice". And the right one is only known in the specific case. Every time you do the right thing somewhere and try to transpose it into another situation, you’re doing it wrong. Every situation is unique. Some coincidentally must have the same solution.

I think the answer meant that it’s not good to have an exposed public field and got confused in writing, that’s all.

Without going into too much detail because this is not the issue here, this is something that can be bad in many situations, especially in Java, and it is recommended to use a method getter/Setter for access to it. Anyway the phrase is very unfortunate. I am not going to discuss this here (but I disagree with what is said as absolute truth), the subject is different, but Linkei questions below that talk about the subject, if you need more information you can still ask a new specific question.

Your example

Your specific case is using the contador as private. Ok. The problem with what you’re doing is that it creates a running condition in concurrent environments. You can have the counter increasing by 2 or more before being used in each one, then you will have two objects with the same index. It’s very rare to happen, which is why the day it happens will be very difficult to reproduce and find out why.

What you’re doing is not the best idea. I would try to do otherwise, but since I don’t know what the problem is, the requirements, anything I say will sound like "good practice".

###Getter/Setter

The indice is public. It is no problem to be final and public. This in itself does not create any problem. It is usually better that your access is done by a method accessor (see in the questions below the why), but only usually, if there is no reason for it, can leave as public.

I agree that in Java, which is a language that does not like much of syntatic sugar, It is usually a good idea to access the fields by a method to ensure the best maintenance. If you need to change the form of access in the future you will not need to change all the codes that consumed your class. In other languages this can be more convenient and give more freedom, if the person knows what he is doing.

In Java, to expose a field publicly (any type of field) you must be sure that you will never have changes in the way you access it. It’s rare to be so sure. But there are cases.

The rest of what they talk about is a silly theory.

The ramaral response has an example of how to access with an auxiliary method. Note that you do not have a Setter, after all it would make no sense to have in a field marked as final.

Completion

Never do anything because someone told you it’s right, learn because it’s right. Then you may find that the person who told you this may be wrong.

You were right to question here.

To speak the truth I think that none of the answers in these questions show well these questions in full, but reading everything already helps to understand and form a own opinion.

  • 8

    Fortunately I have already overcome the obsession phase of "good practices", not only in programming but also in life (fruit of experience and age). Why eat shrimp with a knife and fork if it’s much easier to eat it by hand? Don’t let "good practice/manners" influence you in the answer.

  • 3

    @ramaral of course that if the shrimp is shelled, it is easy and can be even desirable to eat with fork and knife, especially if you take into consideration where you are eating. There is always an exception for everything :) But the metaphor is good, there are people who are chic to do this, but those who are really chic know that the hand can be the best tool many times :) I don’t know if I understood the last sentence.

  • 2

    "answer" does not refer to yours but rather to the question of how to eat the shrimp. It (the phrase) means that it should not only be the existence of "good practice" that guides it, it should also take into account the context.

  • 2

    "It is completely absurd to say that an attribute should not be int". I fully agree!

  • 1

    @ramaral, experience and age is what many devs still don’t have. We will all get there one day and no longer need empirical knowledge from others. But like the mustache says, "to tell the truth I think that none of the answers in these questions show this question well". There are situations that are difficult to clarify even if you waste a lot of saliva. " Instead of speaking in good practice, explain why", but this explanation will often be Aza and will not stray too far from "good practice". There are wrong "logical" responses, and there are wrong "good practices". Normal. The term chosen changes nothing.

  • 2

    @Caffé I have nothing against "good practices", just think that they should not be used because they exist. Their use is conditioned to a context. There are times when I eat shrimp with a knife and fork, because the context recommends it. The problem of the use of "good practices" is, most of the time, the understanding where/when they should be used. At the moment I am leaving it to development to dictate whether or not it is necessary to use it, unless it is clear from the outset that it benefits.

Show 1 more comment

10

In relation to "It’s bad practice to have attributes int(public),...." I do not see why, how much can be questioned if having public fields in general is good.

The case presented has nothing to do with "good practice" but with "common sense"/functionality.

In this example, being final, I see no problem being public, it cannot be modified.
However, because in Java the use of getter/Setter is so rooted, the use of a getter, if you need to access it externally.

public class UmObjeto{

    private static int contador = 0;
    private final int indice;

    public UmObjeto(String nome){
        this.nome = nome;
        this.indice = contador++;
    }

    public int getIndice(){
        return indice;
    }
}

It would also make sense if he were a "class constant", in which case he would have to be also static, what is not possible in this case.

  • Makes sense final public when the attribute needs to be read outside the class but should only be set by the constructor. And why declare the getter? Would that be good practice? D

  • @Caffé "Would it be good practice?" In Java, which has not Properties, in general terms it is. Is there a need to always apply it? No. In this particular case, I agree with you, perhaps there is no such need, however, because in Java the use of getter/Setter is so deep-rooted, its use should be considered.

  • 1

    I agree, ramaral. And here we are in good old-fashioned good practice, always making life easier for those who are sharing experience and also the life of those who are starting out, eager to produce soon, willing to make a cool code early on, even before you still understand 100% of everything you are doing. Three cheers for good practice! :D

  • 1

    Good practices can either serve as a guide while not "picking up" experience, or can be ignored. Deep research into the reason behind good practice is needed.

5

Competition

If this class can be instantiated by more than one thread, declare the counter as Atomicinteger to ensure its integrity. Example:

private static AtomicInteger contador = new AtomicInteger(0);

And, to increase:

this.indice = contador.incrementAndGet();

How to use attribute int or Integer

Use the int when you want the default value Zero and the Integer when you want the ability to have an attribute null.

In your case, if there is no concurrent constructor execution (class instance by more than one thread), int will do very well.

As to declare a getter for the index

Depends on the nature of its object.

If he’s a simple data structure, without many other attributes, if it carries little state, little or no behavior and the state changes are simple or nonexistent, declare as public instead of using getter serves.

Now, if this object is a important entity in the system, with complex behaviors and state changes, eventually various public attributes, hence a getter may fall better because the class may have more need for encapsulation, uniform usage, consumption in various parts of the code, and suffer many changes.

Anyway this is just a guide because some prefer at all times declare getters and never expose the class fields publicly - for the sake of standardization. Standardization is useful because if it’s already decided how to do it, you don’t have to spend energy making the decision every time, and as the getter is the safest method, so to speak, it serves at all times.

I personally don’t know any reason against this standardization - it just takes more work to encode.

Finally, it might be worth mentioning that there are tools that require you to declare getters and setters even in simple data structures. In JSF, for example, you declare in the class getName() and setName() and in the code facelets you write only object name. both for reading and writing.

  • I suppose, then, it’s safer to use AtomicInteger. Especially to create indexes that are unique for each object in a class.

  • 1

    @Pedrohenriquen.Vieira If these indexes will be increased in code that must support competition (environment multithreading, code tread safe), yes. In practice: if this question constructor can be invoked by more than one thread, use Atomicinteger.

1

For the purpose of clarification:

int is a primitive type. Variables of type int store the binary value to represent the desired integer. int.parseint("1") makes no sense because int is not an object, so it has no methods. int in java are primitive types and, we do not create objects with primitive types.

Integer is a class. Integer type objects store references to other objects. This is good, saves memory (not good practice, is fact). This is an example of transforming a string into an Integer object through a static method Integer.parseint("1").

To be more specific, Integer is a class with a single attribute of the primitive type int used when you want to have the power to assign NULL to the object, not necessarily zero. This is used in various situations and interesting for collections and generic types.

Here are classes of the Wrapper pattern to represent primitive types in objects:

byte / Byte

short / Short

int / Integer

long / Long

Boolean / Boolean

char / Character

float / Float

double / Double

These classes extend from Object and primitive types not because they are not objects. To use Generics are needed objects, not primitive types.

Since Java 5 we have autoboxing and the conversion of a primitive to wrapper object is done automatically, but in some specific versions of JVM there were performance problems in these conversions. Maybe that’s what someone meant by "bad practice".

Remembering that primitive types can be compared with ==, while objects must be compared with . equals().

-1

This has already been mentioned in the previous answers, but I will point out. In practice, the biggest difference is that a Integer for being null (has no value assigned) and a int is initialized with zero (You can’t tell if the value is zero even or if you just haven’t been assigned any value). And conceptually, if your application is object-oriented, it would be better if you had objects rather than primitive variables.

Declare an object Integer instead of a variable int provides you with more resources, but if you don’t use any of them, it won’t make a difference in practice. It is defined as good practice because one day you may need to use, and then your application will already be prepared for it. I have dozens of applications I’ve never used, but will...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.