N
N
Nikita Gusakov2013-01-19 17:03:11
Programming
Nikita Gusakov, 2013-01-19 17:03:11

What is the correct way to write functions with the get prefix?

Let's say we have a class, one of its methods is getting the contents of a file, the function is private, which means you can only save it to an object, two implementations arise - using return or immediately writing to the class field. Which option is better and why?
PS getting the contents of a file is just an example.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
serso, 2013-01-19
@hell0w0rd

It is not very clear what kind of object it is. Let's say our object is an application class. When you open an additional window, you need to read a large file, such as a CSV table. At the same time, it is clear that this file does not need to be loaded when the application starts (because the additional window may not be open), but if we read it at least once, we don’t want to read it a second time. In this case, you can use the lazy loading pattern:

public class Application {

    private CsvData csvData = null;

    public CsvData getCsvData() {
        if ( csvData == null ) {
            csvData = readCsvData();
        }
        return csvData;
    }

    private CsvData readCsvData() {
        // read file from the disk, do not forget about synchronization
        // ...
        return csvData;
    }
}

X
xanep, 2013-01-19
@xanep

Your approach to development is turned inside out. The development chain is: requirements->architecture->implementation. You are trying to figure out from the implementation how "correctly". This is fundamentally impossible. Correct as it satisfies the requirements. And there are no requirements. Therefore, you first need to decide on the requirements for the class interface, and then make the implementation (well, private methods are nothing more than a way to implement the interface).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question