Skip to content

Instantly share code, notes, and snippets.

@justinfx
Created December 27, 2011 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinfx/1522860 to your computer and use it in GitHub Desktop.
Save justinfx/1522860 to your computer and use it in GitHub Desktop.
An alternative to doing switches in OOP
#!/usr/bin/env python
"""
Based on the this SO question:
http://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code
Ways to use object oriented programming to create interfaces
instead of using switch patterns like:
if
elif
elif
...
else
The main logic does not contain any knowledge of what to do with different
cases. Its up to the implementations to handle the actions through a common
interface.
Justin Israel
justinisrael@gmail.com
justinfx.com
"""
import os
import sys
class AbstractInterface(object):
"""
AbstractInterface
This class is meant to be subclasses, and not
used directly. Subclasses should impliment the
methods of this class.
"""
def getFullPath(self, afile):
pass
def numThreads(self):
pass
class Posix(AbstractInterface):
"""
Implements the AbstractInterface for Posix systems
"""
def getFullPath(self, aFile):
return os.path.join( "/home/blah/food", aFile)
def numThreads(self):
# call out to the filesystem with specific
# posix commands to determine how many cpus
# or threads?
return 8
class Nt(AbstractInterface):
"""
Implements the AbstractInterface for Nt systems
"""
def getFullPath(self, aFile):
return os.path.join(r'Z:\path\to\root', aFile)
def numThreads(self):
# call out to the filesystem with specific
# posix commands to determine how many cpus
# or threads?
return 2
def main():
systems = {
'nt': Nt(),
'posix': Posix()
}
try:
system = systems[os.name]
except KeyError:
print "System not supported!"
sys.exit(1)
print system.getFullPath('myFile.txt')
print system.numThreads()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment