What are "code units"?

12

I want to know what code units mean?

I saw this term in an answer here in SOpt and I was in doubt.

  

Code units should be short and have only one responsibility.

Question link where I saw the term > > What defines clean code ?

    
asked by anonymous 28.06.2017 / 18:59

3 answers

13
  

The word unit comes from the Latin term unitas and designates the quality of what is unique or indivisible . It means what is considered individually rather than plural.

The physical boundaries of a unit of code are abstract concepts and vary according to context. It can be a line of code, it can be a group of them, a function, a class, or an entire project. You can not define exactly where a unit of code begins and ends. But what was said in the quoted answer is that each unit of code must have one, and only one, responsibility. It is said unit, in the concept of indivisible, as I mentioned above, because the implemented logic, indifferent to the number of lines of code, performs only a very well defined task.

As an example you can consider a class implementation. You can have get / set methods of properties, as well as methods of validating the values. It would be possible to implement the validation logic within the set method, but if within any other method you need to validate the value again, you need to replicate the validation logic or use the set method. Not always the second option is indicated, because it can leave the code little semantic (to understand: you need to validate a value, but it uses its respective setter ). The ideal is to have the method only for validation and, within the set method, invoke it to validate the value. Division of responsibilities for different units of code (in this case, methods).

    
28.06.2017 / 19:20
10

There it was purposely left vacant.

Probably the smallest unit of code is function , but I have doubts without no exceptions, maybe a lambda that is practically a function.

It is also a structure, a class, a module , a font file. Each one with its level of influence and with what should be its responsibility. Usually one goes inside the other.

function - > class - > module or source file

    
28.06.2017 / 19:19
10

Code units are the ways that statements can be grouped. This helps in organizing and deploying / integrating a project. Some examples are functions, 'modules', classes.

The term indicates the granularity of a 'snippet', as well as (we classify) the units of measurements: km, m, cm, and mm. The software has them respectively.

    
28.06.2017 / 19:19