Improving code for counting things

Progress.

I have now managed to chart mood_types. Although this seems extremely convoluted. Any possible suggestions for improving the code would be very gratefully received.

I don’t seem to be using any server code at all (I didn’t understand the multi-row furniture example above).

   

#this get me a happy counts variable...
    happy_counts = app_tables.mood_types_table.get(mood_types="happy")   
    happy_notes = app_tables.mood_journal.search(mood_types=happy_counts)
    hppy = len(happy_notes)    

    #neutral
    neutral_counts = app_tables.mood_types_table.get(mood_types="neutral")   
    neutral_notes = app_tables.mood_journal.search(mood_types=neutral_counts)
    ntrl = len(neutral_notes)    

    #sad
    sad_counts = app_tables.mood_types_table.get(mood_types="sad")   
    sad_notes = app_tables.mood_journal.search(mood_types=sad_counts)
    sd = len(sad_notes)    

    #desperate
    desperate_counts = app_tables.mood_types_table.get(mood_types="desperate")   
    desperate_notes = app_tables.mood_journal.search(mood_types=desperate_counts)
    dsprt = len(neutral_notes)    

    #this plots the 4 moods
    self.plot_mood_counts.data = go.Bar(y=[hppy,ntrl,dsprt,sd])    

One code improvement you might make is based on the DRY principle (don’t repeat yourself).
If you find you are writing the same code several times it’s probably time to abstract the logic into a separate procedure

Something like:


def get_mood_counts(*moods):
    mood_counts = []
    for mood in moods:
        counts = app_tables.mood_types_table.get(mood_types=mood)
        notes = app_tables.mood_journal.search(mood_types=counts)
        mood_counts.append(len(notes))
    return mood_counts

mood_counts = get_mood_counts('happy', 'sad', 'neutral', 'desperate')

self.plot_mood_counts.data = go.Bar(y=mood_counts)    

Then there’s efficiency - I’d definitely look to move these to a server function since the way your code is set up, you are unintentionally making a server call for each database search query (i.e. 8 round trips to the server)

# In a server module
@anvil.server.callable
def get_mood_counts(*moods):
    ... # as above


# on the client
mood_counts = anvil.server.call('get_mood_counts', 'happy', 'sad', 'neutral', 'desperate')

Now it’s only 1 intentional server call.

4 Likes

Great. Thanks @stucork