Leis, teorias, princípios e padrões que desenvolvedores acharão úteis.
Traduções: 🇧🇷 🇨🇳 🇩🇪 🇫🇷 🇬🇷 🇮🇹 🇱🇻 🇰🇷 🇷🇺 🇪🇸 🇹🇷
Gostou deste projeto? Por favor, considere me apoiar e apoiar os tradutores.
- Introdução
- Leis
- Princípio 90-9-1 (Regra do 1%)
- Lei de Amdahl
- Teoria das Janelas Quebradas
- Lei de Brook
- Lei de Conway
- Lei de Cunningham
- Número de Dunbar
- Lei de Gall
- Lei de Goodhart
- Navalha de Hanlon
- Lei de Hofstadter
- Lei de Hutber
- O Ciclo Hype e Lei de Amara
- Lei de Hyrum (Lei das Interfaces Implícitas)
- Lei de Kernighan
- Lei de Metcalfe
- Lei de Moore
- Lei de Murphy / Lei de Sod
- Navalha de Occam
- Lei de Parkinson
- Efeito de Otimização Prematura
- Lei de Putt
- Lei de Reed
- A Lei da Conservação da Complexidade (Lei de Tesler)
- A Lei das Abstrações Gotejantes
- A Lei da Trivialidade
- A Filosofia Unix
- O Modelo Spotify
- Lei de Wadler
- Lei de Wheaton
- Princípios
- O Princípio Dilbert
- O Princípio de Pareto (Regra do 80/20)
- O Princípio de Peter
- O Princípio da Robustez (Lei de Postel)
- SOLID
- O Princípio da Responsabilidade Única
- O Princípio do Aberto/Fechado
- O Princípio da Substituição de Liskov
- O Princípio da Segregação de Interface
- O Princípio da Inversão de Dependência
- O Princípio DRY
- O Princípio KISS
- YAGNI
- As Falácias da Computação Distribuída
- Lista de leitura
- Traduções
- Projetos relacionados
- Contribuindo
- Em construção
Existem muitas leis sobre as quais as pessoas discutem quando falam sobre desenvolvimento. Este repositório é uma referência e uma visão global das mais comuns. Sinta-se a vontade para contribuir e compartilhar.
❗: Este repositório contém explicações sobre algumas leis, princípios e padrões, mas não advoga nenhum. Se eles devem ser aplicados é uma questão de discussão, e depende diretamente no que você está trabalhando.
E lá vamos nos!
The 90-9-1 principle suggests that within an internet community such as a wiki, 90% of participants only consume content, 9% edit or modify content and 1% of participants add content.
Real-world examples:
- A 2014 study of four digital health social networks found the top 1% created 73% of posts, the next 9% accounted for an average of ~25% and the remaining 90% accounted for an average of 2% (Reference)
See Also:
A lei de Amdahl, também conhecida como argumento de Amdahl, é usada para encontrar a máxima melhora esperada para um sistema em geral quando apenas uma única parte do mesmo é melhorada. Isto é frequentemente usado em computação paralela para prever o máximo speedup teórico usando múltiplos processadores. A lei possui o nome do Arquiteto computacional Gene Amdahl, e foi apresentada a AFIPS na Conferência Conjunta de Informática na primavera de 1967.
Fica mais fácil de entender com um exemplo prático. Se um programa é feito de duas partes, parte A, que é executada por um processador único, e parte B, que pode ser feito paralelamente com N processadores. Se adicionarmos mais processaores ao sistema, só vai ter aumento nas tarefas relacionadas à parte B do programa. A velocidade de A se mantém a mesma.
O diagrama abaixo mostra alguns exemplos de melhoria na velocidade:
(Image Reference: By Daniels220 at English Wikipedia, Creative Commons Attribution-Share Alike 3.0 Unported, https://en.wikipedia.org/wiki/File:AmdahlsLaw.svg)
Como pode-se perceber, mesmo um programa que teve metade da sua implementação de forma paralela, o benefício é menos de 10 processing units. Porém, um programa 95% paralelo, o ganho pode passar de 20 processing units.
The Broken Windows Theory on Wikipedia
The Broken Windows Theory suggests that visible signs of crime (or lack of care of an environment) lead to further and more serious crimes (or further deterioration of the environment).
This theory has been applied to software development, suggesting that poor quality code (or Technical Debt) can lead to a perception that efforts to improve quality may be ignored or undervalued, thus leading to further poor quality code. This effect cascades leading to a great decrease in quality over time.
See also:
Examples:
- The Pragmatic Programming: Software Entropy
- Coding Horror: The Broken Window Theory
- OpenSource: Joy of Programming - The Broken Window Theory
Adicionar recursos humanos em um projeto, de desenvolvimento de sotware, atrasado, faz ficar ainda mais atrasado.
Essa lei sugere que em muitos casos, na tentativa de acelerar uma entrega, que já está atrasada, adcionando mais pessoas atrasa ainda mais essa entrega. Brooke assume que essa afirmação é uma generalização excessiva, entretanto, o principal motivo para isso acontecer é dado pelo simples fato de adicionar pessoas requer um gasto com comunicação e construção de novos recursos para a equipe suportar novos membros. Logo, a curto prazo esse investimento não tem um retorno. Também existem tarefas que não podem ser dividias, portanto adicionar mais pessoas não vai fazer ela ser concluida mais rápido.
"Nove mulheres não podem parir uma criança em um mês" e "Dois pilotos não fazem o carro ir mais rápido" são frases relacionadas a Lei de Brooke, principalmente porque algumas tarefas nao podem ser divididas.
Esse é um tema central do livro'The Mythical Man Month'.
Veja também:
Essa lei sugere que limites técnicos de um sistema refletirão na estrutura da organização. Se uma organização é estruturada em pequenos setores, desconexas unidades, o sofware que ela produz sera assim também. Se uma organização é construida de forma vertical, em torno de funcionalidades e serviços, terá reflexo disso dentro do sistema.
Veja também:
The best way to get the right answer on the Internet is not to ask a question, it's to post the wrong answer.
According to Steven McGeady, Ward Cunningham advised him in the early 1980s: "The best way to get the right answer on the Internet is not to ask a question, it's to post the wrong answer." McGeady dubbed this Cunningham's law, though Cunningham denies ownership calling it a "misquote." Although originally referring to interactions on Usenet, the law has been used to describe how other online communities work (e.g., Wikipedia, Reddit, Twitter, Facebook).
See also:
[Dumbar] propós que humanos só conseguem manter de forma confortável, 150 relacionamentos estáveis. Esse número está mais em um contexto social, "o número de pessoas que você não se sentiria sem graça para se juntar em uma bebiba se esbarrase com ela em um bar". Esse número geralmente está entra 100 e 250.
Esse número é uma sugestão cognitiva limite para o número de pessoass para qual consegue-se manter uma relação social estável.
Como uma relação entre pessoas, manter uma relação entre desenvolvedor e codigo requer esforço. É necessário usar politicas, padrões e procedimentos para encarar projetos complicados ou qualquer adversidade possível nesse tipo de relação. Número de Dunbar é importante em vários aspectos, não somente quando a empresa está em crescimento, mas também ao definir o escopo para os esforços da equipe ou decidir quando u msistema deve investir em ferramentas para axuliar na sobrecarga da logística. Colocando em contexto de engrenharia, é o número de projetos para os quais você se sentiria confiante para ingresssar em uma rotação de plantão de suporte.
Veja também:
A complex system that works is invariably found to have evolved from a simple system that worked. A complex system designed from scratch never works and cannot be patched up to make it work. You have to start over with a working simple system.
Gall's Law implies that attempts to design highly complex systems are likely to fail. Highly complex systems are rarely built in one go, but evolve instead from more simple systems.
The classic example is the world-wide-web. In its current state, it is a highly complex system. However, it was defined initially as a simple way to share content between academic institutions. It was very successful in meeting these goals and evolved to become more complex over time.
See also:
The Goodhart's Law on Wikipedia
Any observed statistical regularity will tend to collapse once pressure is placed upon it for control purposes.
Charles Goodhart
Also commonly referenced as:
When a measure becomes a target, it ceases to be a good measure.
Marilyn Strathern
The law states that the measure-driven optimizations could lead to devaluation of the measurement outcome itself. Overly selective set of measures (KPIs) blindly applied to a process results in distorted effect. People tend to optimize locally by "gaming" the system in order to satisfy particular metrics instead of paying attention to holistic outcome of their actions.
Real-world examples:
- Assert-free tests satisfy the code coverage expectation, despite the fact that the metric intent was to create well-tested software.
- Developer performance score indicated by the number of lines committed leads to unjustifiably bloated codebase.
See also:
Navalha de Hanlon na wikipedia
Nunca atribua à malícia aquilo que é adequadamente explicado por estupidez.
Robert J. Hanlon
Esse principio sugeste que ações negativas não são sempre resultado de má vontade. Em vez disso, é mais provável que o resultado negativo seja atribuido à ações que não foram totalmente entendidas.
Lei de Hofstadter na Wikipedia
Sempre leva mais tempo do que esperado, mesmo quando se leva em conta a lei do Hofstadter.
Douglas Hofstadter
Você já deve ter ouvido sobre essa lei quando se fala em estimar tempo para fazer algo. Quando se fala em desenvolvimento de software parece obvio que nós tendemos a não sermos muitos precisos em estimar quando tempo levará para entregar alguma coisa.
This is from the book 'Gödel, Escher, Bach: An Eternal Golden Braid'.
Improvement means deterioration.
This law suggests that improvements to a system will lead to deterioration in other parts, or it will hide other deterioration, leading overall to a degradation from the current state of the system.
For example, a decrease in response latency for a particular end-point could cause increased throughput and capacity issues further along in a request flow, affecting an entirely different sub-system.
Nós tendemos a superestimar os efeitos da tecnologia em curto prazo e subestimar os efeitos a longo prazo.
Roy Amara
O Ciclo Hype é uma representação visual da empolgação e desenvolvimento da tecnologia ao longo do tempo, originalmente produzida por Gartner.
(Image Reference: By Jeremykemp at English Wikipedia, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=10547051)
Em curto prazo, o ciclo sugere que acontece uma explosão de empolgação a cerca de uma nova tecnologia e seu impacto em potencial. Equipes geralmente entram juntas nessas tecnlogias de forma rápida e em alguns casos ficam desapontados com os resutados. Uma das possíveis causas para isso é o fato da tecnologia em questão não ser madura o suficiente, ou aplicações do mundo real que não estão totalmente prontas. Depois de um certo tempo, a capacidade da tecnologia aumenta e oportunidades práticas para uso dela aumentam, as equipes finalmente podem ser produtivas. A citação de Amara resume isso de forma sucinta - "Nós tendemos a superestimar os efeitos da tecnologia em curto prazo e subestimar os efeitos a longo prazo".
Com um número suficientes de clientes de uma API, não importa a sua pré-condição no contato: todos os comportamentos observáveis do seu sistema serão dependentes de alguém.
(Hyrum Wright)
A lei de Hyrum sugere que quando você tem um número muito grande de consumidores de uma API, todos os comportamentos dessa API (mesmo aqueles que não estão definidos como parte de um contrato público) eventualmente irão dependender de outra parte do sistema, ou outra API. Um exemplo trivial pode ser elementos não funcionais, como o tempo de resposta de uma API. Um exemplo mais sutil pode ser os consumidores que estão confiando em aplicar um regex a uma mensagem de erro para determinar o tipo de erro de uma API. Mesmo que o contrato público da API não especifique nada sobre o conteúdo da mensagem, indicando que os usuários devem usar um código de erro associado, alguns usuários podem usar a mensagem e alterar a mensagem essencialmente interrompe a API para esses usuários.
Veja Também:
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
(Brian Kernighan)
Kernighan's Law is named for Brian Kernighan and derived from a quote from Kernighan and Plauger's book The Elements of Programming Style:
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?
While hyperbolic, Kernighan's Law makes the argument that simple code is to be preferred over complex code, because debugging any issues that arise in complex code may be costly or even infeasible.
See also:
In network theory, the value of a system grows as approximately the square of the number of users of the system.
This law is based on the number of possible pairwise connections within a system and is closely related to Reed's Law. Odlyzko and others have argued that both Reed's Law and Metcalfe's Law overstate the value of the system by not accounting for the limits of human cognition on network effects; see Dunbar's Number.
See also:
O número de transistores dentro de um circuito integrado dobra a cada 2 anos, aproximadamente.
Até meados de 1965 não havia nenhuma previsão real sobre o futuro do hardware, quando Gordon E. Moore fez sua profecia, na qual o número de transistores dos chips teria um aumento de 100%, pelo mesmo custo, a cada período de 18 meses. Essa profecia tornou-se realidade e acabou ganhando o nome de Lei de Moore.
Esta lei serve de parâmetro para uma elevada gama de dispositivos digitais, além das CPUs. Na verdade, qualquer chip está ligado a lei de Gordon E. Moore, até mesmo o CCD de câmeras fotográficas digitais (sensor que capta a imagem nas câmeras nuclear; ou CNCL, sensores que captam imagens nas câmeras fotográficas profissionais).
Esse padrão continuou a se manter, e não se espera que pare até, no mínimo, 2021.
Anything that can go wrong will go wrong.
Related to Edward A. Murphy, Jr Murphy's Law states that if a thing can go wrong, it will go wrong.
This is a common adage among developers. Sometimes the unexpected happens when developing, testing or even in production. This can also be related to the (more common in British English) Sod's Law:
If something can go wrong, it will, at the worst possible time.
These 'laws' are generally used in a comic sense. However, phenomena such as Confirmation Bias and Selection Bias can lead people to perhaps over-emphasise these laws (the majority of times when things work, they go unnoticed, failures however are more noticeable and draw more discussion).
See Also:
Entities should not be multiplied without necessity.
William of Ockham
Occam's razor says that among several possible solutions, the most likely solution is the one with the least number of concepts and assumptions. This solution is the simplest and solves only the given problem, without introducing accidental complexity and possible negative consequences.
See also:
Example:
O trabalho se expande de modo a preencher o tempo disponível para a sua realização.
A lei de Parkinson foi publicada por Cyril Northcote Parkinson num artigo na revista The Economist em 1955, sendo depois reimpresso com outros artigos no livro Parkinson's Law: The Pursuit of Progress [A lei de Parkinson: a busca do progresso].Em seu contexto original, essa Lei foi baseada em estudos de burocracia. E pode ser pessimisticamente aplicado a desenvolvimento de software, a teoria diz que equipes serão ineficientes até os prazos finais, quando irão dar o máximo até o prazo final.
Premature Optimization on WikiWikiWeb
Premature optimization is the root of all evil.
In Donald Knuth's paper Structured Programming With Go To Statements, he wrote: "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."
However, Premature Optimization can be defined (in less loaded terms) as optimizing before we know that we need to.
Tecnologia é dominada por dois tipos de pessoa. Aqueles que entendem o que não gerenciam e aqueles que gerenciam o que não entendem.
A Lei de Putt é frequentemente seguida pelo Corolário de Putt:
Cada hierarquia técnica, no tempo, desenvolve uma inversão de competência.
Estas declarações sugerem que devido a vários critérios de seleção e tendências na forma como grupos se organizam, haverá um número de pessoas qualificadas nos níveis de trabalho de organizações técnicas, e um número de pessoas em funções gerenciais que não estão cientes das complexidades e desafios do trabalho que estão gerenciando. Isso pode ser devido a fenômenos como (#em-progresso)
Veja também:
The utility of large networks, particularly social networks, scales exponentially with the size of the network.
This law is based on graph theory, where the utility scales as the number of possible sub-groups, which is faster than the number of participants or the number of possible pairwise connections. Odlyzko and others have argued that Reed's Law overstates the utility of the system by not accounting for the limits of human cognition on network effects; see Dunbar's Number.
See also:
A lei da Conservação de Complexidade na wikipedia
Essa lei sugere que em todos sitemas sempre vai existir uma quantidade de complexidade que não pode ser reduzida.
Alguma complexidade em um sistema é "inadvertida". É uma consequência da estrutura deficiente, erros ou apenas má modelagem de um problema a ser resolvido. A complexidade inadvertida pode ser reduzida (ou eliminada). No entanto, alguma complexidade é "intrínseca" como consequência da complexidade inerente ao problema a ser resolvido. Essa complexidade pode ser movida, mas não eliminada.
Um elemento interessante para essa lei é a sugestão de que, mesmo simplificando todo o sistema, a complexidade intrínseca não é reduzida, ela é “movida para o usuário”, que deve se comportar de uma maneira mais complexa.
The Law of Leaky Abstractions on Joel on Software
Todas as abstrações não triviais, até certo ponto, são vazadas
This law states that abstractions, which are generally used in computing to simplify working with complicated systems, will in certain situations 'leak' elements of the underlying system, this making the abstraction behave in an unexpected way.
An example might be loading a file and reading its contents. The file system APIs are an abstraction of the lower level kernel systems, which are themselves an abstraction over the physical processes relating to changing data on a magnetic platter (or flash memory for an SSD). In most cases, the abstraction of treating a file like a stream of binary data will work. However, for a magnetic drive, reading data sequentially will be significantly faster than random access (due to increased overhead of page faults), but for an SSD drive, this overhead will not be present. Underlying details will need to be understood to deal with this case (for example, database index files are structured to reduce the overhead of random access), the abstraction 'leaks' implementation details the developer may need to be aware of.
The example above can become more complex when more abstractions are introduced. The Linux operating system allows files to be accessed over a network but represented locally as 'normal' files. This abstraction will 'leak' if there are network failures. If a developer treats these files as 'normal' files, without considering the fact that they may be subject to network latency and failures, the solutions will be buggy.
The article describing the law suggests that an over-reliance on abstractions, combined with a poor understanding of the underlying processes, actually makes dealing with the problem at hand more complex in some cases.
See also:
Real-world examples:
- Photoshop Slow Startup - an issue I encountered in the past. Photoshop would be slow to startup, sometimes taking minutes. It seems the issue was that on startup it reads some information about the current default printer. However, if that printer is actually a network printer, this could take an extremely long time. The abstraction of a network printer being presented to the system similar to a local printer caused an issue for users in poor connectivity situations.
The Law of Triviality on Wikipedia
This law suggests that groups will give far more time and attention to trivial or cosmetic issues rather than serious and substantial ones.
The common fictional example used is that of a committee approving plans for nuclear power plant, who spend the majority of their time discussing the structure of the bike shed, rather than the far more important design for the power plant itself. It can be difficult to give valuable input on discussions about very large, complex topics without a high degree of subject matter expertise or preparation. However, people want to be seen to be contributing valuable input. Hence a tendency to focus too much time on small details, which can be reasoned about easily, but are not necessarily of particular importance.
The fictional example above led to the usage of the term 'Bike Shedding' as an expression for wasting time on trivial details.
The Unix Philosophy on Wikipedia
The Unix Philosophy is that software components should be small, and focused on doing one specific thing well. This can make it easier to build systems by composing together small, simple, well-defined units, rather than using large, complex, multi-purpose programs.
Modern practices like 'Microservice Architecture' can be thought of as an application of this law, where services are small, focused and do one specific thing, allowing complex behaviour to be composed of simple building blocks.
The Spotify Model on Spotify Labs
The Spotify Model is an approach to team and organisation structure which has been popularised by 'Spotify'. In this model, teams are organised around features, rather than technologies.
The Spotify Model also popularises the concepts of Tribes, Guilds, Chapters, which are other components of their organisation structure.
Wadler's Law on wiki.haskell.org
In any language design, the total time spent discussing a feature in this list is proportional to two raised to the power of its position.
- Semantics
- Syntax
- Lexical syntax
- Lexical syntax of comments
(In short, for every hour spent on semantics, 8 hours will be spent on the syntax of comments).
Similar to The Law of Triviality, Wadler's Law states what when designing a language, the amount of time spent on language structures is disproportionately high in comparison to the importance of those features.
See also:
Don't be a dick.
Wil Wheaton
Coined by Wil Wheaton (Star Trek: The Next Generation, The Big Bang Theory), this simple, concise, and powerful law aims for an increase in harmony and respect within a professional organization. It can be applied when speaking with coworkers, performing code reviews, countering other points of view, critiquing, and in general, most professional interactions humans have with each other.
Os princípios são como diretrizes relacionadas à design.
The Dilbert Principle on Wikipedia
Companies tend to systematically promote incompetent employees to management to get them out of the workflow.
Scott Adams
A management concept developed by Scott Adams (creator of the Dilbert comic strip), the Dilbert Principle is inspired by The Peter Principle. Under the Dilbert Principle, employees who were never competent are promoted to management in order to limit the damage they can do. Adams first explained the principle in a 1995 Wall Street Journal article, and expanded upon it in his 1996 business book, The Dilbert Principle.
See Also:
The Pareto Principle on Wikipedia
Most things in life are not distributed evenly.
The Pareto Principle suggests that in some cases, the majority of results come from a minority of inputs:
- 80% of a certain piece of software can be written in 20% of the total allocated time (conversely, the hardest 20% of the code takes 80% of the time)
- 20% of the effort produces 80% of the result
- 20% of the work creates 80% of the revenue
- 20% of the bugs cause 80% of the crashes
- 20% of the features cause 80% of the usage
In the 1940s American-Romanian engineer Dr. Joseph Juran, who is widely credited with being the father of quality control, began to apply the Pareto principle to quality issues.
This principle is also known as: The 80/20 Rule, The Law of the Vital Few and The Principle of Factor Sparsity.
Real-world examples:
- In 2002 Microsoft reported that by fixing the top 20% of the most-reported bugs, 80% of the related errors and crashes in windows and office would become eliminated (Reference).
The Peter Principle on Wikipedia
People in a hierarchy tend to rise to their "level of incompetence".
Laurence J. Peter
A management concept developed by Laurence J. Peter, the Peter Principle observes that people who are good at their jobs are promoted, until they reach a level where they are no longer successful (their "level of incompetence"). At this point, as they are more senior, they are less likely to be removed from the organisation (unless they perform spectacularly badly) and will continue to reside in a role which they have few intrinsic skills at, as their original skills which made them successful are not necessarily the skills required for their new jobs.
This is of particular interest to engineers - who initially start out in deeply technical roles, but often have a career path which leads to managing other engineers - which requires a fundamentally different skills-set.
See Also:
The Robustness Principle on Wikipedia
Be conservative in what you do, be liberal in what you accept from others.
Often applied in server application development, this principle states that what you send to others should be as minimal and conformant as possible, but you should be aim to allow non-conformant input if it can be processed.
The goal of this principle is to build systems which are robust, as they can handle poorly formed input if the intent can still be understood. However, there are potentially security implications of accepting malformed input, particularly if the processing of such input is not well tested.
É um acrônimo para:
- S: The Single Responsibility Principle
- O: The Open/Closed Principle
- L: The Liskov Substitution Principle
- I: The Interface Segregation Principle
- D: The Dependency Inversion Principle
These are key principles in Object-Oriented Programming. Design principles such as these should be able to aid developers build more maintainable systems.
The Single Responsibility Principle on Wikipedia
Every module or class should have a single responsibility only.
The first of the 'SOLID' principles. This principle suggests that modules or classes should do one thing and one thing only. In more practical terms, this means that a single, small change to a feature of a program should require a change in one component only. For example, changing how a password is validated for complexity should require a change in only one part of the program.
Theoretically, this should make the code more robust, and easier to change. Knowing that a component which is being changed has a single responsibility only means that testing that change should be easier. Using the earlier example, changing the password complexity component should only be able to affect the features which relate to password complexity. It can be much more difficult to reason about the impact of a change to a component which has many responsibilities.
See also:
The Open/Closed Principle on Wikipedia
Entities should be open for extension and closed for modification.
The second of the 'SOLID' principles. This principle states that entities (which could be classes, modules, functions and so on) should be able to have their behaviour extended, but that their existing behaviour should not be able to be modified.
As a hypothetical example, imagine a module which is able to turn a Markdown document into HTML. If the module could be extended to handle a newly proposed markdown feature, without modifying the module internals, then it would be open for extension. If the module could not be modified by a consumer so that how existing Markdown features are handled, then it would be closed for modification.
This principle has particular relevance for object-oriented programming, where we may design objects to be easily extended, but would avoid designing objects which can have their existing behaviour changed in unexpected ways.
See also:
The Liskov Substitution Principle on Wikipedia
It should be possible to replace a type with a subtype, without breaking the system.
The third of the 'SOLID' principles. This principle states that if a component relies on a type, then it should be able to use subtypes of that type, without the system failing or having to know the details of what that subtype is.
As an example, imagine we have a method which reads an XML document from a structure which represents a file. If the method uses a base type 'file', then anything which derives from 'file' should be able to be used in the function. If 'file' supports seeking in reverse, and the XML parser uses that function, but the derived type 'network file' fails when reverse seeking is attempted, then the 'network file' would be violating the principle.
This principle has particular relevance for object-oriented programming, where type hierarchies must be modeled carefully to avoid confusing users of a system.
See also:
The Interface Segregation Principle on Wikipedia
No client should be forced to depend on methods it does not use.
The fourth of the 'SOLID' principles. This principle states that consumers of a component should not depend on functions of that component which it doesn't actually use.
As an example, imagine we have a method which reads an XML document from a structure which represents a file. It only needs to read bytes, move forwards or move backwards in the file. If this method needs to be updated because an unrelated feature of the file structure changes (such as an update to the permissions model used to represent file security), then the principle has been invalidated. It would be better for the file to implement a 'seekable-stream' interface, and for the XML reader to use that.
This principle has particular relevance for object-oriented programming, where interfaces, hierarchies and abstract types are used to minimise the coupling between different components. Duck typing is a methodology which enforces this principle by eliminating explicit interfaces.
See also:
The Dependency Inversion Principle on Wikipedia
High-level modules should not be dependent on low-level implementations.
The fifth of the 'SOLID' principles. This principle states that higher level orchestrating components should not have to know the details of their dependencies.
As an example, imagine we have a program which read metadata from a website. We would assume that the main component would have to know about a component to download the webpage content, then a component which can read the metadata. If we were to take dependency inversion into account, the main component would depend only on an abstract component which can fetch byte data, and then an abstract component which would be able to read metadata from a byte stream. The main component would not know about TCP/IP, HTTP, HTML, etc.
This principle is complex, as it can seem to 'invert' the expected dependencies of a system (hence the name). In practice, it also means that a separate orchestrating component must ensure the correct implementations of abstract types are used (e.g. in the previous example, something must still provide the metadata reader component a HTTP file downloader and HTML meta tag reader). This then touches on patterns such as Inversion of Control and Dependency Injection.
See also:
The DRY Principle on Wikipedia
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
DRY is an acronym for Don't Repeat Yourself. This principle aims to help developers reducing the repetition of code and keep the information in a single place and was cited in 1999 by Andrew Hunt and Dave Thomas in the book The Pragmatic Developer
The opposite of DRY would be WET (Write Everything Twice or We Enjoy Typing).
In practice, if you have the same piece of information in two (or more) different places, you can use DRY to merge them into a single one and reuse it wherever you want/need.
See also:
Keep it simple, stupid
The KISS principle states that most systems work best if they are kept simple rather than made complicated; therefore, simplicity should be a key goal in design, and unnecessary complexity should be avoided. Originating in the U.S. Navy in 1960, the phrase has been associated with aircraft engineer Kelly Johnson.
The principle is best exemplified by the story of Johnson handing a team of design engineers a handful of tools, with the challenge that the jet aircraft they were designing must be repairable by an average mechanic in the field under combat conditions with only these tools. Hence, the "stupid" refers to the relationship between the way things break and the sophistication of the tools available to repair them, not the capabilities of the engineers themselves.
See also:
This is an acronym for You Aren't Gonna Need It.
Always implement things when you actually need them, never when you just foresee that you need them.
(Ron Jeffries) (XP co-founder and author of the book "Extreme Programming Installed")
This Extreme Programming (XP) principle suggests developers should only implement functionality that is needed for the immediate requirements, and avoid attempts to predict the future by implementing functionality that might be needed later.
Adhering to this principle should reduce the amount of unused code in the codebase, and avoid time and effort being wasted on functionality that brings no value.
See also:
The Fallacies of Distributed Computing on Wikipedia
Also known as Fallacies of Networked Computing, the Fallacies are a list of conjectures (or beliefs) about distributed computing, which can lead to failures in software development. The assumptions are:
- The network is reliable
- Latency is zero
- Bandwidth is infinite
- The network is secure
- Topology doesn't change
- There is one administrator
- Transport cost is zero
- The network is homogeneous
The first four items were listed by Bill Joy and Tom Lyon around 1991 and first classified by James Gosling as the "Fallacies of Networked Computing". L. Peter Deutsch added the 5th, 6th and 7th fallacies. In the late 90's Gosling added the 8th fallacy.
The group were inspired by what was happening at the time inside Sun Microsystems.
These fallacies should be considered carefully when designing code which is resilient; assuming any of these fallacies can lead to flawed logic which fails to deal with the realities and complexities of distributed systems.
See also:
- Foraging for the Fallacies of Distributed Computing (Part 1) - Vaidehi Joshi on Medium
- Deutsch's Fallacies, 10 Years After
If you have found these concepts interesting, you may enjoy the following books.
- Extreme Programming Installed - Ron Jeffries, Ann Anderson, Chet Hendrikson - Covers the core principles of Extreme Programming.
- The Mythical Man Month - Frederick P. Brooks Jr. - A classic volume on software engineering. Brooks' Law is a central theme of the book.
- Gödel, Escher, Bach: An Eternal Golden Braid - Douglas R. Hofstadter. - This book is difficult to classify. Hofstadter's Law is from the book.
- The Dilbert Principle - Scott Adams - A comic look at corporate America, from the author who created the Dilbert Principle.
- The Peter Principle - Lawrence J. Peter - Another comic look at the challenges of larger organisations and people management, the source of The Peter Principle.
Thanks to a number of wonderful contributors, Hacker Laws is available in a number of languages. Please consider sponsoring moderators!
Language | Moderator | Status |
---|---|---|
🇧🇷 Brasileiro / Brazilian | Leonardo Costa | |
🇨🇳 中文 / Chinese | Steve Xu | Partially complete |
🇩🇪 Deutsch / German | Vikto | |
🇫🇷 Français / French | Kevin Bockelandt | |
🇬🇷 ελληνικά / Greek | Panagiotis Gourgaris | |
🇮🇹 Italiano / Italian | Claudio Sparpaglione | Partially complete |
🇰🇷 한국어 / Korean | Doughnut | Partially complete |
🇱🇻 Latviešu Valoda / Latvian | Arturs Jansons | |
🇷🇺 Русская версия / Russian | Alena Batitskaya | Partially complete |
🇪🇸 Castellano / Spanish | Manuel Rubio (Sponsor) | Partially complete |
🇹🇷 Türkçe / Turkish | Umut Işık |
If you would like to update a translation, just open a pull request. If you want to add a new language, log onto GitLocalize to create an account, then open an issue asking to administer the language and I will add you to the project! It would also be super helpful if you can open a pull request which updates the table above and link at the top of the file.
- Tip of the Day - Receive a daily hacker law/principle.
- Hacker Laws CLI - List, view and see random laws from the terminal!
Por favor, contribua! Abra uma issue se você deseja ver aqui algum conteúdo novo, sugerir uma alteração/correção, ou então abra uma pull request e proponha suas próprias modificações.
Certifique-se de ler as Diretrizes de Contribuição para saber sobre os padrões de texto, estilo etc. Esteja ciente do Código de Conduta ao participar de discussões sobre o projeto.
Olá! Se você parou aqui, clicou em um link para um tópico que não foi escrito ainda. Desculpe por isso, este trabalho está em andamento!
Sinta-se livre para abrir uma issue solicitando mais detalhes, ou abra uma pull request para submeter suas modificações.