Podcast #128: We chat with Kent C Dodds about why he loves React and discuss what life was like in the dark days before Git. Listen now.

Hot answers tagged

285

Very briefly, it makes program state unpredictable. To elaborate, imagine you have a couple of objects that both use the same global variable. Assuming you're not using a source of randomness anywhere within either module, then the output of a particular method can be predicted (and therefore tested) if the state of the system is known before you execute ...


135

Mutable global state is evil for many reasons: Bugs from mutable global state - a lot of tricky bugs are caused by mutability. Bugs that can be caused by mutation from anywhere in the program are even tricker, as it's often hard to track down the exact cause Poor testability - if you have mutable global state, you will need to configure it for any tests ...


118

First, I'd say that the answer you link to overstates that particular issue and that the primary evil of global state is that it introduces coupling in unpredictable ways that can make it difficult to change the behaviour of your system in future. But delving into this issue further, there are differences between global state in a typical object-oriented ...


94

"web applications should be stateless" should be understood as "web applications should be stateless unless there is a very good reason to have state". A "shopping cart" is a stateful feature by design, and denying that is quite counter-productive. The whole point of the shopping cart pattern is to preserve the state of the application between requests. An ...


62

Since your whole damn app can be using it, it's always incredibly hard to factor them back out again. If you ever change anything to do with your global, all your code needs changing. This is a maintenance headache- far more than simply being able to grep for the type name to find out which functions use it. They're bad because they introduce hidden ...


56

It's true that web applications should be stateless. However, session variables, cookies, and tokens don't violate this when they are all stored on the client (web browser). They can be parameters in the request. Here's a simplified model: Web Browser (has state) <-> Web Server (stateless) <-> Database (has state) This could work for Software ...


46

You have state when you associate values (numbers, strings, complex data structures) to an identity and a point in time. For example, the number 10 by itself does not represent any state: it is just a well-defined number and will always be itself: the natural number 10. As another example, the string "HELLO" is a sequence of five characters, and it is ...


45

I'd offer a few observations: Yes, a database is global state. In fact, it's a super-global state, as you pointed out. It's universal! Its scope entails anything or anyone that connects to the database. And, I suspect lots of folks with years of experience can tell you horror stories about how "strange things" in the data led to "unexpected behavior" in ...


37

There is no rule. It's entirely up to how you want to make your API "feel." Personally, in a music player, I think a transition from the state Stopped to Stopped by means of the method Stop() is a perfectly valid state transition. It's not very meaningful, but it is valid. With this in mind, throwing an exception would seem pedantic and unfair. It would ...


34

If you say "state", that is usually taken to mean "mutable state". And global mutable state is totally evil, because it means that any part of the program can influence any other part (by changing the global state). Imagine debugging an unknown program: You find that function A behaves a certain way for certain input parameters, but sometimes it works ...


32

What exactly is meant by this? In this context, it means that OOP obscures the state of a program by hiding it away from the programmer but still making it visible via (leaky) accessor methods. The argument is that by obscuring the state, it makes it more difficult to work with, and by extension lead to more bugs. how accurate/relevant do you guys think ...


30

web applications should be stateless Nonsense. Web requests should be stateless. Or more accurately, web requests are stateless. But, saying that a whole application should be stateless is complete nonsense. each request is treated as an independent transaction. Yes, exactly. Or more accurately, yes, necessarily. Over HTTP, each request is inherently ...


29

All else being equal, you should express your invariants in code. In this case you have the invariant $this->tax = $this->taxPC * 0.01 * $this->price; To express this in your code, remove the tax member variable and replace getTaxAmt() with public function getTaxAmt() { return $this->taxPC * 0.01 * $this->price; } You should do ...


22

What's the difference between new CustomerReceiptCreator().createReceipt() and CustomerReceiptCreator.createReceipt()? Pretty much none. The only significant difference is that the first case has considerably more awkward syntax. If you follow the first in the belief that somehow avoiding static methods makes your code better OO, you are gravely mistaken. ...


21

