A question about `object` and companion objects, p...
# announcements
n
A question about
object
and companion objects, philosophically
It seems like in this approach, by putting functionality in a class of anonymous type, you are a) making it harder to unit test the functionality, and b) If the user ever decides they need another instance of the functionality, it's just made things more difficult
If you write a class like
Logger
and it's an ordinary, well behaved class, you can then have a global of type
Logger
called
globalLogger
(never mind details of safe initialization at the moment)
Then Logger can be easily unit tested. And if a user wants to log to a secondary logger from the global logger, they can do it easily.
I suppose that in Kotlin you can try to keep your object/companion object types extremely lightweight, and have them as mere inheritance wrappers
i.e.
object globalLogger (..) : Logger
That's one possible approach but it seems like Kotlin makes it very easy, almost encouraging of putting a lot of functionality in a place that's just not very good
r
When you have things like extension functions that allow you to add functionality to objects within very specific scopes without polluting the main object, I am not sure if Kotlin is encouraging that as much as developers may just not fully be aware of all the tools at their disposal.
n
Yeah, I know there are java developers that are used to using
static
just to have functions that are not associated with a specific object
And they will use companion objects even though it's totally unnecessary for that purpose
but I'm discussing real usages of companion objects, i.e. when a class actually wants to have some global state
s
static
like (companion) objects and functions are not only useful for maintaining a global state. They can also be used for name-spacing/scoping of functionality.
n
In Java, yes static is often used for that. In Kotlin my understanding is that this is discouraged.
But at any rate, I'm more interested in the global state aspect of it.
k
I often put utility and factory functions in the companion object, without any state. I don't think I've ever written one with state.
w
My personal feeling is that the companion object is primarily useful to deal with existing Java frameworks that expect certain static functions, etc. For factory functions I prefer top level functions in the package. I take "listOf" and "mutableListOf" as examples of this.
k
They are okay because they're used so often, but polluting the global autocomplete with hundreds of utility factory functions isn't great.
n
Yeah, for factory functions I can't imagine touching this stuff. For me,
object
and companions are basically singleton enabling devices, I can't really imagine using them for anything that doesn't require a singleton.
If I actually did need a singleton though I think I would write a real class and then inherit from that class with
object
, keep
object
itself extremely minimal.