Day23 非原创 Alternative code styl

2019-04-25  本文已影响0人  JSleefat

There are many good, neat code style guides. These lay out standards for things like indentation, whitespace, line length, naming conventions, and more. Some well-known examples are:

Ok, so there are also plenty of information, history, tools, etc. for popular styles. Enough on them. Let’s look at some lesser known alternatives!

DISCLAIMER: use the styles that follow at your own risk.

Bournegol

Let’s begin with the most (im)famous alternate code styles! Bournegol is the C coding style used by Steven Bourne in the sh source code. It makes C look more like Algol, which some would argue has a nicer syntax. Below is a snippet from main.c(source):

  /* command loop */
  LOOP  tdystak(0);
    stakchk(); /* may reduce sbrk */
    exitset();
    IF (flags&prompt) ANDF standin->fstak==0 ANDF !eof
    THEN  IF mailnod.namval
          ANDF stat(mailnod.namval,&statb)>=0 ANDF statb.st_size
          ANDF (statb.st_mtime != mailtime)
          ANDF mailtime
      THEN  prs(mailmsg)
      FI
      mailtime=statb.st_mtime;
      prs(ps1nod.namval); alarm(TIMEOUT); flags |= waiting;
    FI

    trapnote=0; peekc=readc();
    IF eof
    THEN  return;
    FI
    alarm(0); flags &= ~waiting;
    execute(cmd(NL,MTFLG),0);
    eof |= (flags&oneflg);
  POOL

Look no braces! This is a really nice example of how the C preprocesser can be used to seemingly modify C’s syntax. All the sh source files can be found here for your viewing pleasure.

For anyone wishing to use this code style in their own code, the macros that make it possible are located in mac.h. Extract below:

#define LOCAL  static
#define PROC  extern
#define TYPE  typedef
#define STRUCT  TYPE struct
#define UNION  TYPE union
#define REG  register

#define IF  if(
#define THEN  ){
#define ELSE  } else {
#define ELIF  } else if (
#define FI  ;}

For other posts about Bournegol, see here and here.

Poetry

Code can be an art form. While function is generally put before form in code, it doesn’t hurt to break the trend and produce source code that is in itself beautiful.

In it’s simplest form, code poetry can be code with alignment used to produce a poetry-like effect. For example this tweet by @mraleph:

new innovative way to format code: programming is an art, and each program is a poem. pic.twitter.com/Sf2MsnQlOM

— Vyacheslav Egorov (@mraleph) 13 septembre 2018

Another example with centre alignment applied to a project of mine (c-calculator):

    // splits the expression into tokens (a makeshift linked list structure)
         // returns a pointer to the list, or NULL if tokenizing failed
      linked_list * tokenize(char exp[], const double * const last_answer,
                         const double * const memory) {

                               // setup variables
                 linked_list * tokens_head = new_linked_list();
                bool first = true; // true while at first token
                         token previous = {NOTHING, 0};
                        token temp_token = {NOTHING, 0};

                 // insert a token if there was a last answer,
                    //  and the first thing is an operator.
                           if (last_answer != NULL) {
                               switch (exp[0]) {
                                   case '-':
                                   case '+':
                                   case '*':
                                   case '/':
                                   case '^':
                                   case '#':
                           temp_token.type = LITERAL;
                        temp_token.value = *last_answer;
                 previous = add_token(tokens_head, temp_token);
                                 first = false;
                                     break;
                                       }
                                       }

Quite eye-pleasing! The good news is that this style is really easy to apply automatically in Vim. Assuming the standard 80 character line limit is adhered to, one can simply run :%center 40 to format the entire file.

Poetry code styling doesn’t stop there though! One can incorporate more poetic elements to produce real works of art.code-poetry.com contains some masterpieces.

Fibonacci indentation

Indentation has always been a hot topic. Tabs or spaces? Two, four, or even eight spaces? Let’s add a new option! Welcome to Fibonacci indentation.

The Fibonacci indenting style was promoted on Twitter by @RichardWestenra:

Personally, I prefer to increase the spacing for each successive indent according to the Fibbonaci sequence: pic.twitter.com/x5lPd4M5Mk

— Wicked Rich of the Westenra (@RichardWestenra) 16 août 2016

This style is especially nice when the code is deeply nested, producing a nice curved effect.

There is even a vim plugin for automatic Fibonacci indenting fun! Below is a screencast from the repository showing just how neat this is.

example of fib indentation in vim

Braces -> Python style

Python has a clean syntax, without all those messy semicolons and braces. If your eyeballs can’t handle looking at all the extra punctuation, this code style is for you.

This is a simple style: just add spaces before syntax ending the lines until they surpass the maximum allowed line length. The source for this as far as I can tell is a Reddit post by u/b3n, which demonstrates that even Java can look pretty with the right style.

Here is a quick example of some Rust code with this style. Rust is a syntax heavy language and it is immediately evident that the code is now cleaner and easier to read. That is, if you ignore everything past the 80 character line length limit… ;)

fn run() -> io::Result<()>                                                      {
    let mut args = env::args()                                                  ;

    let _procname = args.next()                                                 ;

    let ifname: String = match args.next()                                      {
        Some(arg) => match arg.as_ref()                                         {
            "--help" | "-h"                                                     =>{
                help()                                                          ;
                return Ok(())                                                   ;}
            s                                                                   =>
              s.to_owned()                                                      ,},
        None                                                                    =>{
            ".".to_owned()                                                      }};

    let ft = fs::metadata(&ifname)?.file_type()                                 ;

    if ft.is_dir()                                                              {
        process_dir(ifname)                                                     }
    else                                                                        {
        process_file(ifname)                                                    }}

Obfuscation

I guess this could legitimately be called a style here. Interestingly, it is probably by far the most widely used code style. Much production Javascript is minified, becoming thoroughly obfuscated in the process. Of course, the minified output isn’t supposed to be directly edited by humans. Unless you’re into reverse engineering.

Obfuscation as a style is also used by competitors in contests such as the International Obfuscated C Code Contest. For example, can you guess what this code does?

char O,o[];main(l){for(;~l;O||puts(o))O=(O[o]=~(l=getchar())?4<(4^l>>5)?l:46:0)?-~O&printf("%02x ",l)*5:!O;}

This won the Best one-liner award in IOCCC 2018. (source) The other entries are pretty amazing and worth checking out, especially if you are a C programmer.

Conclusion

They say constraints help creativity. In all seriousness, these styles are awesome examples of truly creative works built within the constraints of programming language syntax and semantics. The results can be useful, pretty, amusing, or downright terrifying.

原文:Alternative code styles

上一篇下一篇

猜你喜欢

热点阅读