Use strings in a clean way!

By the title of this post, you might already know what I’m going to tell you today. You might think that using strings in code might not be that harmful to your project but believe me, it will.

Why?

Each advice you get should start with the question “why?”. So let me explain why you should care about using strings in your code in a proper way! ?

The first of all, you shouldn’t hardcode values in your code in the first place! Of course, this is not always possible, but the programmer should always strive for greatness. ?

When using a lot of strings in your code, it’s starting to get messy. You have to remember where you put specific text, and if you are using the same strings in multiple places, then you have a problem. Especially when you want to make some changes… ?

Solution?

If you are following my blog, you might already seen how I’m handling strings in my code. If not, then you can check it in posts about Singletons, Localization and REST API.
In the first two posts, I’ve created const variables as I don’t want to change these values at any point.

public class UsageExample : MonoBehaviour
{
    // Key to store data.
    private const string SAVE_KEY = "Secret Info";

    // More code at: https://bitbucket.org/gaello/singletons/src/master/Assets/Scripts/Usage/UsageExample.cs
}
public class LocalizationManager : PersistentLazySingleton<LocalizationManager>
{
    // Path to translation file inside Resource folder
    private const string TRANSLATION_FILE_PATH = "translations";

    // More code at: https://bitbucket.org/gaello/localization/src/master/Assets/Scripts/Localization/LocalizationManager.cs

}

But in case of REST API, I stepped it up and created a separate ServerConfig class that stores string variables that I’m later using in my ServerCommunication class.

/// <summary>
/// This class store server config keys and urls.
/// </summary>
public class ServerConfig
{
    // URL with place to put API method in it.
    public const string SERVER_API_URL_FORMAT = "http://www.mocky.io/v2/{0}";

    // Mocky generates random strings for your endpoints, you should name them properly!
    public const string API_GET_QUOTE = "5cb15fdf330000ee1557204f";
    public const string API_GET_BLOG_INFO = "5cb28ba13000007b00a78c92";
}

That approach makes your code cleaner, and you have fewer opportunities to mess it up! Especially when you have to use the same string in multiple places!

Hope you enjoy this little tip and hope to see you on next post!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x