uis,

SSA

crispy_kilt,

Needs more monads

Omega_Haxors, (edited )

Why even use variables in the first place? Just place the values directly into your code. If you need to change a value, that’s just bad planning. Hell, why even use values either? Just run a loop on the INC instruction until you get the value you need. It’s just efficient programming.

lemmesay,
@lemmesay@discuss.tchncs.de avatar

I oscillate between using more functional paradigms and more object-oriented ones. is that normal?
I use a linter BTW(TypeScript) if that is a useful info.

jkrtn,

I think using both is normal. Closures and objects are duals of each other. Do whatever is understandable and maintainable, neither paradigm is magic.

lemmesay,
@lemmesay@discuss.tchncs.de avatar

that’s a nice way to look at it. thanks!

kogasa,
@kogasa@programming.dev avatar

Is the duality statement meant to be true in a technical sense?

jkrtn,

Yeah! For example, if the language allows closures to capture state, they can act like properties on an instance.

kogasa,
@kogasa@programming.dev avatar

I don’t see the duality

jendrik,

A closure is a function with captured state. An object is state with methods.

ZILtoid1991,

I also do that. Very simple stuff, especially of those that are easy to optimize for the compiler, are often very close to functional programming paradigms.

crispy_kilt,

Avoid shared mutable state like the plague in any paradigm and you’ll be fine

lemmesay,
@lemmesay@discuss.tchncs.de avatar

state management crying in the corner

crispy_kilt,

Functional state management is fine

DickFiasco,

I use a combination of both. Objects are declared const, all members are set in the constructor, all methods are const. It doesn’t really work for some types of programs (e.g. GUIs) but for stuff like number crunching it’s great.

lemmesay,
@lemmesay@discuss.tchncs.de avatar

I heavily use classes while working on back end, and when I’m making a really self-contained logic, such as a logger or an image manipulation service.
but since most frontend stuff heavily leans on functional side, I go with it

ornery_chemist,

you mean let.

and then letting Hindley-Milner do the rest

Magnetar,

let there = “light”

LinearArray,
@LinearArray@programming.dev avatar

Me irl

9point6,

Const everything by default

If you need to mutate it, you don’t, you need to refactor.

ByGourou,

Sorry, I want to make an app that works, not a perfect art piece.

9point6,

The app working isn’t good enough, it needs to be maintainable. From a professional perspective, unmaintainable code is useless code.

Code that mutates everywhere is generally harder to reason about and therefore harder to maintain, so just don’t do it (unless there’s literally no other practical way, but genuinely these are very rare cases)

ByGourou,

I personally disagree, forcing yourself to use non mutable variables only leads to longer and more convoluted code.

9point6,

Fair play, I guess we’re probably just gonna disagree.

In my experience I’d say mutable code (larger than anything other than toy examples) always results in more time spent fixing bugs down the line, predominantly because it’s objectively harder for humans to reason about multiple one to many relationships rather than multiple one to one relationships. I’d say because you need to think about all possible states of the set of mutable variables in your code in order to completely understand it (and I don’t just mean understanding the intended purpose of the code, I mean understanding everything that code is capable of doing), that usually results in a more convoluted implementation than the pretty linear way you typically read functional code.

Longer code is practically always better if it’s easier to understand than the shorter alternative. Software engineers aren’t employed to play code golf, they’re employed to write maintainable software. Though I’ll say ultra high performance applications might be the exception here—but 99% of engineers aren’t doing anything like that.

I’m always happy to be convinced otherwise, but I’ve never seen a convincing argument

noli,

Dogmatic statements like this lead to bad, messy code. I’m a firm believer that you should use whatever style fits the problem most.

Although I agree most code would be better if people followed this dogma, sometimes mutability is just more clean/idiomatic/efficient/…

Corbin,

Define your terms before relying on platitudes. Mutability isn’t cleaner if we want composition, particularly in the face of concurrency. Being idiomatic isn’t good or bad, but patterned; not all patterns are universally desirable. The only one which stands up to scrutiny is efficiency, which leads to the cult of performance-at-all-costs if one is not thoughtful.

9point6,

