Java naming factory methods

Java naming factory methods

  • LogManager. getLogManager
  • Pattern. compile
  • Collections. unmodifiableCollection , Collections. synchronizeCollection , and so on
  • LocalDateTime. now
  • have names, unlike constructors, which can clarify code.
  • do not need to create a new object upon each invocation — objects can be cached and reused, if necessary.
  • can return a subtype of their return type — in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.
public final class ComplexNumber < /** * Static factory method returns an object of this class. */ public static ComplexNumber valueOf(float real, float imaginary) < return new ComplexNumber(real, imaginary); > /** * Caller cannot see this private constructor. * * The only way to build a ComplexNumber is by calling the static * factory method. */ private ComplexNumber(float real, float imaginary) < this.real = real; this.imaginary = imaginary; > private float real; private float imaginary; //..elided >

Java Practices 3.012
© 2023 John O’Hanley
Source Code | Contact | License | RSS
Individual code snippets have a BSD license
Over 1,000,000 unique IPs last year
Last updated 2023-01-03
— In Memoriam : Bill Dirani —

Источник

Java naming factory methods

Factory method pattern naming conventions The “factory method” is a very useful pattern, but it has som limitations when it comes to documentation. Constructors “stand out” in API documentation and are easy to spot, but factory methods on the other hand can be hard to find. There are some naming conventions laid out in effective java that can reduce this problem and make the factory methods easier to find in an IDE.

Type-conversion. Takes a single parameter and returns an instance of the same type as the parameter. Date d2 = Date.from(d1);

An aggregation method that takes multiple parameters and returns an instance that “incorporate” the parameters. Return type is same as parameters. Set genders = EnumSet.of(MALE, FEMALE);

More verbose alternative to from and of BigInteger.valueOf(Integer.MAX_VALUE);

instance or getInstance

Returns an instance that is described by its parameters (if any). Doesn’t have to have the same type as parameters. Return value is typically cached (singleton, etc) KeyFactory.getInstance(«RSA»);

create or newInstance

Like instance or getInstance but returns a new instance on each invocation Array.newInstance(classObject, length);

getType or type

Like getInstance, but used if the factory method in in a different class than the type. Collections.list();

A more descriptive version than type, where foo adds meaning to the return type Collections.singletonList(T value);

Источник

How to name factory like methods

Since these methods can be used to implement «fluent interface», maybe they could be «fluent factory methods»? Better suggestions? EDIT: as suggested by one of answers, is a good example with its ‘add’, ‘subtract’ (etc) methods. Technically it is kind of a factory method, but somehow that does not seem quite right to me, since often factories are just given basic properties (and are either static methods, or are not members of the result type but factory type).

Читайте также:  Php decode json request

What to call factory-like (java) methods used with immutable objects

When creating classes for «immutable objects» immutable meaning that state of instances can not be changed; all fields assigned in constructor) in Java (and similar languages), it is sometimes useful to still allow creation of modified instances. That is, using an instance as base, and creating a new instance that differs by just one property value; other values coming from the base instance. To give a simple example, one could have class like:

public class Circle < final double x, y; // location final double radius; public Circle(double x, double y, double r) < this.x = x; this.y = y; this.r = r; >// method for creating a new instance, moved in x-axis by specified amount public Circle withOffset(double deltaX) < return new Circle(x+deltaX, y, radius); >> 

So: what should method «withOffset» be called? (note: NOT what its name ought to be — but what is this class of methods called). Technically it is kind of a factory method, but somehow that does not seem quite right to me, since often factories are just given basic properties (and are either static methods, or are not members of the result type but factory type).

So I am guessing there should be a better term for such methods. Since these methods can be used to implement «fluent interface», maybe they could be «fluent factory methods»? Better suggestions?

EDIT: as suggested by one of answers, java.math.BigDecimal is a good example with its ‘add’, ‘subtract’ (etc) methods.

Also: I noticed that there’s this question (by Jon Skeet no less) that is sort of related (although it asks about specific name for method)

EDIT, MAY-2014: My current favorite is mutant factory , FWIW.

I call those types of methods «copy methods» .

While the clone() method creates an exact copy, a copy method makes a copy of an instance, usually with an implied or explicit variation. For example, String#toUpperCase() would be a copy method of the immutable String class — it copies an instance with a variation: it upcases all the letters.

I would consider withOffset() method in your example to be a similar copy method.

I don’t know of any references that document the term «copy method». I’m borrowing the term «copy» from its use in C++: copy constructors and the «copy» naming guideline from the Taligent Coding Standards (more info).

As for the term «fluent factory methods», I don’t know why «fluent» would make a difference, since a «fluent interface» is just an API style (separate from the builder pattern). If the term «factory method» doesn’t apply here, I don’t see how calling it a «fluent factory method» makes it apply any better.

Hrm … it creates mutated versions of the object … maybe we should call it a mutant factory? 🙂

This does not really look like a factory method. The signature alone only tells me that I can chain it in different calls, but not that it is supposed to create a new instance: I see this use case more like a StringBuilder that allows append(«a»).append(«b»). It could, of course return a new StringBuilder every time (as your Circle does).

So it’s not by design a factory. (Think of extracting the interface and writing the JavaDoc for that method: «one must return a new instance, since I’m immutable» — why so ??) The fact that your class is immutable is just an implementation detail).

Читайте также:  Html добавить внешний файл

EDIT: Perahs a better example would be BigInteger, since that’s also immutable. Along with multiply(BigInteger), it provides a package-private method:

BigInteger multiply(long v) 

