should have only one reason to change Alternately: Things that change for the same reasons should be together. Things that change for different reasons should be kept apart.
of a person who controls or uses it Any module should be responsible to only one person (or role) Consider, how to build code such that changes requested by different roles do not break or change code written for a different role e.g. Changing page layout should not impact Business Rules about valid data
with open('/etc/passwd', 'r') as input: for line in input.readlines(): if not line.startswith('#'): parts = line.split(':') struct = { 'login_name': parts[0], 'password': parts[1], 'uid': parts[2], 'gid': parts[3], 'user_name': parts[4], 'home_dir': parts[5], 'shell': parts[6] } db.write(struct)
self.transformer = Transformer() self.writer = DB() def load_data(self): for record in self.loader.load_file('/etc/passwd'): self.writer.write(self.transformer.transform(record)) class FileLoader: def load_file(self, filename): with open(filename, 'r') as input: for line in input: yield line class Transformer: def transform(self, line): if not line.startswith('#'): parts = line.split(':') return { 'login_name': parts[0], 'password': parts[1], 'uid': parts[2], 'gid': parts[3], 'user_name': parts[4], 'home_dir': parts[5], 'shell': parts[6] }
independent of the other you can change it without affecting the other parts You can test each module in total isolation No matter what you do, as long as the input/output structures don’t change you can modify code to your hearts content Each module is easily reused You don’t have to think nearly as hard about things (because they are simple and focused)
how many methods should a class have? Fewer arguments to methods/functions How many is too many? What do you do about that? Test are considerably easier to write
https://youtu.be/Gt0M_OHKhQE Uncle Bob - The Single Responsibility Principle https://blog.8thlight.com/uncle-bob/2014/05/08/ SingleReponsibilityPrinciple.html DZone - The Single Responsibility Principle https://dzone.com/articles/single-responsibility