집에서 동영상으로 코딩 가이드에 대한 강좌를 보는 과정중에 재미난 내용이 있어 python
을 사용해서 분석해 보았습니다.
해당 동영상에 나온 내용은 빠른 시일내에 블로그에 정리해서 올릴려고 합니다. 좋은 내용들이 많아서…
프로그래밍 가이드에는 왜 한 라인에 80자만 사용하라고 하는 것인가?
동영상 강좌에 나온 내용으로는 예전 환경은 콘솔 + 작은 모니터 + IDE없는
이어서 한 줄에 80라인을 넘기면 보기가 어려워서 그렇다고 설명을 하였습니다.
그러면서 나온게 최근에 사용되는 오픈소스 프로젝트인 JUnit
, Ant
와 몇몇가지를 예를 들어 최근에는 80자가 넘는 소스들도 많이 있다고 하였습니다.
그렇지만 한 줄에 너무 많은 글자를 쓰면 가독성이 떨어진다고 단지 좌우스크롤이 안될 정도로만 하라고 설명하셨습니다.
분석
그렇다면 제가 자주 사용하는 라이브러리들은 한 줄에 어느정도의 평균 글자수 와 한 파일에 몇라인이 포함되어 있는지 확인을 해보았습니다.
분석은 소스 폴더에 포함된 java
로 확장자를 가지는 파일을 대상으로 하였습니다.
[분석도구]
- python 2.7
- matplotlib
- OSX(Yosemite)
[분석대상]
- commons-lang
- commons-net
- Ant
- Open JDK7
결과
결과는 어느정도 예상한대로 commons-lang 과 commons-net의 경우는 평균 100자를 넘지 않는 수치가 나왔습니다. 그렇지만 의외로 open-jdk7에서 평균 400자를 넘는 파일이 있어 확인을 해보니 그럴만한 이유가 있었습니다. 기타
참조
commons-lang

commons-net

open-jdk7

