Code: Select all
int function ( const int input )
{
return input * 2; // output
}
Code: Select all
std::string global_string;
void function_that_sets_the_global_string ( )
{
global_string = "String set!";
}
int function_that_isnt_supposed_to_set_the_global_string ( )
{
global_string = "I set it anyway! MUHAHAHAHAHAHAHAHAHAH!";
return 0;
}
void function_that_relies_on_the_global_string_being_set ( const int some_value )
{
if ( global_string != "String set!" )
{
throw std::wtf_bro { };
}
}
void run ( )
{
function_that_sets_the_global_string ( );
int some_value = function_that_isnt_supposed_to_set_the_global_string ( );
function_that_relies_on_the_global_string_being_set ( some_value );
}
Code: Select all
void do_not_do_this ( char* buffer )
{
char set_string [] = "String set!";
std::memcpy ( buffer, set_string, sizeof ( set_string ) );
}
std::string do_this_instead ( )
{
return "String set!";
}
There are situations where large objects are hard to manage with pure functions.
Code: Select all
std::vector<int> sort ( const std::vector<int>& input )
{
std::vector<int> output;
//Sort input into output
return output;
}
std::vector<int> input;
std::vector<int> sorted_input = sort ( input );
Code: Select all
void sort ( std::vector<int>& input )
{
//Sort input in place
}
std::vector<int> input;
sort ( input );
Code: Select all
std::vector<int> sort ( std::vector input )
{
//Sort input in place
return input; // return input as output
}
std::vector<int> input;
std::vector<int> sorted_input = sort ( std::move ( input ) );
Course, you can't make a program entirely with pure functions. Eventually, somebody needs to take the output that the pure function gave and show it to the outside world.
Code: Select all
auto output = some_func ( );
std::cout << "The output:" << output << '\n'; // Show our output to the world!
Code: Select all
void print_grade ( const std::string& name, const std::vector<student_type>& list_of_students )
{
for ( std::size_t index = 0; index < list_of_students.size ( ); ++i )
{
if ( list_of_students [ index ].name == name )
{
std::cout << "Grade: " << list_of_students [ index ].grade << '\n';
}
}
throw out_of_range { };
}
Code: Select all
std::size_t find_student_index ( const std::string& name, const std::vector<std::string>& list_of_students )
{
for ( std::size_t index = 0; index < list_of_students.size ( ); ++i )
{
if ( list_of_students [ index ].name == name )
{
return index;
}
}
throw out_of_range { };
}
void print_grade ( const std::string& name, const std::vector<std::string>& list_of_students )
{
std::size_t index = find_student_index ( name, list_of_students );
std::cout << "Grade: " << list_of_students [ index ].grade << '\n';
}
Programming like this takes some time to get used to but once you do, you'll thank yourself for putting in the effort. It's the best way of creating simple code that's very easy to test and debug!