1

I am creating a program, and I would like to know the best practice for creating a class which defines different fuel types

For instance, I have the following class that I have written in python:

class Fuel():
    def __init__(self, fuel_type, energy_density):
        self.fuel_type = fuel_type
        self.energy_density = energy_density

    def energy_output():
        return energy_density*100

The fuel types can be gas, coal or oil, with energy densities of 35.7, 24.0 and 43.37 respectively.

These numbers won't change when used in the future. However, somebody may wish to add an additional fuel type through a data file.

I thought that maybe inheritance could work, by defining a sub-class for each fuel type, with the energy densities pre-defined. But this would create a number of different classes that weren't very different, and it would be more difficult for users to add a new fuel type.

Any help on best practice would be greatly appreciated.

  • 2
    What exactly are your concerns? When you say a "user" do you mean an end-user of the application, or a developer who's using your code as a module in their application? – user1118321 Sep 6 '18 at 16:29
  • Thank you for your question. It is for a developer who's using my code as a module in their application. – AKE Sep 6 '18 at 16:40
2

If all instances are known at compile time (yours or the consuming developer ones), you should create your well known examples as globally known instances or offer static factory methods for them somewhere (in particular if your objects are mutable).

Usually you achieve this by creating a class like Fuels and adding N static read-only properties to it which are initialized with your examples - or by adding N static methods each of which creates one of the examples.

Your consuming developers are free to define their own well known values somewhere else in the same way.

This is the static way (registration in code).

If in contrast those instances (and the new ones) depend on data only known at runtime, you may create a FuelRegistry to register provided objects and receive them by their name (maybe fuel type). That registry may get persisted or just be in-memory.

You can combine these approaches by adding code which prefills your registry with your standard instances.

This is the dynamic way.

  • 1
    Thank you for your help. This explains the two options well. – AKE Sep 6 '18 at 21:50
  • 1
    AKE: If you think the correct answer to your question has been given, please mark it as such by clicking the checkmark next to it. – Hero Wanders Sep 7 '18 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.