开发者

When to use methods and objects [closed]

Closed. This questi开发者_开发技巧on is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 8 years ago.

Improve this question

This might be a duplicate, but as I haven't seen anything hopefully it isn't. Basically, I've never seen a good rule-of-thumb for when to split a chunk of code into separate methods and objects. Does anyone have any good rules they found work well?


If a method doesn't fit on a page, it's too big. :-)

That's not an excuse to use a really small font or use a really big monitor

Go and read;

  • Refactroring : http://www.amazon.co.uk/Refactoring-Improving-Design-Existing-Technology/dp/0201485672/
  • Working with legacy code : http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052/

Although they talk about how to deal with what you already have, if you read them and learn from them you can aim not to create lagacy code to start with!


I've found this article (butunclebob.com, S.O.L.I.D. principles for OOP) to be enlightening for designing boundaries and hierarchies of classes. Although it is mostly common sense, putting a name to the goals you want to achieve helps until you gain a feel for "good"ness of a design through experience.


Disclaimer: I have nothing against OOP, quite the opposite. The following is just a personal opinion

In general I agree with the other answers and I would also try to break up code into methods whenever I "feel" it necessary.

Nevertheless, OOP is a method, a tool if you want to call it. While adopting OOP techniques is very powerful, there are still some situations in which other approaches just fit better.

A simple

echo "Hello World!"

might be faster/better/easier than

class HelloWorld {

    private String text = null;

    public HelloWorld() {
        this.text = "Hello World";
    }

    public void print() {
        echo this.text;
    }

}

(Compare the exaggerated example hello world in pattern)


The rule of thumb goes like this:

Q: Should I split this into methods and objects?

A: Yes.


From an OO perspective, all code should be written as objects and methods. The currency of OOP is objects. Now, if you have a large class and are wondering how to break it up because it violates single responsibility, the rule of thumb is to encapsulate what varies.


A class should be designed to have one primary purpose. Ie. Keep the classes simple and unambiguous.

When deciding on the methods, you should have two things in mind. Focus on a clear interface for the class, and create testable methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