which returns a new instance and resembles your case very well. That’s simply an operation that happens to return a result of the same type as the initial object; not a factory and I don’t think this kind of operation really deserves its own name.

Java — What are static factory methods?, The static factory method pattern is a way to encapsulate object creation. Without a factory method, you would simply call the class’s constructor directly: Foo x = new Foo (). With this pattern, you would instead call the factory method: Foo x = Foo.create (). The constructors are marked private, so they …

Factory-like method as abstract template method

Say I have an abstract base class that has a method to generate Foo objects (acting like a factory method). Right now my classes look something like this:

public class Foo < >public class FooBar extends Foo < >public abstract class MyBaseClass < abstract public Foo createObject(); >public class MyDerivedClass extends MyBaseClass < @Override public Foo createObject() < return new FooBar(); >> 

This is sub-optimal, because code calling MyBaseClass#createObject needs to cast the return value back to what it was originally, i.e.:

FooBar fooBar = (FooBar)myDerivedClass.createObject(); 

This is like taking my pants off to put them on again.

I haven’t used Java generics for a while, but I was hoping I could turn that abstract method into a templated method, something like:

public abstract class MyBaseClass < abstract public T createObject(); > 

But I get the following errors from Eclipse when I try to implement the method in the derived class:

public class MyDerivedClass extends MyBaseClass < @Override public FooBar createObject() // The type parameter FooBar is hiding the type FooBar < return new FooBar(); // Cannot instantiate the type FooBar >> 

I don’t think I’m applying the right solution to my problem of reducing the unnecessary casting going on. Any ideas?

You’re probably looking for a generic class (as opposed to a generic method):

public abstract class MyBaseClass  < public abstract T createObject(); >public class MyDerivcedClass extends MyBaseClass  < public FooBar createObject() < return new FooBar(); >> 

To learn more about Java generics, I highly suggest you read the Generics tutorial.

C# — How to choose between Factory method pattern, To me this fits perfectly with the definition of a Factory method pattern: Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses. 2) in the second part PizzaStore is the client and it’s dependent on …

Need advice on wordy naming of methods

I’m writing an API for creating geometric shapes, and I’m running into some difficulties naming my methods.

Let’s take a simple case: Creating a circle. Most of us might be familiar with a method like graphics.drawEllipse(x, y, w, h) . To draw a circle, you need to know the top left coordinate, and the width and height of the circle.

My API is intended to make it easy for a developer to draw shapes using a variety of information, without doing a lot of math — which is trivial for circles, but more complicated for other shapes. For example, you should also be able to draw a circle given its center coordinates and radius, or the top left and bottom right coordinates.

Читайте также:  Лучшие способы выучить питон

So I have a Circle class with factory methods like:

Circle.createWithCenterAndRadius(cx, cy, r) Circle.createWithBoundingBox(x1, y1, x2, y2) Circle.createWithWidthAndHeight(x, y, w, h) 

I feel like there might be a «code smell» here, but I’m not sure. On the one hand, these factory methods are necessarily descriptive. On the other hand, I can forsee these method names getting out of control. For example, how would I name a Triangle factory method that creates a triangle given a point, the length of one side, an angle, and the length of another side? Triangle.createWithPointSideAngleAndSide(x, y, side1, angle, side2) ? Is that just evil?

If you were to use this API, would method names like this be okay to you? Do you have advice on how I can make the method names more sane?

You might change your circle methods to

Circle.FromCenterAndRadius(. ) Circle.FromBoundingBox(. ) Circle.FromWidthAndHeight(. ) 

It implies that you’re creating circles from their different representations in a kind of concise way.

It is ok in any language that doesn’t support named parameters. If the language supports named parameters, I like more the short Create and just have obvious parameters names.

For a language with named parameters, you would:

Circle.Create( centerX = cx, centerY = cy, radius = r ); 

Another more involved option, would be a fluent interface like (but that is probably too much):

circleBuilder.Center(cx,cy).Radius(r) circleBuilder.Center(x,y).Width(w).Height(y) circleBuilder.BoundWith().Left(x1,y1).Right(x2,y2) 

Center returns an instance of an intermediate class that only allows Radius or Width. And BoundWith returns one that only allows Left.

I think there is nothing wrong with your descriptive methods — they are the compact and describe exactly what’s going on. The users of the library will have no doubt about the function of your methods, neither the maintanance programmers.

You could also apply some design pattern here if you are really worried about exposing a large number of factory methods — like having factory methods with property classes. You could have a CircleProperties class with properties like CenterX, CenterY, Radius, (bool)UseCenterX, (bool)UseCenterY etc and then you pass this to the public factory method which will figure out which (private) factory method to use.

var circleProperties = new CircleProperties() < CenterX = 10, CenterY = -5, Radius = 8, UseCenterX = true, UseCenterY = true, UseCenterRadius = true >; var circle = Circle.Create(circleProperties); 

My first instinct is to have more types, which would allow for more intuitive method overloading.

// instead of Circle.createWithCenterAndRadius(cx, cy, r) Circle.create( new Point(cx,xy), r); // instead of Circle.createWithBoundingBox(x1, y1, x2, y2) Circle.create( new Point(x1,y1), new Point(x1,y1) ); // or even. Circle.create( new Box(p1,p2)); // instead of Circle.createWithWidthAndHeight(x, y, w, h) Circle.create( new Point(x,y), w, h); 

As well as Point, you could define Distance (which would allow for different units)

If this style suits you, consider why you need a factory method instead of a constructor.

Circle c = new Circle(new Point(cx,xy), r); 

Factory Method Design Pattern, A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor.

Источник

Оцените статью