How much responsibility should a method have?

This is, of course, a linguistic agnostic question and one that has bothered me for quite some time. An example will probably help me explain the dilemma I have encountered:

Let's say we have a method that is responsible for reading a file, filling the collection with some objects (which store information from the file), and then returning the collection ... something like the following:

public List<SomeObject> loadConfiguration(String filename);

Let's also say that during the implementation of this method, it would seem unacceptable to continue the application if the returned collection was empty (size 0). Now the question is, should this check (check for an empty collection and, possibly, throw an exception later) within the framework of the method? Or, if it is solely responsible for executing the file download and ignoring the verification task, allowing you to do the verification at some later stage outside the method?

I assume that the general question is: is it better to separate the check from the actual task performed by the method? Whether it can simplify a change or build at a later stage - in the case of my example above, it can be at a later stage, when another strategy is added to recover from an empty event, the collection is returned from the loadConfiguration method ..... it would be difficult, if the method were checking (and the resulting exception).

Maybe I'm too pedantic looking for some kind of dogmatic answer, where instead he just relies on the context in which the method is used. In any case, I would be very interested to know what others can say about it.

Thanks everyone!

+3
source share
8

- , , 1 . 3 , 4, .

, .

  • LoadConfig

  • .

  • .

  • .

  • .

1 4 3 . .

,

+7

, : , ?

. ( , - .) , , . . , , , API, , . , .

+4

, . , , , , , , . , , .

   private byte[] ReadFile(string fileSpec)
   {  
       // code to read in file, and return contents
   }
   private FileData GetFileData(string fileContents)
   {
       // code to create FileData struct from file contents
   }
   private void FileDataCollection: Collection<FileData> { }

   public void DoItAll (string fileSpec, FileDataCollection filDtaCol)
   {
        filDtaCol.Add(GetFileData(ReadFile(fileSpec)));
   } 

, ,

+2

: ?

, "": void, "init"... !

, : Fail Fast, , , , ....

, : 3 , ? (load, parse, validate) , DRY.

, :

  • : (1)
  • , (, "check" , , , )

(1) , , ... : :)

+2

API . , , .

, , , , . , , . loadConfiguration , , , .

. , ? URL-, , ? , , . . , - , - , ConfigurationReader .

+2

... . , , . ... , ... 1,5 .

0

, : , , , , . , , , , ( , , ...), .

0

, , Injection Dependency, . "" , , , ( Fail Fast - ).

, , , , .

0

Source: https://habr.com/ru/post/1720490/


All Articles