I disagree with the fundamental claim that: When your program is working with data from a database, you don't care if other code in your system is changing it, or even if an entirely different program is changing it, for that matter. My initial thought was "Wow. Just Wow". So much time and effort is spent trying to avoid exactly this - and working out ...


18

The point that the sole reason global variables can't be trusted since the state can be changed somewhere else is, in itself, not reason enough to not use them, agreed (it's a pretty good reason though!). It's likely the answer was mainly describing usage where restricting a variable's access to only areas of code that its concerned with would make more ...


17

Short answer: yes. According to Wikipedia, the equivalence of lambda calculus to Turing machines as an universal model of computation was shown 1937 by Alan Turing. The computational model of a Turing machine is what you typically have in mind when talking about imperative or stateful programming, and lambda calculus is a mathematically formalization of "...


17

There are two distinct kinds of actions one may wish to perform: Simultaneously test that something is in one state, and change it to another. Set something to a particular state, without regard for the previous state. Some contexts require one action, and some require the other. If a media player which reaches the end of content will remain in a "...


17

In the context of web applications, we call the server stateful if it maintains transient state in memory, rather than storing any data externally (e.g. in a database). Stateful applications have a number of problems, for example: you can't have more than one server running without pinning sessions to a particular server the state is lost when the server ...


16

Doesn't any mutable thing really manipulate state? Yes. And what does the "you should have to deal with little state" mean? It means that less state is better than more state. More state tends to introduce more complexity. In an impure language like C++, isn't state management really what you are doing? Yes. What are other ways to "deal with ...


15

I'll try to hint on the answer. This is not an answer, only an introductory illustration. @jk's answer points to the real thing, zippers. Imagine you have an immutable tree structure. You want to alter one node by inserting a child. As a result, you get a whole new tree. But most of the new tree is exactly the same as old tree. A clever implementation ...


15

Statefulness is not necessarily a bad thing, but you need to understand the difference between stateful and stateless apps. In short, stateful apps maintain information about the current session, and stateless apps do not. Information stored permanently as part of a user account may or may not be stored in a session, but storing information related to a user ...


14

In whatever dynamic system, the "state" is what make your present to be influenced by your past or future (the arrow of time is not a mathematical issue, just a physical constrain). Whether you have something to "remember" or that depends on what you did, you have a state. A system with no state is not "dynamic": it is just a combinatorial function. That ...


14

I like this question. The following is from my head but I think it fits quite well. status is used to describe an outcome of an operation (e.g. success/fail). state is used to describe a stage in a process (e.g. pending/dispatched). I also like this definition: status is a final (resulting) state. It is quite clear when applied to programming. Much less ...


14

The whole program is going to end up contained in the IO monad, basically. That's the bit where I think you're not seeing it from the Haskellers' perspective. So we have a program like this: module Main main :: IO () main = do xmlData <- readFile "input.xml" let jsonData = convert xmlData writeFile "output.json" jsonData convert :: String -> ...


13

Any disadvantages[?] Sure. This method relies on everyone always remembering to do something. Any method relying on everyone&always is bound to fail sometimes. maybe better ways to do this? One way to avoid the burden of remembering ceremony is calculating properties of the object that depend on other properties as needed, as @eigensheep suggested. ...


13

Is this what the global state must overcome to be accepted? No. Adding contracts to what goes into and out of global state is as easy as using a language with real types. There are lots of those and global state is still evil there. Things you're missing: Who fubar'd my data?!? - the biggest, most obvious problem with global mutable state is that anyone ...


12

(I don't know Erlang, and I can't write Haskell, but I think I can answer nevertheless) Well, in that interview the example of a random number generation library is given. Here is a possible stateful interface: # create a new RNG var rng = RNG(seed) # every time we call the next(ceil) method, we get a new random number print rng.next(10) print rng.next(10)...


11

State is simply information about something held in memory. As a simple exercise in object orientation, think of a class as a cookie cutter, and cookies as objects. You can create a cookie (instantiate an object) using the cookie cutter (class). Let's say one of the properties of the cookie is its color (which can be changed by using food coloring). The ...


Only top voted, non community-wiki answers of a minimum length are eligible