DEV Community

Adithr123
Adithr123

Posted on

Simplifying code

Hello! I am 13 years old, and i was wondering if someone could help me. I have writen a program in python, but it is 267 lines long, and it is mostly repeated code. Github link - https://github.com/Adithr123/pizza

Top comments (3)

Collapse
 
mykezero profile image
Mykezero

I'm not a python programmer, but you might benefit from creating a class to hold all of your language messages. This may not shorten you code, but will allow you to move the messages out of the main python file and into another one.

There is a lot going on here, but these are the features of python I am using for reference:

The approach here is to centralize your messages into a single spot and allow easy access to the messages without too much code.

What I've essentially have created is a dictionary for each languages messages:

english = dict(
    Welcome="Welcome to Adith Pizzeria\n",
    OrderName="What would you like your order name to be? ",
)
Enter fullscreen mode Exit fullscreen mode

The dictionary data structure holds keys and values. In this case, it is holding the message name: Welcome and its value: "Welcome to Adith Pizzeria\n" . We can get the message from the dictionary by indexing into it by key:

english["Welcome"]
Enter fullscreen mode Exit fullscreen mode

I've created an enum for the AvailableLanguages that contains one value per language that you are supporting in your application:

class AvailableLanguages(Enum):
    English = 1,
    Spanish = 2
Enter fullscreen mode Exit fullscreen mode

Now, this is where things get tricky. We are going to use a design pattern called the factory method pattern to get the language dictionary for the given user selected language. We are using the class Languages with a static method on it called "get" that will take an enum value of either English or Spanish, and it will return the corresponding language dictionary

# Create a class to get the specified language by AvailableLanguage enum value
class Languages:
    @staticmethod
    def get(language):
        if language == AvailableLanguages.English.name:
            return english
        if language == AvailableLanguages.Spanish.name:
            return spanish
        raise Exception("Language is not defined")
Enter fullscreen mode Exit fullscreen mode

I tried to figure out how to convert your user input which is either a "1" or a "2" to an enum value, but couldn't find a quick answer, so I'll leave that up to you to find for now.

Now, we create a Messages class that has a constructor that takes an AvailableLanguage enum value and has a single method get that takes a string parameter called key. The key will match the keys defined in both the Spanish and English dictionaries like "Welcome".

# Create a messages class to get the specific message for a given language.
class Messages:
    def __init__(self, language):
        self.language = Languages.get(language)

    def get(self, key):
        return self.language[key]
Enter fullscreen mode Exit fullscreen mode

By initializing Messages with the correct AvailableLanguage enum value in the beginning, then we can simply call get with the key "Welcome" to get the welcome message for the language:

messages = Messages(AvailableLanguages.English)
print(messages.get("Welcome"))
Enter fullscreen mode Exit fullscreen mode

That should finally print the text: "Welcome to Adith Pizzeria\n". With that in place, you could move all of your messages out of the main.py file and put they maybe in a messages.py file to centralize the language messages.

I know what I've wrote here is a bit confusing, but hopefully it gives you an idea about some other features of the python language you can use like dictionaries, enums, classes and static methods (decorators).

If I have some more free time this weekend, I might try to convert the whole program to show you a different way that I might handle some of the program aspects. But I hope this helps in some way! ^^

Full Code:

# Import ability to use enums
from enum import Enum

# Create a dictionary for each language, with each message translation inside
english = dict(
    Welcome="Welcome to Adith Pizzeria\n",
    OrderName="What would you like your order name to be? ",
)
spanish = dict(
    Welcome="Bienvenidos a Adith Pizzeria.\n",
    OrderName="Qual es tu nombre? "
)


# Create an enum to hold the available languages in the program
class AvailableLanguages(Enum):
    English = 1,
    Spanish = 2


# Create a class to get the specified language by AvailableLanguage enum value
class Languages:
    @staticmethod
    def get(language):
        if language == AvailableLanguages.English:
            return english
        if language == AvailableLanguages.Spanish:
            return spanish
        raise Exception("Language is not defined")


# Create a messages class to get the specific message for a given language.
class Messages:
    def __init__(self, language):
        self.language = Languages.get(language)

    def get(self, key):
        return self.language[key]


# Creates an instance of the Messages class, asking it for only english messages
messages = Messages(AvailableLanguages.English)

# Prints out the english version of the welcome message
print(messages.get("Welcome"))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
avdol profile image
Adithr123

Thank you, i will try to fully impliment it in my code.

Collapse
 
mykezero profile image
Mykezero

Awesome! I will also do a refactoring of the whole program. Definitely let me know if you have questions about the implementation and when I convert the whole program, definitely ask why I have written something a specific way. Programming is almost like an art: everyone balances the programming statements a different way.

I've written the code to separate English from Spanish because the main program module does not care which language is used, but cares that we communicate the menu with our customer. So from that perspective, that is why I have separated it out. If you wanted to support Japanese next, we might ask someone for a new translation for that. Then, all we'd need to create is a new dictionary for Japanese and only add a new enum entry and a new dictionary. We are gaining maintainability by separating the languages out of the main module. Which is why I said it may not shorten the code, but we are trading for maintainability.

Hopefully after the refactor we can have someone python wise comment how to improve further and why!