1. 程式人生 > >The Strictness Principle

The Strictness Principle

Pretty often in software engineering, people end up in situations where there are several pieces of functionality in which the integration between those pieces become harder to reason about. One example is when the developer is reading a piece of functionality that is dependent on a specific scope, and that scope is shared amongst several parts of the system.

There are several principles that indicate how components should behave to be maintainable (SOLID, DRY, Atomic Commits, etc.). It all works, despite the programming paradigm that is being used.

However, there is one that is used quite often, but seems to stay (ironically) restricted to certain communities and languages as standard best practices instead of being defined as a general principle that can be applied almost anywhere:

Restrict the scope of what you do. Increase the scope as the need arises.

This means that, if there is a given component that doesn't need knowledge of an outer scope, one should always start writing by default with a restricted scope, then expose to other scopes as necessary, even if the defaults of the language or framework are different.

If the functionality is not exposed, then it's less likely to be used for a purpose different from the one it was intended to. Also, there is no need to speculate about the conditions in which the functionality might be used in another scope.

Below are some examples of best practices that exist inside specific communities:

Java

In Java (and many other similar languages), there are access modifiers that change the visibility of the members in a class. When starting to write a class or the members of it, there is no need to know if that functionality should be exposed or not. By default, the developer should always use the private modifier, which represents the maximum access restriction in Java. In this case, if the need arises, one can increase the visibility scope for that class or method, so that it can be used outside its initial strict scope.

A code example showing the use of the "private" modifier in Java

Another example is the final modifier. Even though it doesn't care about the visibility of the member, it restricts the binding. If used in a class, it prevents to be subclassed. If used in a variable, it prevents the reference to be changed, ensuring the binding is consistent, even in a multi-thread environment. Because of that, one should always use the final modifier by default in all declarations.

A code example showing the use of the "final" modifier in Java

One could argue that classes should be open for extension but closed for modification, so it might not make sense creating everything with a reduced scope by default in Java. If one wants to make the class extensible, though, then it might be reasonable to increase the strictness a little bit. However, this is a smell that encourages the author to consider using other forms of class extension instead of inheritance (like composition or prototypal inheritance using the prototype pattern).

JavaScript

JavaScript is not (as from May 2016) as robust as Java for handling visibility access. It requires a lot of Duck Typing and inferences. Still, it does have some features that could leverage the Strictness Principle, and they are very well documented in the community.

For example, it's impossible to create in pre-ES2015 something that is block scoped, therefore it’s necessary to use a closure so that everything inside will not be accessible outside the scope. This capability gave birth to a pattern called Revealing Module, which uses an IIFE (Immediately-Invoked Function Expression) as the engine for its execution. In this case, one should restrict the variables by default unless they are required to be exposed into the parent scope.

A code example showing the Revealing Module pattern in JavaScript

In JavaScript, ES2015 and beyond, it's possible to use the constmodifierwhich, besides being block scoped (like let), it also prevents the variable binding to be changed. Similar to Java's final modifier.

Again, it's recommended to use const by default due to its strict properties, unless there is an additional need for rebinding (like the punch variable shown below).

A code example showing the use of the "const" modifier in JavaScript

Angular

This principle doesn't apply only to languages, but also to frameworks.

Angular has something called isolated scope for directives. By default, all directives will share the scope of the parent, but that can cause unintended consequences because the directive can use by mistake something that is declared in the parent scope and break when moved to somewhere else. If the isolated scope is used by default instead, then the directive will create a new scope that will only be accessible through the attributes that should be passed explicitly from wherever the directive is in the HTML template.

The best practice here is: Use isolated scope for directives by default unless there is a good reason not do to so. Be careful, though, using by default doesn't mean using it blindly.

An HTML example showing a pagination component containing a single "page" component
A code example showing the pagination component controller using an isolated scope to pass some information

As you probably realized, this principle doesn't limit itself to technical issues. It can also be applied in other contexts where there is a definition of scope:

  • The scope of a project regarding the proposal of new features, which should be restricted by default unless there is a good reason to tackle problems outside that scope.
  • Discussions that should be restricted to a specific topic unless there is a need to increase the scope of the conversation.

Never start something with low strictness by default, even if your tool, language, framework or context allows that. Always try to be as strict as possible in order to prevent unintended side effects and keep the focus on what is important.

相關推薦

The Strictness Principle

Pretty often in software engineering, people end up in situations where there are several pieces of functionality in which the integration between those pi

the Principle of Trading

