Builder pattern: When should the model members be final? [closed] - java

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 2 years ago.
Improve this question
The builder pattern is one of the most popular creation patterns, and it has numerous benefits. I specifically want to understand if immutability of the model object itself is one of the key benefits. All the while I thought it was, but I could not find any backing documentation on the same. Consider this scenario, you are creating an object from a network call (from json let's say). We create model objects and it has a Builder inline. This is what everybody does. The members of the model are also private. Since this is a network object, the members won't have setters. My doubts are
With builder securing object creation, do we need to make members private.
Can we instead keep them public final and eliminate need for getter()
In general (irrespective of the above two points), shouldn't all non-settable members be final? I don't see many people making members final, why is it so?
Is this a good approach or not?

I'm really having my pain with the example you chose. Parsing JSON into objects is really something you can delegate to JSON-B / Jackson / insert JSON library here nowadays. But I get it that we're on a theoretical level here.
Wikipedia just says: The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
From the theory, the builder pattern neither forces immutability nor is it any aspect of it.
With builder securing object creation, do we need to make members
private.
You don't need to do anything. But there is one simple stylistic rule: You either access members by getters and setters or by making them public. But not both.
Can we instead keep them public final and eliminate need for getter()
Final would imply immutability - if that's what you want to achieve, you can do so.
In general (irrespective of the above two points), shouldn't all
non-settable members be final? I don't see many people making members
final, why is it so? Is this a good approach or not?
You only make members final if you want them to be immutable or if they are constants. Otherwise it makes no sense. With your example, I can only think of constant values? However, you cannot make members final without setting their value. You either need to set them in the constructor or initialise them to null. But having final null values most likely doesn't serve any purpose.
The better approach for such values would be really just not to define a getter or setter and making it private. But then you again have just some useless null values laying in your class.
To be frank, this whole discussion about getters/setters or public is opening Pandora's box. I have had too many discussions about this by now, and it just doesn't matter which way you do it. In the end both serve the same purpose: setting and retrieving values.
Regarding final values: I don't have to use immutability often to be frank, in my area of development I can't really think of any case I've used it so far. The only thing I use it for is to mark constant values which I don't want to be changed by anything.
In the end, this whole discussion about design patterns is tedious. A builder is just a helping structure. You have to find your way on how to use it for your use case and in your company. Just remind you of the fact that it's whole purpose is to make the creation of complex objects more accessible.

Related

Does encapsulation of class methods/fields matter if they are only accessed by the class itself? [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 2 years ago.
Improve this question
Short context: I made a tetris clone in java (all the game data and methods are a Class) and I am concerned about whether encapsulation matters in this case.
Almost all of the fields and methods are marked as "default", without any getters and setters because the user is not supposed to access them.
Methods manipulate variables directly without any arguments passed, of course only when the thing it is manipulating is unique (there can not be two current pieces, two next block lists, two held pieces and so on)
Do I really need getters and setters if the user is never supposed to get raw members of the class? Methods just directly get and set the values. If I have a simple int that I want to get or set, I am just doing it directly.
No return value, if one exact thing is supposed to happen every time. For example: if a collision happens during spawning, gameOver() is triggered immediately instead of returning false, then doing it outside of function. I chose to not have a return value because it is much simpler to do it inside function instead of surrounding each function call with an if statement doing the same thing.
Do I need to fix some of these things, and how should I, preserving stability in both readability and performance?
It does not.
Why? The understanding is that a class’s fields and methods are working in conjunction towards a common goal. So they are not enemies or careless actors that you have to protect yourself against.
It is only to prevent external actors from mucking up class invariants that you hide your fields and methods as much as possible and expose only that which is necessary.
If you have to use setters and getters to enforce discipline in the code within a class, then you have much bigger problems to handle than maintaining proper encapsulation (and other OO principles.)
No, you do not need getters and setters if you do not intend on anything accessing the member variables from outside of the class.
In your case because the member variables are only accessed from within the class itself then the access modifier(s) should be changed to private.
The use of the default keyword means that you do not want to provide an access modifier and that variable should be available to any other class in the same package.
More info can be found Here

java field qualifier best practice [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 7 years ago.
Improve this question
It is a good practice to use a proper qualifier between private, protected, private or default. But is there any other reason like performance or JVM optimization drawback default is used instead of private? As an example
public class Class1{
Class2 class2;
}
And where variable class2 could have been private.
Also if the variable is autowired or injected by DI framework. Framework calls field.setAccessible(true). Does that make any difference as per the performance or optimization.
I think I now understand the motivation for this question.
The reasons for using the correct access modifiers on variables in normal Java are well understood. Basically, it is all about modularity, encapsulation, avoiding unwanted / harmful coupling and so on.
What about Spring?
Well it is true that Spring can circumvent normal access rules and allow you to inject private variables. However, from what I understand, you have to deliberately annotate your private fields with #autowire or similar for this to occur. What is actually going on here is that Spring is following an "instruction" that is explicitly declared in the source code by means of the annotation. Spring XML-based wiring won't let you inject a value into a private field or using a private setter.
In the light of this, the argument that Spring allows you break private encapsulation is ... while technically true ... ultimately self-serving. Sure, you can do it. But you have to do it explicitly, deliberately ... by design. And it ONLY happens when the objects are wired.
By contrast, if you are sloppy about the modifiers, and declare every instance variable as public or package private, then you are leaving open the possibility of all sorts of lazy, ill-considered, or even accidental breaking of encapsulation. And even if you (the original author) are disciplined, the next guy reading / maintaining your code can't be sure that you have been disciplined. He has to check ...
So how do you "force" someone to toe the line?
It is probably best to persuade rather than force, but the way to force people to write decent code is to get your project manager / quality manager to adopt a coding standard, and insist that it is followed. (But this can be easier said than done if your management doesn't understand the long-term costs of poor quality.)
The real reason we have these pesky coding standards is so that the code can be maintained ... by someone other than the guy who wrote it. A good IT manager will understand this. A good PM will understand this. A good programmer will understand this.
If it's not meant to be used by any other application - then just make it private. The point is OTHER developers can't read your mind. And if it's not private, then they will think, that it is meant to be used outside of class.

What are the things to be kept in mind when aiming for a good class design? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Yesterday I have attended interview in one Leading IT Service company. Technical interview was good, no issues, then I have moved to another set of round about Management, Design and Process. I have answered everything except the below question.
Question asked by interviewer:
Let say you are developing a class, which I am going to consume in my
class by extending that, what are the key points you keep in
mind? Ex, Class A, which has a method called "method A" returns a Collection,
let say "list". What are the precautions you will take?
My Answer: The following points I will consider, such as:
Class and method need to be public
Method 1 returns a list, then this needs to be generics. So we can avoid class cast exception
If this class will be accessed in a multi-threaded environment, the method needs to be synchronized.
But the interviewer wasn't convinced by my points. He was expecting a different answer from me but I am not able to get his thought process, what he was excepting.
So please provide your suggestions.
I would want you holding to design principles of Single Reaponsibility, Open/Close, and Dependency Injection. Keep it stateless, simple, and testable. Make sure it can be extended without needing to change.
But then, I wasn't interviewing you.
A few more points which haven't been mentioned yet would be:
Decent documentation for your class so that one doesn't have to dig too deep into your code to understand what functionality you offer and what are the gotchas.
Try extending your own class before handing it out to someone else. This way, you personally can feel the pain if you class is not well designed and thereby can improve it.
If you are returning a list or any collection, one important question you need to ask is, "can the caller modify the returned collection"? Or "is this returned list a direct representation of the internal state of your class?". In that case, you might want to return a copy to avoid callers messing up your internal state i.e. maintain proper encapsulation.
Plan about the visibility of methods. Draw an explicit line between public, protected, package private and private methods. Ensure that you don't expose any more than you actually want to. Removing features is hard. If something is missing from your well designed API, you can add it later. But you expose a slew of useless public methods, you really can't upgrade your API without deprecating methods since you never know who else is using it.
If you are returning a collection, the first thing you should think about is should I protect myself from the caller changing my internal state e.g.
List list = myObject.getList();
list.retainAll(list2);
Now I have all the elements in common between list1 and list2 The problem is that myObject may not expect you to destroy the contents of the list it returned.
Two common ways to fix this are to take a defensive copy or to wrap the collection with a Collections.unmodifiableXxxx() For extra paranoia, you might do both.
The way I prefer to get around this is to avoid returning the collection at all. You can return a count and a method to get the n-th value or for a Map return the keys and provide a getter, or you can allow a visitor to each element. This way you don't expose your collection or need a copy.
Question is very generic but i want to add few points:
Except the method which you want to expose make other methods and variable private. Whole point is keep visibility to minimum.
Where ever possible make it immutable, this will reduce overhead in mutithreaded environment.
You might want to evaluate if serializability is to be supported or not. If not then dont provide default constructor. And if serializable then do evaluate serialized proxy pattern.

Good practice when accessing a field in a class [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
When you have to access a "member variable"/field in a class, is it good practice to access it directly or call the getter and setter? and why?
I see almost only benefits in making your fields private and only provide access through a getter and possibly a setter
controlled access. If you only want to provide read access, or only write access you can only achieve this by using getters/setters
if you want to fire PropertyChangeEvents for bean properties, you can include this code in your setter. Otherwise all calls which modify this field directly should trigger a change event as well
I personally find it easier to discover in my IDE who modifies the field. The only direct access to the field is in the class (since it is a private field), and all external changes go through the setter. This allows for faster debugging than having to use a field watchpoint
subclasses who want to do something extra when the field change can override the setter, call super.set and do something extra
The only possible drawback I can think of is that it requires a bit more code to write (for the getters and setters), and a bit more code for accessing the field from outside the class. But with the current IDEs is this a pretty lame excuse
Some extra literature:
link1, link2
Call the setter/getter rather than accessing directly. That way any extra required code in the setter/getter will be run.
Getter/ Setter allows for lazy instantiation, which is often a way to go. Additionally, this way you have a controlled access to your variables (both for yourself and as part of any API you may want to expose); ability to hide implementation of initialization etc are also very important.
The biggest benefits of S/G in my opinion is reduced risk of someone modifying it without your control. A small example .. consider that a getter may give you .. a copy of the original instead of an original.
Benefits are multiple, when given a choice, choose setter/ getter for the benefits of data encapsulation and more control.
If it is a member of the calling class, access it directly. Otherwise use the getter/setter methods.
Why? You should not be creating getter/setter methods just so that the calling class can access its own members. Otherwise you should use the getter/setter methods for the reasons elaborated by others.

Getters on an immutable type [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 4 months ago.
Improve this question
I am writing some immutable types in Java and wonder about how to name the accessor methods.
The Java Bean specification says that the names of accessors should be getX or isX, but since the fields are final, there is no setter and the fields are more like attributes than properties.
There for I'd prefer naming the getter methods like:
public T x()
rather than
public T getX()
Please note as an example:
public int java.lang.String#length()
(Which might have been specified so early in the Java history, so the conventions where not there yet.)
The immutable objects expose means to create modified versions of themselves through methods which I've tried to name like a verb rather than MyObject MyObject#setX(), this should limit the risk of the user calling setX() and think that the object has changed. So: MyObject MyObject#shine(newShineLevel).
This is not always possible easy though. How would you name a method for adjusting an endpoint in a rectangle other than Rectangle.setUpperLeft()? Rectangle.adjustUpperLeft maybe, but now we're just moving away from the conventions.
I guess the question is relevant for all languages, but this questions concern Java in particular.
If these classes may be used with any reflection based framework then you are better off staying with the getX convention. For example, accessing properties in JSPs and other templating systems via an expression "x.y" requires that the object have a method getY().
In my opinion, the get prefix is really only mandatory if you're writing a bean. There are lots of examples of where get is not used. not only String.length(). You find it in the primitive wrapper classes (intValue(), doubleValue(), booleanValue(), ...), enums (name() and ordinal()) and collections (size()), and the way annotations were design also seems to encourage the get-less style. (Josh Bloch covers the subject in Effective Java, and advocates the more readable get-less style unless you're actually writing a bean.)
So: Use the get prefix and your object can be used as a bean. Ditch it, and your code gets easier to read. It's up to you to decide what you think is more important.
Even for immutable types, the convention getX() still stands. Some examples:
java.lang.Integer.getInteger()
java.lang.Boolean.getBoolean()
It is true that there are also many examples such as java.lang.String.length(), but the common convention is to use getX. Just as mentioned in the answer below, it is crucial to separate between an atomic get operation, and a method which does some calculations on the data.
Also worth mentioning that plain java beans in many frameworks depend on the fact that getters/setters are conveniently named getX and setX.
The convention in Java for accessing properties of a class -- including immutable classes -- is to use the get and set prefixes so I would recommend using public final T getX().
The reason the length() method on a String isn't called getLength() is because there is no property called length on the String class.
I'd stick with the "get" convention simply because so many other tools work with it. Jakara Commons BeanUtils for example. Lots of tools/libraries will work by default if you have the right naming, but require configuration if you've deviated from the bean accessors convention.
I'm not disagreeing with you reasoning for deviating, I just think you're probably better off in the long run sticking with the get/set convention.
It's a good idea to use get--never mandatory, but people will automatically know what it's for.
Get does not imply that you have that as a member variable, in fact it's supposed to hide that fact. It can easily be giving access to a computed value.
size(), length(), etc were created before Borland found they needed the get/set concept to implement their GUI builder (I'm not sure exactly who came up with the idea, but that was the reason).
intValue, doubleValue etc are not getters, they are converters and therefore are named differently.
Now, all that said, if you really want to use x or getX it is your choice. getters and setters are no longer needed for most decent toolsets, they will use annotations instead--just be ready for a few people to take a few extra seconds typing "get" followed by "ctrl-space" and not finding what they are after.

Categories