Dart: Mixins vs Static Methods
Asked Answered
A

2

7

Is using mixins a better practice than using static methods?

For example:

  • we can create a Utils class, put static methods in it and then use them like Utils.print().
  • or we can create a UtilsMixin class, access it using "with" keyword and just call print().

How do these two methods compare to each other? Which one is the way to go?

Assyrian answered 17/3, 2019 at 19:6 Comment(0)
J
9

Mixins vs Static member is like Black vs White. They do the opposite.

Members of a mixin are linked to one specific instance of an object. But static members are common to all objects

If it made sense to implement something like a static function, then it likely means that a mixin is not what you want. It'll just make the object bloated and slower to instantiate.

Jovia answered 17/3, 2019 at 19:47 Comment(2)
Can you tell me a simple case when I would prefer mixins over static methods? and what do you mean by "Members of a mixin are linked to one specific instance of an object. But static members are common to all objects". Can you explain more?Assyrian
from what I gather Remi is saying that AFTER you instantiate a class you can add a method to it and then call it and I imagine the method you attach might come from a static method. Obviously the method is going to expect that all the variable names are defined in the class it's being appended to. Good example here: javascript.info/mixinsInfinity
J
0

AVOID defining a class that contains only static members.

Dart has top-level functions, variables, and constants, so you don’t need a class just to define something. If what you want is a namespace, a library is a better fit. Libraries support import prefixes and show/hide combinators. Those are powerful tools that let the consumer of your code handle name collisions in the way that works best for them.

If a function or variable isn’t logically tied to a class, put it at the top level. If you’re worried about name collisions, give it a more precise name or move it to a separate library that can be imported with a prefix.

Source: https://dart.dev/effective-dart/design

Janeejaneen answered 11/12, 2023 at 14:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.