분석 소스
import os
import fnmatch
import matplotlib.pyplot as plt
class FileVO:
def __init__(self, filename, file_size, line_of_file, avg_char):
self.file_size = file_size
self.line_of_file = line_of_file
self.avg_char = avg_char
self.filename = filename
def __str__(self):
return '%-20s / size=%5d, line=%5d, chars(AVG)=%5d' % (self.filename, self.file_size, self.line_of_file, self.avg_char)
if __name__=='__main__':
matches = []
source_path = '/Users/coozplz/Downloads/sources/src-jdk'
for root, dirnames, filenames in os.walk(source_path):
for filename in fnmatch.filter(filenames, '*.java'):
found_file = os.path.join(root, filename)
file_size = os.path.getsize(found_file)
js_file = open(found_file)
lines = js_file.readlines()
sum_of_chars = 0
for line in lines:
sum_of_chars += len(line)
vo = FileVO(filename, file_size, len(lines), sum_of_chars / len(lines))
# print vo
matches.append(vo)
js_file.close()
plt.title("%s(%d files)" % (source_path, len(matches)))
for match_file in matches:
plt.scatter(match_file.line_of_file, match_file.avg_char)
plt.ylabel("Average chars of line")
plt.xlabel("Lines per file")
plt.grid()
plt.show()
기타
평균글자수가 가장 많은 파일 : launcher.java
아래와 같은 코딩이 되어 있어 평균 글자수 길이가 비약적으로 많이 나오는거 같습니다. 나머지 파일들도 마찬가지라고 생각합니다.
소스코드
package sun.launcher.resources;
import java.util.ListResourceBundle;
public final class launcher extends ListResourceBundle {
protected final Object[][] getContents() {
return new Object[][] {
{ "java.launcher.X.macosx.usage", "nThe following options are Mac OS X specific:n -XstartOnFirstThreadn run the main() method on the first (AppKit) threadn -Xdock:name="n override default application name displayed in dockn -Xdock:icon=n override default icon displayed in docknn" },
{ "java.launcher.X.usage", " -Xmixed mixed mode execution (default)n -Xint interpreted mode execution onlyn -Xbootclasspath:n set search path for bootstrap classes and resourcesn -Xbootclasspath/a:n append to end of bootstrap class pathn -Xbootclasspath/p:n prepend in front of bootstrap class pathn -Xdiag show additional diagnostic messagesn -Xnoclassgc disable class garbage collectionn -Xincgc enable incremental garbage collectionn -Xloggc: log GC status to a file with time stampsn -Xbatch disable background compilationn -Xms set initial Java heap sizen -Xmx set maximum Java heap sizen -Xss set java thread stack sizen -Xprof output cpu profiling datan -Xfuture enable strictest checks, anticipating future defaultn -Xrs reduce use of OS signals by Java/VM (see documentation)n -Xcheck:jni perform additional checks for JNI functionsn -Xshare:off do not attempt to use shared class datan -Xshare:auto use shared class data if possible (default)n -Xshare:on require using shared class data, otherwise fail.n -XshowSettings show all settings and continuen -XshowSettings:alln show all settings and continuen -XshowSettings:vm show all vm related settings and continuen -XshowSettings:propertiesn show all property settings and continuen -XshowSettings:localen show all locale related settings and continuennThe -X options are non-standard and subject to change without notice.n" },
{ "java.launcher.cls.error1", "Error: Could not find or load main class {0}" },
{ "java.launcher.cls.error2", "Error: Main method is not {0} in class {1}, please define the main method as:n public static void main(String[] args)" },
{ "java.launcher.cls.error3", "Error: Main method must return a value of type void in class {0}, please ndefine the main method as:n public static void main(String[] args)" },
{ "java.launcher.cls.error4", "Error: Main method not found in class {0}, please define the main method as:n public static void main(String[] args)" },
{ "java.launcher.ergo.message1", " The default VM is {0}" },
{ "java.launcher.ergo.message2", " because you are running on a server-class machine.n" },
{ "java.launcher.init.error", "initialization error" },
{ "java.launcher.jar.error1", "Error: An unexpected error occurred while trying to open file {0}" },
{ "java.launcher.jar.error2", "manifest not found in {0}" },
{ "java.launcher.jar.error3", "no main manifest attribute, in {0}" },
{ "java.launcher.opt.datamodel", " -d{0}t use a {0}-bit data model if availablen" },
{ "java.launcher.opt.footer", " -cp n -classpath n A {0} separated list of directories, JAR archives,n and ZIP archives to search for class files.n -D=n set a system propertyn -verbose:[class|gc|jni]n enable verbose outputn -version print product version and exitn -version:n require the specified version to runn -showversion print product version and continuen -jre-restrict-search | -no-jre-restrict-searchn include/exclude user private JREs in the version searchn -? -help print this help messagen -X print help on non-standard optionsn -ea[:...|:]n -enableassertions[:...|:]n enable assertions with specified granularityn -da[:...|:]n -disableassertions[:...|:]n disable assertions with specified granularityn -esa | -enablesystemassertionsn enable system assertionsn -dsa | -disablesystemassertionsn disable system assertionsn -agentlib:[=]n load native agent library , e.g. -agentlib:hprofn see also, -agentlib:jdwp=help and -agentlib:hprof=helpn -agentpath:[=]n load native agent library by full pathnamen -javaagent:[=]n load Java programming language agent, see java.lang.instrumentn -splash:n show splash screen with specified imagenSee http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details." },
{ "java.launcher.opt.header", "Usage: {0} [-options] class [args...]n (to execute a class)n or {0} [-options] -jar jarfile [args...]n (to execute a jar file)nwhere options include:n" },
{ "java.launcher.opt.hotspot", " {0}t is a synonym for the "{1}" VM [deprecated]n" },
{ "java.launcher.opt.vmselect", " {0}t to select the "{1}" VMn" },
};
}
}