7 ms·
The concept of class invariant in object-oriented programming
- zabzonk 4y agoi like the idea of invariants. i even like their implementation in eiffel. i even quite like eiffel as a language. too bad that Meyer never produced a useable implementation of it, and that he was so destroyed by envy over the success of C++.
- pjmlp 4y agoEiffel Software keeps the lights on for almost 30 years now, given how little many care to pay for their tooling, it seems quite usable to me.
- anonymousDan 4y agoInteresting, but a pity concurrency seems to cause the whole thing to break down.
- rramadass 4y agoRelated: Applying Design by Contract (pdf) - https://se.inf.ethz.ch/~meyer/publications/computer/contract.pdf https://se.inf.ethz.ch/~meyer/publications/computer/contract... See Also: https://en.wikipedia.org/wiki/Design_by_contract https://en.wikipedia.org/wiki/Design_by_contract
- moloch-hai 4y agoInvariants are the single most useful concept, in any programming environment, for making and keeping correct systems. They are necessary to reason mathematically about systems. In interviews, I find them very inconsistently taught. Invariants are not a substitute for anything else, but bolt on cleanly to whatever else you are doing. Whatever power functional programming offers comes from having numerous invariants baked in.
- fooker 4y agoInvariants (of various kinds) are great concepts. There is a good reason you won't find these in mainstream languages though. Invariants are mind-bogglingly difficult to come up with and incrementally update. For any non-trivial code, you will be spending significantly more time thinking about invariants than implementing functionality. If you think a borrow-checker is a cognitive overhead, invariants are significantly more so. I am sure there are people who would consider than a good thing, and even argue that it results in better code in the long run. Just not enough for pushing these into mainstream languages.
- gavinray 4y agoClass invariants are fundamental to Functional Programming too They are the core principle our of much-beloved Lexi Lambda's "Parse, Don't Validate" approach. One example might be a dataclass called "NonEmptyAlphanumericString" in Kotlin: data class NonEmptyAlphanumericString(val value: String) { init { require(value.isNotBlank()) { "String cannot be blank" } require(value.all { it.isLetterOrDigit() }) { "String must be alphanumeric" } } } Here we have a data type that is parsed from a basic "String" and enforces the invariants that the string is neither empty, nor contains non-alphanumeric characters. If it fails those invariants, we won't get a valid instance of "NonEmptyAlphanumericString" and "require()" will throw. (Though is this is a bit different because there is purposefully no mutable state here, if you enforce invariants again it's through creating a new instance of the immutable class)
- dfee 4y agoI never got it, but on a reread: > Is it really parsing anything, or is it merely validating its input and returning a result? Ok. Now I guess I’m on board. Just feels like the word is wrong. > Consider: what is a parser? Really, a parser is just a function that consumes less-structured input and produces more-structured output. By its very nature, a parser is a partial function—some values in the domain do not correspond to any value in the range—so all parsers must have some notion of failure. Ok. It still feels like there’s a better word. “Constrain” might sit better with me, though I’ve not spent enough time to really worry about its fit. https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/ https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...
- Snarwin 4y agoMaybe "decode"? As in "decode a Unicode string", or "decode a JPEG image", or "decode an MP3 audio file."
- lalaithion 4y agoThe key of the idea is you're not asserting that predicates on values are true, you're recognizing whether a value (of a type with few guarantees) conforms to the guarantees of a type (implicitly, a type with more guarantees), and transforming the value into a value of the output type. Parsing might not be the right word, but it's definitely an example of the above; we transform a string into a tree of tagged nodes.
- wheelerof4te 4y agoSorry, 99% of these buzzwords aren't applicable in real life, professional programming. Business just wants stuff to work, no matter how you make it work.
- thesuperbigfrog 4y ago>> Sorry, 99% of these buzzwords aren't applicable in real life, professional programming. Professionals use proven tools and techniques to get the job done. Design by Contract (DbC) is a proven technique that ensures code is robust and does what it is supposed to do. >> Business just wants stuff to work, no matter how you make it work. Business cares if shody code has security vulnerabilities that lets money or customer data be stolen. DbC has been proven to help prevent shody code.
- vidarh 4y agoVarious forms of checking invariants is applied in all kinds of "real life, professional programming" ranging from test suites to e.g. invariants checked by your database schema. Most code contains huge amounts of manually written invariants (every check to determine if a value is valid before e.g. setting an instance variable in a class is an attempt to maintain an invariant), and often it'd be a lot faster to get stuff to work with more comprehensive ability to enforce invariants - whether just during development or in production too.
- jrochkind1 4y agoIn real life, most software is a fragile unreliable timebomb waiting to ruin businesses and lives.
- zabzonk 4y agoit wants it to work correctly, and it wants it to work fast. this is what all these "buzzwords" enable.
- UncleMeat 4y agoIn my experience, class invariants are among the very most useful techniques for enabling rapid development of features while managing mutable data. They allow you to "make stuff work" at a faster pace than otherwise.
- jstx1 4y ago> Class invariants — consistency constraints preserved by ev- ery operation on objects of a given type — are fundamental to building, understanding and verifying object-oriented programs. I think calling them "consistency constraints" would have made everything much easier to understand. Although I'll admit that I have a strong bias against nouns that can also be adjectives in programming terminology (invariant, generic, atomic, primitive etc). There's something about them that makes my brain spin an extra cycle to process them.
- riffraff 4y agoBut "invariant" has application in various areas, e.g. you can have a loop invariant, or function invariant. The concept/wording makes more sense on this case than "loop consistency constraint", and then you get the benefit of the concept carrying over to different places.
- okr 4y agoBack in the day i struggled with the term invariant, same as with pre- and postconditions. Now i am actually quite happy being able to use them. Anyways,when i describe invariant i also say something is in itself consistent or true.
- hinkley 4y agoJava came along with a free compiler and Meyer still insisted on charging for his. That’s what killed Eiffel. And a doomed a generation and a half of devs to shitty object orientes analysis, culminating in Design Patterns, and reaching its absurd conclusion in Enterprise Design Patterns (institutionalized architectural astronautics). Which incidentally was published after Alexander had already moved on to new organizational principles.
- _a_a_a_ 4y agoQuite so; it is invariantly true
- afterburner5 4y agoI worked for a company at some point where, due to the how the original product was built, testing before a release took between 3 and 5 days and was generally quite brittle. Within my first three months there, we had business requests to improve that. Invariants, and generally speaking, contracts for our models helped us out. Because we were able to run effective, cheap, fast tests, that proved our implementations were satisfying our requirements, pre and post conditions, invariants, the whole shebang, at the contract level, without even worrying about the actual underlying implementation. This greatly simplified the release tests, and it meant we were able to release much quicker, and with a higher confidence than before
- tabtab 4y agoIn business and administrative applications, there are very few reliable "invariants". Demo examples often use physics and geometry for a reason: Mother nature rarely changes those. Biz is different: new legislation, corporate edicts, new CEO's etc. can "rewrite" anything. These animal and shape demos gave too many the wrong impression of categories and types, creating "spaghetti class" messes that are still being cleaned up today. Has-A has replaced Is-A as the better modelling mechanism in my domain, but it turns out relational does Has-A better than OOP modelling because it's based around set theory, not category hierarchies.
- anonymousDan 4y agoI don't see any problem with evolving invariants over time as business requirements change. The point is to be clear about your invariants for any given release.
- tabtab 4y agoWe usually put most "constraints" in the database. It's often a D.R.Y. violation to echo them in code.
- anonymousDan 4y agoAh, I think I understand your previous comment a bit better now. Yes it's a fair point about the best place to enforce the invariants.
- bmm6o 4y agoIf the requirements change then the code is changed and the invariants are updated as necessary.
- kazinator 4y ago> [Callbacks] can find an object in a state not satisfying the invariant. Example: "please don't delete item X from the dictionary out of a traversal callback visiting item X." :)
- torial 4y agoThere was a now-defunct python-like language built on .Net called Cobra that had class invariants and other contract functionality. It generally speaking had a lot of ideas focused on high quality programming built into the language which made it great to program against. I wish it had caught on.... http://cobra-language.com/ http://cobra-language.com/
- moritzwarhier 4y agoListing and implementing/asserting invariants of data structures feels underrated. To me, it makes so much more sense than trying to sell writing tests to my stakeholders.