If I use builder pattern that create some PRODUCT, i would, probably should want to limit the ability to create this PRODUCT by explicit way?
Because it is probably not good of users of my code would create PRODUCT like new PRODUCT().
I mean the users of my code my do not know about some builder.
So, should I make constructor of PRODUCT with as private? And then in the Builder I would use reflection to create the initial instance of the PRODUCT?
Does this approach make sense? Is it ok?
Or you set the constructor as protected, and create a builder in the same package, so it has access to it, or create static methods that might even use your builder implicitly.
If your ProductBuilder is able to create an instance of Product through reflection, then any other class can do the same.
I think, it's easier to add builder and product to the same namespace (package) and make the constructor package private. It has the same effect (invisible for classes outside the package) and keeps the code clean.
What you seem to be describing is called the Factory Pattern (rather than the builder pattern).
The simplest way to implement this is to make your constructor private and provide static factory methods on the Product class. This is the bare minimum implementation:
public class Product {
private Product() {}
public static Product create() {
return new Product();
}
}
There are plenty of classes in the JDK that follow this pattern, for example Integer.parseInt is static factory method the creates as Integer (although the constructor is not private)
Alternatively, you could create a separate Factory class in the same package as Product and give the Product constructor the default visibility.
You should avoid using reflection in general, unless you really need it. In this case you don't need it - keep things as simple as possible (but no simpler).
Related
I have seen two popular methods of implementing the builder pattern:
// 1. The build() approach
Product p = builder.part1()
.part2()
.build();
// 2.The constructor approach
builder.part1()
.part2();
Product p = new Product(builder);
Which of these is preferable?
1st one is the way to go...
if you use the 2nd choice then doing this:
Product p = new Product(builder);
will add dependencies to the Product class..
that means the Product class needs now at least a constructor with the parameter builder
The question is a little vague, however in case you have a static builder class, effective java book of joshua bloch suggests a structure more like the first one with build method. It is a cleaner and safer way.
Product p= new Product.ProductBuilder("hw", "sw")
.version(30)
.mac("1234567")
.address("Fake address 1234")
.build();
I tend to use a combination of both of those examples.
I would define a builder class inside the Product class and give the product class a private constructor that takes a ProductBuilder.
These are two different approaches. Trades-off are different.
You must use and adapt a pattern according your needs and your context, not according a hard rule...
Using a builder like it :
Product p = new Product(builder);
allows to create your builder and to reuse it.
If you need to reuse the builder or to create the builder in another class, it is a good implementation. You open your API because you need it.
The drawbacks of the solution are a no straight way of creating your object.
About design quality and dependency, I think that it is a false problem.
Yes with a public constructor for Product, you create a public dependency between Product and builder and you expose the Product constructor.
But if in the Product constructor, you dispatch to the builder instance the task for constructing the Product, is the coupling will make the code less flexible ? Never. Besides, the real coupling is located in the Product construction since the builder uses mirrors properties to build the Product object. So, the real and strong coupling will stay whatever happens: these two classes must work together and must look like.
Using a builder like it :
Product p = builder.part1()
.part2()
.build();
doesn't allow to reuse builder but is more straight to use for your client of the class and it opens at the minimum the dependency between Builder to Product.
If you don't need to reuse the builder or to create the builder in another class, it's the best since you don't open your API in a useless way.
So, in the facts, both solutions are near.
I would use the solution with a constructor if I must reuse the builder or i need to create the builder in another class and i would use the solution without constructor if not needed.
In some places where a class hierarchy is present and the top most base class is an abstract class there is a static getInstance() method in the abstract class. This will be responsible for creating the correct sub-class and returning it to the caller. For example consider the below code.
public class abstract Product {
public static Product getInstance(String aCode) {
if ("a".equals(aCode) {
return new ProductA();
}
return ProductDefault();
}
// product behaviour methods
}
public class ProductA extends Product {}
public class ProductDefault extends Product {}
In Java, java.util.Calendar.getInstance() is one place this pattern has been followed. However this means each time a new subclass is introduced one has to modify the base class. i.e: Product class has to be modified in the above example. This seems to violate the ocp principle. Also the base class is aware about the sub class details which is again questionable.
My question is...
is the above pattern an anti-pattern ?
what are the draw-backs of using the above pattern ?
what alternatives can be followed instead ?
The interface is not an anti-pattern. But the way you've implemented it is rather poor ... for the reason you identified. A better idea would be to have some mechanism for registering factory objects for each code:
The Java class libraries do this kind of thing using SPIs and code that looks reflectively for "provider" classes to be dynamically loaded.
A simpler approach is to have a "registry" object, and populate it using dependency injection, or static initializers in the factory object classes, or a startup method that reads class names from a properties file, etcetera.
No it's not. It's more like factory method pattern http://en.wikipedia.org/wiki/Factory_method_pattern. E.g. Calendar.getInstance();. JDK is full of such examples. Also reminds of Effective Java Item 1: Consider static factory methods instead of constructors
There are a number of separate issues here.
getInstance is probably going to be a bad name. You explicitly want a new object you can play around with. "Create", "make", "new" or just leave that word out. "Instance" is also a pretty vacuous word in this context. If there is sufficient context from the class name leave it out, otherwise say what it is even if that is just a type name. If the method returns an immutable object, of is the convention (valueOf in olden times).
Putting it in an abstract base class (or in an interface if that were possible) is, as identified, not the best idea. In some cases an enumeration of all possible subtypes is appropriate - an enum obviously and really not that bad if you are going to use visitors anyway. Better to put it in a new file.
Anything to do with mutable statics is wrong. Whether it is reusing the same mutable instance, registration or doing something disgusting with the current thread. Don't do it or depend (direct or indirectly) on anything that does.
Based on the feedback i introduced a new ProductFactory class that took care of creating the correct Product. In my case the creation of the correct product instance depends on an external context (i've put the product code for the purpose of simplicity.. in the actual case it might be based on several parameters.. these could change over time). So having a Product.getInstance() method is not that suited because of the reasons outlined in the question. Also having a different ProductFactory means in the future.. Product class can become an interface if required. It just gives more extensibility.
I think when the creation of the object doesn't depend on an external context.. like in the case of Calendar.getInstance() it's perfectly ok to have such a method. In these situations the logic of finding the correct instance is internal to that particular module/class and doesn't depend on any externally provided information..
I usually set each attribute of a class as final (only for attributes that will be initialized within the constructor).
The point is that I am now implementing a Mockup of an object for testing purpose. This Mockup extends the class that it is mocking up and this class has some final attributes. Therefore I'm forced to call the super() constructor within the constructor of the Mockup object. This breaks however the utility of the Mockup because I don't want it to initialize all of the attributes in the way the normal class does it. I'd rather call the Mockup constructor without calling to super() and doing whatever I want.
My question is: Is it a good practice to define attributes as final as long as they will force you to call the class constructor in the Mockup?
EDIT: I add some code. The problem in this case is that I'm using a singleton, I know that this is not a good idea when testing but in this case I cannot change it. So my intention is not to call this method in the Mockup.
public class ReportsDataManager {
private final Map<String, List<String>> translations;
public ReportsDataManager() {
this.translations = GenericUtils.getTranslation();
}
}
Declaring attributes final is a very good practice when you can do it. It confers immutability - guaranteed thread safety. Breaking it to mock is a bad idea. Your design should serve the user's needs, not your testing convenience.
If you wish to mock the class, give it an interface and mock the interface. Also, mocks aren't stubs. It sounds like you're creating a stub, rather than a mock.
If you do wish to create a mock, pick a library that generates mocks for interfaces for you.
In general I'd say that if a practice you use makes testing your code more difficult then the practice may be a smell.
Try to decide exactly what you want to achieve by setting variables final. Would protected be acceptable?
You can sidestep the final restriction with standard reflection. Since you are in the context of a mockup, this wouldn't cause much problems, I suppose. Just beware of multithreading issues: the JVM will assume the field adheres to the final semantics and will optimize with that in mind.
Util class in java can be made in two ways
class Utils
{
public static ReturnType someUtilMethod(
// ...
}
and execute util method by
Utils.someUtilMethod(...);
Or I can make
class Utils
{
public Utils(){}
public ReturnType someUtilMethod(
// ...
}
and execute util method by
new Utils().someUtilMethod(...)
What way is better? Are some differences between this ways?
Generally Util class contains Utility methods which doesn't need to store the state of Object to process and so static methods are good fit there
A utility function should always be static, unless for some reason it depends on the state of some other variables, and those variables need to be remembered between calls.
The latter should almost never happen, although something like a pseudo-random number generator might be a good case.
The Math functions are a good example of utility functions. When you call Math.sin() the result depends only on the supplied parameter. There is no "state" involved, so there's no need to create an object.
static access will be a better approach as in Util class hold methods which are not concerned with the attributes of the Objects.
Another example will be of Math Class.
Math class has no Instance variables.
And has private constructor, so no object can be created.
So in Math class case using static access like Math.PI is appropriate.
If you use a class that only has static methods, you will not need to instantiate the object everytime you need to use it, saving a line of code and some memory. Just remember to make the default constructor private, so that no one cane inadvertently instantiate it!
A utility class is just a place where to syntactically hold global functions in Java.
Your second example is not covered by the term "utility class". The definition of that concept includes non-instantiability of the class.
The reason to have instance methods would be dynamic method dispatch (to achieve polymorphism), or possibly hold some non-global state. But, as I said, then you would be out of the scope of the term "utility class".
I am involved in this project where we are building on good bit of legacy code. I have a particular situation about one big java bean object which has to be transferred over wire. So my first thought was to make it immutable and serializable to do the trick .At this point I am faced with a few difficult choices :-
Ideally I want some way to
automatically generate an immutable,
serializable version of this class.
I dont have the scope to refactor or
alter this class in any way and i
would really really hate to have to
copy paste the class with a
different name ?
Assuming that i gave up on 1 i.e i
actually chose to duplicate code of
the HUGE javabean class , i still
will be in the unsavoury situation
of having to write a constructor
with some 20-25 parameters to make
this class immutable. what is a
better way to make a class immutable
other than constructor injection ?
Thanks and Regards,
To make it truly immutable, you need to initialize the members at construction time.
One way (and I ain't sayin' it's pretty!) to do this and avoid a huge parameter list in the constructor is to have a mutable type that has the same properties. Set the the properties on the mutable type one at a time, through "setters", then pass the mutable object to the constructor of the immutable type as a single argument. The immutable object then copies the properties from the mutable source to it's own (final) members.
You might also consider "effective immutability". That is, even though immutability is not enforced by the system, you use coding practices that clearly separate the initialization phase from the usage phase. After all, immutability is not required for serialization.
You can take this a step further, creating an implementation-hiding wrapper for the interface that doesn't expose the properties of the implementation. The wrapper only implements the methods in the interface, by delegating to the "real" implementation. The setters and getters from the implementation are not present in the wrapper. This will stop clients from simply down-casting from the interface to the implementation class and manipulating the properties.
Joshua Bloch's "Effective Java" illustrates the Builder pattern, where simple Builder objects are used to construct a complex object with a long constructor argument list. I'd recommend it.
http://www.drdobbs.com/java/208403883;jsessionid=PJWS41F5DJ4QRQE1GHRSKH4ATMY32JVN?pgno=2
20-25 properties is not huge for a one off, particularly if you are using a half-decent editor.
If you already have a mutable instance when constructing the immutable version, just pass that to the constructor.
If you want to be really evil hacky, use java.beans to create a serialisable Map for the mutable class or subclass implementing Externalizable. Alternatively you could use java.beans XML serialisation (the XML than can be sent over Java serialisation...).
What about a simple read only interface cotaining the getters?
If the bean class is your own, let it simpley implement the interface and use just the interface after creation.
If you have no control over the bean class, you can also create a getter interface and implement it by creating a proxy for the getter interface with an invokation handler delegating all method calls to the bean.
Step 1: Create a new class and give it instance variables with the exact same names as the instance variables of your 'big java bean object'. That new class should not have setters (but getters only) to make it immutable.
Step 2: Use Apache Commons BeanUtils.copyProperties to copy all the properties (i.e. instance variables) from your 'big java bean object' to your new object.
A few ideas:
Protected setters and factory methods
You can define beans with protected setter methods and in the same package, a factory class that takes all the parameters and calls those setters. The bean is immutable outside that package. To enforce this, be sure to seal your jar so end users cannot create new classes in the same package.
Note: You can use my JavaDude Bean annotations to make the creation simpler:
http://code.google.com/p/javadude/wiki/Annotations
For example:
#Bean(writer=Access.PROTECTED, // all setXXX methods will be protected
properties={
#Property(name="name"),
#Property(name="age", type=int.class)
})
public class Person extends PersonGen {
}
Creating getters and a constructor in eclipse
Eclipse has some nice tools to make this fast:
Create the bean class
Add the fields you want
Right-click in the editor window
Choose Source->Generate Getters and Setters
Press the "Select getters" button
Press ok
Right-click in the editor window
Choose Source->Generate Constructors from fields
Pick and order the fields you want in the constructor
Press ok
Immutability Decorator
Another idea is to define your bean with getters and setters (you can use the above technique but include setters), then you can create a wrapper class for it that only has the getters.