Does my builder need to be inside the class it builds? - java

I've just read a fantastic example of a builder pattern.
In my program I'm creating a series of playerCharacter entities, which can be constructed in various ways, with some compulsory fields and some that can be added on as extra or added latter on (after construction). So, after reading the above post, it seems as though I need a builder pattern.
Do I have the option of the builder and super class (here, in the example Pizza and builder) sharing some of the methods? Is there a neat, known solution to this?
For instance if, in the above example (of the pizza), at a later time we had a method of Boolean isPizzaCold() and void heatTo(int degrees) and we wanted the pizza to return false to start with, as it's 'built' hot, and later to let the pizza 'get cold', so that it cools. How would I do this such that they share the same methods?
[edit: as per Joeri's suggestion I've changed the method example.]

If you take the builder out of the class, it's still a builder. A builder is in the first place a convenient way to construct your object, it doesn't always need to be the only way. You could even state that creating an object is clearly a separate responsibility, and that it is cleaner to separate it (like a factory - builder pattern combined). I personally believe it depends mostly on the complexity of the creation.
No, your object and builder classes cannot share methods. The only way to share method is through inheritance, which clearly is not to be used here.
Your builder is a throwaway object, and the object it constructs is clearly of a different class. The only thing you can do is store the requested value, and call the appropriate setters automatically after the object was built.
void setTemperature(int t){
this.temperature = t;
}
Pizza build() {
Pizza pizza = new Pizza(... usual constructor stuff);
pizza.setTemperature(temperature);
return pizza;
}
Also, I wonder if void setTemperature(int) makes sense. void heatTo(int degrees) makes more sense to me :)

I don't really see the relation between your question and the builder pattern. If you want a method setTemperature() and a method isCold(), just add them to the Pizza:
private static final int COLD_THRESHOLD = 40;
private int temperature = 70;
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public boolean isCold() {
return temperature <= COLD_THRESHOLD;
}

Related

Factory method pattern - when should the 'Creator' class implement the Factory method?

