thgs, (edited )
@thgs@phpc.social avatar

Static constructors or a factory class? Which one you tend to prefer.

The factory method, as a pattern seems convenient for me as you can have a private constructor and guard different ways to construct an object with a different static method. However, factory method is meant for subclassing.

On the other hand, a factory, in some cases will leave unguarded the constructed object.

Feel free to elaborate on why.

thgs,
@thgs@phpc.social avatar

I guess those that say "it depends" see both cases as similar but use each for different situations/outcome

davesh,
@davesh@hachyderm.io avatar

@thgs I like a factory that takes either a configuration object or array of parameters.

thgs,
@thgs@phpc.social avatar

@davesh you like fancy :)

shudder,
@shudder@phpc.social avatar

@thgs I use all of them for different purposes (sometimes combined).

Building HttpRequest for example:

  • Static constructor (transforming basic/primitive/default arguments), allows overriding server parameters,
  • Simple factory (cleaner code) in static constructor is dealing with all these ugly superglobals.

Recently I'm experimenting with nullable static constructors (private default) to avoid clunky exceptions in input VOs (separate static method listing validation errors) - so far so good.

zimzat,
@zimzat@mastodon.social avatar

@thgs

I dislike private constructor methods. It makes working with objects more difficult, especially in tests where you want to pass values directly. You can't foresee every possible valid input.

Additional factory methods are okay if they consolidate known common patterns, such as DateTime::createFromInterface. I'm not sure what this has to do with subclassing.

Factory classes should be avoided. Use Dependency Injection Containers instead.

Composition over inheritance.

thgs,
@thgs@phpc.social avatar

@zimzat

See in the design patterns book, factory method pattern is defined as a mechanism for subclasses to redefine construction, in hierarchies of objects. Factory methods are not only meant to create the same object as the one that declares them, for example.

Static constructor is more into point as a term but I try to differentiate between the two approaches, static constructor (and some possible factory method implementation) and a factory.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • php
  • ngwrru68w68
  • rosin
  • GTA5RPClips
  • osvaldo12
  • love
  • Youngstown
  • slotface
  • khanakhh
  • everett
  • kavyap
  • mdbf
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • megavids
  • InstantRegret
  • normalnudes
  • tacticalgear
  • cubers
  • ethstaker
  • modclub
  • cisconetworking
  • Durango
  • anitta
  • Leos
  • tester
  • provamag3
  • JUstTest
  • All magazines