如何 發現 一起 盈利 能力 使用 不明確 構造 歷史 0 澄清事件有兩種辦法,學和思。也就是看別人的想法,和自己琢磨琢磨。本文是第二種途徑的實踐。 我打算寫一系列關於交易的文章,目的是澄清相關的事實,梳理並構造體系。達到的狀態是,其他所有交易相關的知識和信息,都可以在這個

some understanding of《Inferring Decision Trees Using the Minimum Description Length Principle*》

《Inferring Decision Trees Using the Minimum Description Length Principle*》 Information And Computation 80, 227-248(1989) My difficulty is: how

開放-封閉原則(The Open-Closed Principle 、OCP)

一、概念 軟體實體(模組、類、函式等)應該可以擴充套件,但是不可以修改。也就是說軟體對擴充套件開放,對修改封閉。 需要說明的是,對修改關閉不是說軟體設計不能做修改,只是儘量不要做不必要的修改。怎麼才能做到呢?那就是有相應的擴充套件性。其實,軟體有相應的擴充套件性是好處,但是不能說每個地方

Making the Most of Polymorphism with the Liskov Substitution Principle

The Liskov Substitution PrincipleIn object-oriented design, a common technique of creating objects with like behavior is the use of super- and sub-types. A

Maintainable Code and the Open-Closed Principle

The Open Closed PrincipleRobert C. Martin, creator and chief evangelist of SOLID, credits Bertrand Meyer as the originator of the OCP. In his 1988 book Obj

Avoiding Interface Pollution with the Interface Segregation Principle

The Interface Segregation PrincipleAs we discussed in our review of the Open/Closed Principle, interfaces are a means of programming with abstractions rath

Effective Program Structuring with the Dependency Inversion Principle

The Dependency Inversion PrincipleAt its heart, the DIP is about structure. The manner in which you structure your program entities, and the way in which t

OO設計原則 — The Open-Closed Principle:開放/封閉原則(OCP)

對於一個軟體的實體(類,模組,函式等)應該是可以擴充套件的,但是不可被修改。 一、概要 開放/封閉原則(The Open-Closed Principle:OCP)是在面向物件設計中,類和模組等必須遵循以下規則: ◇ 對於功能的擴充套件因該是開放的,即可以追加

[CSS] Showing horizontal scrollbar always for the table

nbsp overflow tab spl spa horizon clas pre idt table { display: block; overflow: scroll; width: 200px; height:95vh;

[LeetCode] Reshape the Matrix 矩陣重塑

ren ati num 我們 資料 call posit tar led In MATLAB, there is a very useful function called ‘reshape‘, which can reshape a matrix into a ne

ZOJ - 3228 Searching the String (AC自己主動機)

won key wid roc lap processor som multiple pla Description Little jay really hates to deal with string. But moondy likes it very mu

SQL Server導入報錯:The LocaleID 4 is not installed on this system

code page localeid 936 問題描述:通過SQLServer導入導出向導導入中文字符集數據,遇到The LocaleID 4 is not installed on this system.錯誤。解決方法:我發現客戶服務器操作系統雖然不支持Chinese (Simplified)

HDU 4930 Fighting the Landlords(扯淡模擬題)

href blank 。。 clear break 輸出 family fig set Fighting the Landlords 大意: 鬥地主。。。。 分別給出兩把手牌,肯定都合法。每張牌大小順序是Y (i.e. colored Joker) &g

Principle of Computing (Python)學習筆記(7) DFS Search + Tic Tac Toe use MiniMax Stratedy

ide out generate depth sku color ati cond with 1. Trees Tree is a recursive structure. 1.1 math nodes https://class.coursera.org/prin

The connection to adb is down, and a severe error has occured

真的 findstr ole pla a10 tool fcm ott art 相信不少人在android中都遇到了你下面不好解決的問題: 首先描寫敘述癥狀,例如以下圖 解決方法: 方法1:先在cmd中adb kill-server,然後adb -startser

HDOJ4355-Party All the Time(三分)

input arc cat ans 5.1 sea nim res stat Problem Description In the Dark forest, there is a Fairy kingdom where all the spirits will go to

HDOJ2438:Turn the corner(計算幾何 + 三分)

scan can 計算 closed 4.5 pri cross cli idt Problem Description Mr. West bought a new car! So he is travelling around the city.One day he c

F - Find The Bone

.com col unit table 輸入 mce 每次 move each F - Find The Bone Zane the wizard is going to perform a magic show shuffling the cups. There are

[SCSS] Write similar classes with the SCSS @for Control Directive

att oop enc rem coo tro from mil for Writing similar classes with minor variations, like utility classes, can be a pain to write and upda