Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format my class? With toString, in the GUI or in other way?

I have some classes in a library that are representing analysis and validation results of some files.

These classes contains enums, Lists of invalid properties, etc.

I wrote a GUI application that uses the library, and wrote some functions for writing those classes in readable form in a rich text box.

It just occured to me, that I may have to write this formatting in a ToString overriding of the class.

However, all this formatting is very long, includes inserting tabs and new lines, includes several iteration over the lists, extracting enum description etc.

So I was wondering - what is the standart for toString size and complexity? Am I suppose to write difficult formatting in the toString? Or maybe I should provide some other common interface- is there any common interface for a formatted printable output of a class? Or shall I do it in the GUI application?

Thanks!

like image 209
sara Avatar asked Dec 07 '25 03:12

sara


1 Answers

Stuff like UI formatting shouldn't be baked into any library except UI libraries.

Instead what you could do is provide a UI agnostic set of classes that can format your entities, as in, can do the complex code necessary to produce a format with the expectation of being displayed in a UI.

These could use a simple interface, something like:

public interface IEntityFormatter<T>
{
    string GetFormattedValue(T myEntity);
}

public class Customer
{
    public string FullName {get;set;}
}

public class CustomerFormatter : IEntityFormatter<Customer>
{
    public string GetFormattedValue(Customer myEntity)
    {
        return myEntity.FullName;
    }
}
like image 88
Adam Houldsworth Avatar answered Dec 08 '25 18:12

Adam Houldsworth