In Factory method pattern there are 2 lead implementation (correct me if I'm wrong):
When Creator class is being abstract and not providing an implementation for the Factory method:
public abstract class CasinoGameCreator {
public void playGame() {
ICasinoGameType gameType = createGame();
gameType.play();
}
public abstract ICasinoGameType createGame();
Or, we can have the Creator class be a concrete class that provides implementation for the Factory method:
public class CasinoGame {
public static CasinoGame createGame(GameType type) {
if (type == GameType.BlackJack) {
return new BlackJackGame();
} else if (type == GameType.Poker) {
return new PokerGame();
} else {
return null;
}
}
}
Is there any strong preference when to use each implementation? if there is, in what general situations we whould prefer using the 1st approach over the 2nd?
Option 1 is following the Open/closed principle. This means: it is open for extensions (as different subclasses can implement different ways of creating a game); but it is closed for modification - the behavior of playGame() is fixed. Well, it is not; but if you use this pattern, you really would want to make playGame() to be final. If you have such an abstract class with an implementation X; and an abstract method Y (used within the other method X); than it doesn't much sense to allow subclasses to change X.
Option 2 is helpful when you are really sure about the different type of games; meaning: chances that this enum will ever change are small. Given the idea of games in casino; I very much doubt that this would be true here. Probably you could add a new game every other day. And then, you have to turn to each place that switches over the GameType and adapt that code.
So, given those thoughts, option 1 would be the first choice - because you can simply add a new game type by creating a new subclass of your creator class. This means: you can add a new game without touching the code responsible for other games.
Of course: if you would pick a different example, the requirements might be different, and then option 2 might have certain benefits.

Better to change parent's field or override getter?

Let's say I have a Projectile class which acts as a base class for all projectiles in my game. This contains default values for maximum speed, gravity coefficient, bounce coefficient, etc.
public abstract class Projectile {
protected float maxSpeed = 100.0f;
protected float gravityCoefficient = 1.0f;
protected float bounceCoefficient = 1.0f;
...
}
I then have a bunch of subclasses, each of which may choose to override some of these default values.
Which is the better approach here?
1. Set field values in child constructor
public class Arrow {
public Arrow(){
super();
maxSpeed = 200.0f;
}
}
2. Make child override getter
public class Arrow {
public float getMaxSpeed(){
return 200.0f;
}
}
I am inclined to say that the first approach is better, since it means the field can be accessed directly without the need for any extra function calls. However, it does mean that the value is set twice during object creation, once by the parent and once by the child.
Am I missing anything here? Is there, perhaps, another approach?
Intuitively, the maximum speed of any particular projectile is unlikely to vary over its lifetime (even in the case where different instances of the same type can have different maximum speeds), therefore I would favour a final field for it. I would also favour making it final - I very rarely use non-private fields, other than for genuine constants.
As you have some state (the field) for Projectile, I would avoid allowing the confusion of having the maximum speed has revealed by getMaxSpeed differing from the field.
I would probably design it like this:
public abstract class Projectile {
private final float maxSpeed;
protected Projectile(float maxSpeed) {
this.maxSpeed = maxSpeed;
}
// Only if you really need this...
protected Projectile() {
this(200f);
}
public final getMaxSpeed() {
return maxSpeed;
}
}
public class Arrow extends Projectile {
public Arrow() {
super(100f);
}
}
The gravity coefficient and bounce coefficient may be treated in a similar way - or if all of these really act as "the same values for every instance of a particular type" you could introduce a new class to represent these constants, which separates the varying state of instances of a type from the constant restrictions/coefficients - and each instance could just have a final reference to an instance of that new class. Unfortunately Java (and at least some similar languages) don't really model this kind of hierarchy well. It's always an annoyance :(
you should have a setter and use it, that is what setters are for. It will allow you to keep the field private. The other benefit is that using Java Bean convention will allow you to use libraries such as Apache Commons BeanUtils to populate and manipulate your Objects. You will also be able to persist your data in DB or file.
public abstract class Projectile {
private float maxSpeed = 100.0f; // default
protected void setMaxSpeed(float newSpeed) {
maxSpeed = newSpeed;
}
}
public class Arrow extends Projectile {
public Arrow() {
super();
setMaxSpeed(200.0f); // arrow specific values
}
}
First approach. Declare a method named modifyDefaults() in your abstract base class. Implement it in each class and call in the constructor so that whenever someone sees abstract class, it can be concluded that you will be modifying defaults in children.
Or just hand over responsibility of Projectile creation to a projectileFactory if there are only a few deciding parameters.
Your inclination towards the first answer should be. It does clearly state the following:
The child class has it's responsibility of creating it's own instance variables (properties)
Overriding of getter, though sounds good at certain views, doesn't usually give a good maintainability. Constructor clearly states the extra set of property defaults whatsoever very cleanly.
I'm not sure about your design, but if you have your super class which doesn't have state of it's own, try making it abstract and the design changes completely than we discussed in that case (option 2 might be considered that time).
For java, compiler optimization and JIT optimization are of great importance for the improvement of performance.
The second piece of code will be much more easier to be optimized with no worry of extra operations.

Java: When to use attributes, when to use method parameters?

I tried googling and searching for this question but somehow couldn't find anything relevant about it. I'm wondering if there is a bbest-practise guide on when to use attributes in a class and when not, but rather use parameters to the single methods.
Many cases are clear to me, e.g.
public class Dog
{
private name;
public setName(...) {....}
}
But sometimes it's not clear to me what's better to use.
E.g. the following, either use:
public class calculation
XYZ bla;
public calculation(XYZ something)
{
this.bla = something;
}
public void calc1()
{
// some calculations with this.bla
}
public void calc1()
{
// some more calculations with this.bla
}
public XYZ getBla()
{
return this.bla;
}
}
or maybe do:
public class calculation
public calculation() {}
public static XYZ calc1(XYZ bla) // maybe static, if not dependant on other attributes/instance-variables etc
{
// some calculations with bla
return bla;
}
public static XYZ calc1() // maybe static, if not dependant on other attributes/instance-variables etc
{
// some more calculations with bla
return bla;
}
}
I mean you can argue for both cases. I see advantages and maybe disadvantages for both different styles, but somehow I prefer the second one as far as long as there are not too many arguments/parameters needed. Sure, if I need many many more attributes etc., then the first one will be better, simpler etc. because I dont need to pass so many parameters to the method...
Just a question of personal style?
Or how to decide for one approach?
Thanks
EDIT: A better example: I'm curently doing much image processing and the question would be wether to store the image internally in the state of the object or not. I'm currently NOT doing it because I'm using static methods, and psasing the image itself I to each method:
public class ImageProcessing
{
/**
*
*/
public static Mat cannyEdges(Mat I, int low, int high)
{
// ...
return I;
}
public static Mat cannyEdges(Mat I)
{
return ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES);
}
/**
*
*/
public static Mat getHoughLines(Mat Edges, ...some_conf_vars...)
{
// ...
return I;
}
}
and then I'm calling it from the outside like this e.g.:
// here: read image to I...
Mat edges = ImageProcessing.cannyEdges(I, 20, 100);
Mat lines = ImageProcessing.getHoughLines(I);
// draw lines...
question is: Does I belong to the state of the object? Would it make sense to convert to non-static and then use for example:
// here: read image to I...
ImageProcessing IP = new ImageProcessing(I);
IP.cannyEdges(20, 100); // CHANGE OF cannyEdges: Also save `edges` internally as property!?
IP.calcHoughLines(); // also save the lines internally maybe?
Mat lines = IP.getLines();
// draw lines...
is this nicer?
The question arising is then again: Should I for example store the result of getHoughLines() (i.e. the lines) internally or should I directly return it to the caller!?
I can use some examples:
public class Multiplier {
private int number;
public Multiplier(int number) {
this.number = number;
}
public int multiply(int other) {
return number * other;
}
}
This class could be instantiated like:
Multiplier multiplyByTwo = new Multiplier(2);
I could use it to multiply many elements on a list by 2.
But I could need to multiply pairs of numbers. So the following class could be what I neeed:
public class Multiplier {
public static int multiply(int number, int other) {
return number * other;
}
}
I could make it static since no state is needed.
This example could be used like this on a list:
for (int x:listOfInts) {
print(Multiplier.multiply(x * 2));
}
But probably in this specific case the 1st example was nicer.
for (int x:listOfInts) {
print(multiplyByTwo(x));
}
or even nicer used with a Java 8 ''map''
If I need to get the elements of the multiplication and the result at many points in my code i could do.
class Multiplier {
private int x;
private int y;
public int multiply() {
return x * y;
}
// getters and setters for x and y
}
In this last case I may consider not adding setters and pass x, y in the constructor.
Every structure could be used in some specific cases.
It's not entirely a question of personal style. But nevertheless, I assume that this topic might be slightly controversial (opinion-based) and thus not perfectly suited for a Q/A-site.
However, the obvious question is: Does an object of the respective class really carry a state? That is, is there any benefit in having the state represented by an instance? If the sole purpose of the instance is to be an accumulator of variables that are modified with a sequence of set... calls and a final call to an execute() method, then there is usually no real justification for such an instance - except for avoiding to have a static method with "many" parameters.
I think that the advantages of static methods outweigh most of the potential clumsiness of calling a method with "many" parameters. One of the most important ones is probably that the approach with static methods doesn't increase the state space. Every field is another dimension in the state space, and documenting state space properly can be hard. Static methods enforce a more "functional" programming style: They don't have any side-effects, and thus, are thread-safe (which is becoming increasingly important).
(Note: All this refers to static methods that are not related to any static state - that should be avoided anyhow. And of course, this refers to methods that are not involved in or aiming at anything related to polymorphism).
And after all, one can easily call any static method from anywhere - even from within an instance method, and pass in some fields as parameters. The opposite is not so easy: When you want to call a method that depends on many instance fields, it can be a hassle when you first have to create an object and set the fields appropriately (still not knowing whether it is in a valid state to call the method). I also see the default methods of Java 8 as a nice application case where static utility methods come in handy: The default method may easily delegate to the utility method, because no state is involved.
There are a few reasons I'd go with the first option, i.e. an object with state over static functions, particularly for complex calculations but also for simpler ones.
Objects work better for the command pattern.
Objects work better for the strategy pattern.
Static methods can turn unit tests into a nightmare.
Static is an anti-pattern in OOP because it breaks polymorphism, with the side-effect that related techniques will break with it, e.g. open/closed, mocking, proxies, etc.
That's my 2c at least.
The weird part of your first example is that those calcX methods don't say anything about idempotency, so it's unclear what this.bla is when it's being manipulated. For complex computations with optional settings, an alternative is to construct an immutable object using a builder pattern, and then offer calcX methods that return the result based on fixed object state and parameters. But the applicability of that really depends on the use case, so YMMV.
Update: With your new code, a more OOP approach would be to decorate Mat. Favouring delegation over inheritance, you'd get something like
public class MyMat
{
private Mat i;
public MyMat(Mat i) {
this.i = i;
}
public Mat getBackingMat() {
return this.i;
}
public MyMat cannyEdges(int low, int high)
{
// ...
return new MyMat(I); // lets you chain operations
}
public MyMat cannyEdges()
{
return new MyMat(ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES));
}
public MyMat getHoughLines(...some_conf_vars...)
{
// ...
}
}
MyMat myMat = new MyMat(I);
lines = myMat.cannyEdges(20, 100).calcHoughLines();
This is just a guess, cause I have no idea what those things mean. :)
When not to use static:
If the result that will be returned is dependent on other variables (state) that make up your "calculation" class then static cannot be used.
However, if you are simply doing calculations on a variable, as the example implies, static is probably the way to go as it requires less code (For example to perform calc1 and then calc2 on a variable by the first method you would have to do:
calculation calc = new calculation(x)
calc.calc1();
calc.calc2();
XYZ y = calc.getBla();
while with the second example you could do
static import ...calculation.*;
...
XYZ y = calc2(calc1(x));

Java getter vs this

This is a very generic scenario, where I am setting a variable using setter function and using the variable only locally.
class Main {
private String str;
public Main(String value)
setStr(value);
}
private String getStr() {
return str;
}
private void setStr(String str) {
this.str = str;
}
public void display() {
//METHOD1
System.out.println(getStr());
//METHOD2
System.out.println(this.str);
}
}
What would be the better practise to follow between the two METHOD1/2 in display function, basically what would be the better way of using "str" variable.
Does it even make sense to have private getter/setter functions?
Ivard
If the getter is private, and doesn nothing more than returning a private variable, it isn't needed, IMHO (i.e. I prefer the second method of accessing it).
But if the getter was public and not final, and could thus be redefined by a subclass, then you'd have to decide if you want to get the potentially overridden value returned by the getter, or if you want the value of the private field in the display method.
Here should be at least one comment with Yes.
By providing new abstraction barrier you can separate data accessors and data presentation. For example, lets look at complex number class. Which can be implemented as
class ComplexNumber {
private final double realPart;
private final double imaginaryPart;
ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public double getRealPart() {
return realPart;
}
public double getImaginaryPart() {
return imaginaryPart;
}
}
or in polar expressions form
class ComplexNumber {
private final double r;
private final double angle;
ComplexNumber(double r, double angle) {
this.r = r;
this.angle = angle;
}
public double getR() {
return r;
}
public double getAngle() {
return angle;
}
}
Presume that you should implement basic operation like +-/*. What presentation model should you choose? For addition and subtraction standard model preferable, but for multiplication and division polar form preferable. So you can create getters for both form. And implement add/_sub_ like you have standard model and div/_mult_ like with polar form. This operation wouldn't depend from your actual data presentation. For change presentation you should change getters. Thats all. In Java world it's called self encapsulation.
For simple cases you'd just use this.str. For more complex cases, you might want to inherit from such a class, and have getStr() be implemented in a subclass perhaps it would lazily get the string from a file/database. Then these methods would't be private though.
For trivial cases where you just assign and fetch a private member, not really. For more complex cases where you might need to do additional logic, it'd make sense to confine that logic to one place. As with 1., it would make sense if you want sub classes to override the methods as welll.
Unless you have a side effects in your public getter which you desire I would consider always using this for consistency unless inheritance is assumed.
It doesn't make sence at all to me to employ private accessors. A routine should typically only do one thing and preferably without side effects. Creating a private getter
without side effects only creates useless redundancy.
with side effects basically proves that either the method is doing too much or is poorly named
Using this might also make refactoring easier [1].
[1] Refactoring a private variable gives less impact than refactoring a method. If you later decide to change the contract, e.g., by no longer providing a getter routine you will get less to refactor. Besides, many editors highlight all occurences of a variable when pointing the cursor to it, which is lost when hiding its use in a sub-routine.
No, it's not useful to have private getter/setter methods. If they were public or otherwise overridible by subclasses though it would be a different story. Should a subclass override your getter/setter, it could change the way the display() method functions.

Hiding a constructor behind a static creator method?

I've recently discovered an interesting way to create a new instance of an object in Google Guava and Project Lombok: Hide a constructor behind a static creator method. This means that instead of doing new HashBiMap(), you do HashBiMap.create().
My question is why? What advantage do you have of hiding the constructor? To me I see absolutely no advantage of doing this, and it seems to break basic object creation principles. Since the beggining you create an object with new Object(), not some Object.createMe() method. This almost seems like creating a method for the sake of creating a method.
What do you gain from doing this?
There are a number of reasons why you might prefer a static factory method instead of a public constructor. You can read Item 1 in Effective Java, Second Edition for a longer discussion.
It allows the type of the object returned by the method to be different than the type of the class that contains the method. In fact, the type returned can depend on the parameters. For example, EnumSet.of(E) will return a different type if the emum type has very few elements vs if the enum type has many elements (Edit: in this particular case, improving performance for the common case where the enum doesn't have many elements)
It allows caching. For instance, Integer.valueOf(x) will, by default, return the same object instance if called multiple times with the same value x, if x is between -128 and 127.
It allows you to have named constructors (which can be useful if your class needs many constructors). See, for example, the methods in java.util.concurrent.Executors.
It allows you to create an API that is conceptually simple but actually very powerful. For instance, the static methods in Collections hides many types. Instead of having a Collections class with many static methods, they could have created many public classes, but that would have been harder for someone new to the language to understand or remember.
For generic types, it can limit how much typing you need to do. For example, instead of typing List<String> strings = new ArrayList<String>() in Guava you can do List<String> strings = Lists.newArrayList() (the newArrayList method is a generic method, and the type of the generic type is inferred).
For HashBiMap, the last reason is the most likely.
This is usually done because the class actually instantiated by the create() method might be different than the type upon which you are invoking the method. i.e. a factory pattern where the create() method returns a specific subclass that is appropriate given the current context. (For example, returning one instance when the currrent environment is Windows, and another when it is Linux).
Unlike constructors, static methods can have method names. Here's a recent class I wrote where this was useful:
/**
* A number range that can be min-constrained, max-constrained,
* both-constrained or unconstrained.
*/
public class Range {
private final long min;
private final long max;
private final boolean hasMin;
private final boolean hasMax;
private Range(long min, long max, boolean hasMin, boolean hasMax) {
// ... (private constructor that just assigns attributes)
}
// Static factory methods
public static Range atLeast (long min) {
return new Range(min, 0, true, false);
}
public static Range atMost (long max) {
return new Range(0, max, false, true);
}
public static Range between (long min, long max) {
return new Range(min, max, true, true);
}
public static Range unconstrained () {
return new Range (0, 0, false, false);
}
}
You couldn't do this using just constructors, as atLeast and atMost would have the exact same signature (they both take one long).
This is called a Factory method pattern. Where the factory lies within the class itself. Wikipedia describes it pretty well but here are a few snippets.
Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.
Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.
Well it would be possible for SomeClass.create() to pull an instance from a cache. new SomeClass() won't do that without some shenanigans.
It would be also be possible for create() to return any number of implementations of SomeClass. Basically, a Factory type of dealio.
Although not applicable to this particular code example, the practice of hiding the constructor behind a static method is Singleton Pattern. This is used when you want to ensure that a single instance of the class is created and used throughout.
There are many reasons to use this factory method pattern, but one major reason Guava uses it is that it lets you avoid using type parameters twice when creating a new instance. Compare:
HashBiMap<Foo, Bar> bimap = new HashBiMap<Foo, Bar>();
HashBiMap<Foo, Bar> bimap = HashBiMap.create();
Guava also makes good use of the fact that factory methods can have useful names, unlike constructors. Consider ImmutableList.of, ImmutableList.copyOf, Lists.newArrayListWithExpectedSize, etc.
It also takes advantage of the fact that factory methods don't necessarily have to create a new object. For instance, ImmutableList.copyOf, when given an argument that is itself an ImmutableList, will just return that argument rather than doing any actual copying.
Finally, ImmutableList's factory methods return (non-public) subclasses of ImmutableList such as EmptyImmutableList, SingletonImmutableList and RegularImmutableList depending on the arguments.
None of these things are possible with constructors.
i got very interesting reason to hide constructor check it and please let me know if there is any other alternative to achieve this
enter code here
Class A
{
String val;
protected A( )
{
}
protected A(String val)
{
this.val=val;
}
protected void setVal( String val)
{
this.val=val;
}
public String getVal()
{
return val;
}
}
class B extends A
{
B()
{
super();
}
public val setVal(String val)
{
super.val=val;
}
}
class C extends A
{
C(String val)
{
super(val);
}
}
Some main reasons
Primarily it gives you the power to instantiate a different (sub) class
Possibility to return null
It enables you to return an already existing object

Categories