I agree somewhat, but I’d also say any codebase needs some level of “dogmatic” standard (ideally enforced via tooling). Otherwise you still end up with bad, messy code (I’d even say messier, as you don’t even get consistency)

sukhmel,

I’d agree with the first half, but not the second. Sometimes mutability allows for more concise code, although in most cases it’s better to not mutate at all

9point6,

I feel like I should maybe have put a “probably” in there

After all “there’s no silver bullet”, but in anything but a few edge cases, the rule applies, IMO

BaardFigur,

What about movable objects? You can’t move a const object

whotookkarl,
@whotookkarl@lemmy.world avatar

I think the general idea would be to take the original const, and create a new const with the new location applied. Destroy the original when it’s no longer needed or scoped. State maintained through parameters passed to the move function e.g. move(original const, new location) -> new const object instead of stateful members in the object like move(mutable, new location) -> updated mutable.

Ironfacebuster,

A const object meets an immutable variable

RageAgainstTheRich,

That is a… strange take.

Random example, imagine a variable that holds the time of the last time the user moved the mouse. Or in a game holding the current selected target of the player. Or the players gold amount. Or its level. Or health. Or current position.

frezik,

In all those cases, the answer is to swap in a new variable and throw the old one away.

RageAgainstTheRich,

Legit question because i think I’m misunderstanding. But if its a const, how are you able to swap or replace it?

frezik,

It’s only a const within a function. You can pass the value to another function and changing it as it’s passed. For example:


<span style="color:#323232;">const int foo = 1
</span><span style="color:#323232;">other_func( foo + 1)
</span>

In functional programming, you tend to keep track of state on the stack like this.

madcaesar,

What is the advantage of this VS just overwriting the var?

frezik,

Keeping state managed. The data for the function will be very predictable. This is especially important when it comes to multithreading. You can’t have a race condition where two things update the same data when they never update it that way at all.

madcaesar,

Hm I’m having trouble visualizing this do you know a quick little example to illustrate this?

frezik,

Rather than me coming up with an elaborate and contrived example, I suggest giving a language like Elixir a try. It tends to force you into thinking in terms of immutability. Bit of a learning curve if you’re not used to it, but it just takes practice.

madcaesar,

Ok how about this then, I frequently do something like this:


<span style="color:#323232;">let className = 'btn'
</span><span style="color:#323232;">  if (displayType) {
</span><span style="color:#323232;">    className += ` ${displayType}`
</span><span style="color:#323232;">  }
</span><span style="color:#323232;">  if (size) {
</span><span style="color:#323232;">    className += ` ${size}`
</span><span style="color:#323232;">  }
</span><span style="color:#323232;">  if (bordered) {
</span><span style="color:#323232;">    className += ' border'
</span><span style="color:#323232;">  }
</span><span style="color:#323232;">  if (classNameProp) {
</span><span style="color:#323232;">    className += ` ${classNameProp}`
</span><span style="color:#323232;">  }
</span>

How would this be made better with a functional approach? And would be more legible, better in anyway?

frezik,

I’d say this example doesn’t fully show off what immutable data can do–it tends to help as things scale up to much larger code–but here’s how I might do it in JS.


<span style="color:#323232;">function generate_class_name( display_type, size, bordered, class_name_prop ) 
</span><span style="color:#323232;">{
</span><span style="color:#323232;">  classes = [
</span><span style="color:#323232;">      'btn',
</span><span style="color:#323232;">      ( display_type ? display_type : [] ),
</span><span style="color:#323232;">      ( size ? size : [] ),
</span><span style="color:#323232;">      ( bordered ? bordered : [] ),
</span><span style="color:#323232;">      ( class_name_prop ? class_name_prop : [] ),
</span><span style="color:#323232;">  ];
</span><span style="color:#323232;">
</span><span style="color:#323232;">  return classes.flat().join( " " );
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">console.log( "<"
</span><span style="color:#323232;">    + generate_class_name( "mobile", "big", null, null )
</span><span style="color:#323232;">    + ">" );
</span><span style="color:#323232;">console.log( "<"
</span><span style="color:#323232;">    + generate_class_name( "desktop", "small", "solid", "my-class" ) 
</span><span style="color:#323232;">    + ">" );
</span><span style="color:#323232;">console.log( "<"
</span><span style="color:#323232;">    + generate_class_name( null, "medium", null, null ) 
</span><span style="color:#323232;">    + ">" );
</span>

