Search code examples
design-patternsfunctioncode-readability

Patterns for declaring functions for greater readability


In C++ functions needed to be declared before they were called. This could be worked around with function signatures but for the most part this is no longer required in newer programming languages, C#, Python, ETC.

However, while reading other peoples, code and when having to structure functions in a class, I find that I miss the consistency that existed in C++.

What patterns exist to declare/order function while maintaining readability and understanding about the structure of your code?

Edit 1


Here is an rough example.

class A
{
  private FunkB()
  {
    ...
  }

  private FunkC()
  {
    ...
  }

  public FunkA()
  {
    FunkB();
    FunkC();
  }

  public FunkD()
  {
    FunkC();
    ...
  }
}

v.s.

class A
{
  public FunkA()
  {
    FunkB();
    FunkC();
  }

  private FunkB()
  {
    ...
  }

  private FunkC()
  {
    ...
  }

  public FunkD()
  {
    FunkC();
    ...
  }
}

Edit 2


This would be a guideline for writing code regardless of editors. Newer editors have excellent "go to definition" features and book marks help out with this too. However I'm interested in a editor independent pattern.


Solution

  • When reading the code of a method in isolation, you want to understand the intent of the method. If the level of abstraction inside the method is good, and the names of all other called methods make sense in its context, you won't need to know them in order to understand the code. You'll treat them like black boxes.

    Some principles that help achieve greater readability in the small:

    Single Level of Abstraction Principle

    Single Resposibility Principle (pdf)

    Composed Method

    And don't forget, always use good names! That's why your example is not good for this discussion.