开发者

What is an elegant way to abstract functions - not objects?

开发者 https://www.devze.com 2023-03-05 07:55 出处:网络
I have a function that logs into a sensor via telnet/pexp开发者_高级运维ect and acts as a data collector.

I have a function that logs into a sensor via telnet/pexp开发者_高级运维ect and acts as a data collector.

I don't want to rewrite the part that logs in, grabs the data, and parses out relevant output from it (pexpect). However, I need to do different things with this code and the data it gathers

For example, I may need to:

  • Time until the first reading is returned

  • Take the average of a varying number of sensor readings

  • Return the status (which is one piece of data) or return the sensor reading (which is a separate piece of data) from the output

Ultimately, it should still login and parse output the same and I want to use one code block for that part.

Higher up in the code, it's being used instantaneously. When I call it, I know what type of data I need to gather and that's that. Constructing objects is too clumsy.

My usage has outstripped adding more arguments to a single function.

Any ideas?


This is such a common situation, I'm surprised you haven't already done what everyone else does.

Refactor your function to decompose it into smaller functions.

Functions are objects, and can be passed as arguments to other functions.

def step1(): 
    whatever

def step2(): 
    whatever

def step2_alternative():
    whatever

def original( args ):
    step1()
    step2()

def revised( args, step2_choice ):
    step1()
    step2_choice()

Now you can do this.

revised( step2 )
revised( step2_alternative )

It's just OO programming with function objects.


Could you pass a data processing function to the function you described as an argument?

That may be more or less elegant, depending on your taste. (Forgive me: I know nothing about pexpect, and I may even have misunderstood your question!)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号