Results:


<span style="color:#323232;"><btn mobile big>
</span><span style="color:#323232;"><btn desktop small solid my-class>
</span><span style="color:#323232;"><btn medium>
</span>

Notice that JavaScript has a bit of the immutability idea built in here. The Array.flat() returns a new array with flattened elements. That means we can chain the call to Array.join( " " ). The classes array is never modified, and we could keep using it as it was. Unfortunately, JavaScript doesn’t always do that; push() and pop() modify the array in place.

This particular example would show off its power a little more if there wasn’t that initial btn class always there. Then you would end up with a leading space in your example, but handling it as an array this way avoids the problem.

madcaesar,

Very interesting. Actually the part you mention about there being an initial ‘btn’ class is a good point. Using arrays and joining would be nice for that. I wish more people would chime in. Because between our two examples, I think mine is more readable. But yours would probably scale better. I also wonder about the performance implications of creating arrays. But that might be negligible.

RageAgainstTheRich,

Aaah okay i get it now :) that makes a lot more sense.

Magnetar,

Scala user unite! There are dozens of us, dozens!

crispy_kilt,

Scala? Can we reimplement it in Rust?

lemmesay,
@lemmesay@discuss.tchncs.de avatar

sure, just make sure to add “blazingly fast” in the description and append “-rs” to the name

Magnetar,

But does it do everything in anonymous functions and lambdas?

crispy_kilt,

It can

loxdogs,

can someone explain please?

noli,

In functional programming, everything is seen as a mathematical function, which means for a given input there is a given output and there can be no side effects. Changing a variable’s value is considered a side effect and is thus not possible in pure functional programming. To work around this, you typically see a lot of recursive and higher order functions.

Declaring all values as const values is something you would do if you’re a diehard functional programmer, as you won’t mutate any values anyway.

loxdogs,

thanks, kinda understand

Mir,

What is the best practice then when you want to update a variable’s value?

Nomecks,

j = i + something

noli,

Depends on how deep down the rabbit hole you want to go :p

  • creating a new variable that contains the updated value
  • recursion (e.g. it’s not possible to make a loop that increments i by 1, but it is possible to turn that loop into a function which calls itself with i+1 as argument)
  • avoiding typical types of operations that would update variable values. For example instead of a for loop that updates every element of a list, a functional programmer will use the map function, which takes a list and a function to apply to each element of that list to create an updated list. There’s several more of these very typical functions that are very powerful once you get used to using them.
  • monads (I’m not even gonna try to explain them as I hardly grasp them myself)
DaforLynx,

You just dropped a mind bomb on me. Suddenly things make sense :o

shield_gengar,
@shield_gengar@sh.itjust.works avatar

A monad is just a monoid in the category of endofunctors, what’s the problem?

gerryflap,
@gerryflap@feddit.nl avatar

Ngl, it’d solve a lot of bugs

BaardFigur, (edited )

And cause some unfortunate accidental pessimizations, at least in C++

crispy_kilt,

Is this some joke I’m too Rust to understand?

FlorianSimon,

Do you have any example in mind? I’m very interested!

BaardFigur,
FlorianSimon,

Thank you!

xmunk,

The only const in life is to const all the things.

sukhmel,
  • All
  • Subscribed
  • Moderated
  • Favorites
  • programmer_humor@programming.dev
  • rosin
  • thenastyranch
  • ethstaker
  • osvaldo12
  • mdbf
  • DreamBathrooms
  • InstantRegret
  • magazineikmin
  • Youngstown
  • ngwrru68w68
  • slotface
  • GTA5RPClips
  • kavyap
  • cubers
  • JUstTest
  • everett
  • cisconetworking
  • tacticalgear
  • anitta
  • khanakhh
  • normalnudes
  • Durango
  • modclub
  • tester
  • provamag3
  • Leos
  • megavids
  • lostlight
  • All magazines