一般编程问题。何时使用OOP? [英] General programming question. When to use OOP?

查看:71
本文介绍了一般编程问题。何时使用OOP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序需要做2件事。


  1. 从网页中提取内容。

  2. 网页内容。


然而,有很多网页,比如Twitter和Facebook。 b
$ b

我应该这样做吗?

  def facebookExtract():
code here
def twitterExtract():
code here
def myspaceExtract():
code here
def facebookProcess():
code here
def twitterProcess():
code here
def myspaceProcess():
code here

或者,我应该有某种课程吗?什么时候推荐使用类,什么时候推荐使用函数?

我最喜欢的经验法则是:if你有疑问(不言而喻的假设:你是一个合理的人,而不是一个狂热者;-),制作和使用一些类。我经常发现自己将最初编写为简单函数的代码重构为类 - 例如,任何时候简单函数与对方进行通信的最佳方式都是使用全局变量,这是一种代码异味,强烈暗示系统的因子是不是很好 - 而且经常重构OOP方式是一个合理的解决方法。



Python是多范式的,但它的中心范例是OOP(很像,C ++)。当程序或功能方法(可能通过发生器& c)对于系统的某个部分是最佳的时候,这通常是突出的 - 例如,静态函数也是代码气味,并且如果你的类有相当多的那些这是一个暗示重构的东西,以避免这一要求。

因此,假设你有丰富的Python所提供的范例的掌握 - 如果你仍然有疑问,这表明你可能想要为你的系统的那个部分使用OOP!仅仅因为Python支持OOP的程度比它支持函数式编程等更多。



从我的骨骼代码来看,我认为每个提取/处理对都属于并可能需要沟通状态,所以一小部分提取和处理方法类似乎是天作之合。


My program needs to do 2 things.

  1. Extract stuff from a webpage.

  2. Do stuff with a webpage.

However, there are many webpages, such as Twitter and Facebook.

should I do this?

def facebookExtract():
    code here
def twitterExtract():
    code here
def myspaceExtract():
    code here
def facebookProcess():
    code here
def twitterProcess():
    code here
def myspaceProcess():
    code here

Or, should I have some sort of class? When is it recommended to use classes, and when is it recommend to just use functions?

解决方案

My favorite rule of thumb: if you're in doubt (unspoken assumption: "and you're a reasonable person rather than a fanatic";-), make and use some classes. I've often found myself refactoring code originally written as simple functions into classes -- for example, any time the simple functions' best way to communicating with each others is with globals, that's a code smell, a strong hint that the system's factoring is not really good -- and often refactoring the OOP way is a reasonable fix for that.

Python is multi-paradigm, but its central paradigm is OOP (much like, say, C++). When a procedural or functional approach (maybe through generators &c) is optimal for some part of the system, that generally stands out -- for example, static functions are also a code smell, and if your classes have any substantial amount of those THAT is a hint to refactor things to avoid that requirement.

So, assuming you have a rich grasp of all the paradigms Python affords -- if you're STILL in doubt, that suggests you probably want to go OOP for that part of your system! Just because Python supports OOP even more wholly than it supports functional programming and the like.

From your very skeletal code, it seems to me that each extract/process pair belongs together and probably needs to communicate state, so a small set of classes with extraction and processing methods seems a natural fit.

这篇关于一般编程问题。何时使用OOP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