'Dividing classes into smaller ones C++
I've recently created a program that handles and manipulates images and converts them into ASCII versions. I put all of the code in one class, properly divided into functions. I organized the functions into groups (functions operating on the file, filters, image rotation, etc.).
And here is my question. How to separate these particular groups, so that all of this code does not sit in one class, but is more organized? I was thinking about a solution where I would extract the code into auxiliary classes, create the appropriate sub-objects in the main class, and access functions as follows:
//main object (containing all of the picture info)
Image img("image.jpg");
img.filters.changeToGrayscale(); // filters, that is sub-object
// containing "filter" functions
But I don't know if this is the optimal solution. Maybe some advice from more experienced coders? :P
EDIT: I know that I should divide it, but how to do it in c++?
If I want those smaller classes have access to members of the main class, I would have to mark them as friend classes and send main object instance to them to be able to do that. And idk if that is the best way of doing it.
Here is the code if you're interested: github Ascii Generator
Solution 1:[1]
I think you already prepared your Image class to be divided into smaller classes. It is necessary to make one small class which will have just one responsibilty. E.g. Filter class
will just apply filters for your image, File class will be responsible just for managing file. Position class will be responisble just for flipping.
After doing this, your classes will correspond to the single responsibility principle of SOLID. Read more about single responsibility principle of SOLID here.
Sketch of your classes:
API of ImagePosition class would have methods:
void flipX();
void flipY();
void flipRight();
API of FileManager class would have:
void writeImageData(const char* filename);
void readImageData(const char* filename);
void printOperationStatus(bool isOperationSuccessfull,
const char* filename, std::string operationName);
API of Filter class would have:
void grayscaleAvg();
void grayscaleLum();
void colorMask(float R, float G, float B);
API of ASCII class would have:
void printAscii();
void printAscii(std::string resultTextName);
API of ImageHelper class would have:
ImageType getFileType(const char* filename);
std::vector <Pixel> formatToPixels(uint8_t* data);
uint8_t* formatToUint8(std::vector <Pixel>& pixels);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | StepUp |
