CeejeeB
CeejeeB

Reputation: 3114

How to Connect Logic with Objects

I have a system that contains x number of strings. These string are shown in a UI based on some logic. For example string number 1 should only show if the current time is past midday and string 3 only shows if a randomly generated number between 0-1 is less than 0.5.

How would be the best way to model this?

Should the logic just be in code and be linked to a string by some sort or ID?

Should the logic be some how stored with the strings?

NOTE The above is a theoretical example before people start questioning my logic.

Upvotes: 0

Views: 53

Answers (1)

9000
9000

Reputation: 40894

It's usually better to keep resources (such as strings) separate from logic. So referring strings by IDs is a good idea.

It seems that you have a bunch of rules which you have to link to the display of strings. I'd keep all three as separate entities: rules, strings, and the linking between them.

An illustration in Python, necessarily simplified:

STRINGS = {
  'morning': 'Good morning',
  'afternoon': 'Good afternoon',
  'luck': 'you must be lucky today',
}

# predicates

import datetime, random

def showMorning():
  return datetime.datetime.now().hour < 12

def showAfternoon():
  return datetime.datetime.now().hour >= 12

def showLuck():
  return random.random() > 0.5

# interconnection

RULES = {
  'morning': showMorning,
  'afternoon': showAfternoon,
  'luck': showLuck, 
}

# usage
for string_id, predicate in RULES.items():
  if predicate():
    print STRINGS[string_id]

Upvotes: 1

Related Questions